sqlite3.c revision 305002
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.14.1.  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.1"
384#define SQLITE_VERSION_NUMBER 3014001
385#define SQLITE_SOURCE_ID      "2016-08-11 18:53:32 a12d8059770df4bca59e321c266410344242bf7b"
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( int nPage = 0; )  /* To assert pCache->nPage is correct */
45002  unsigned int h, iStop;
45003  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45004  assert( pCache->iMaxKey >= iLimit );
45005  assert( pCache->nHash > 0 );
45006  if( pCache->iMaxKey - iLimit < pCache->nHash ){
45007    /* If we are just shaving the last few pages off the end of the
45008    ** cache, then there is no point in scanning the entire hash table.
45009    ** Only scan those hash slots that might contain pages that need to
45010    ** be removed. */
45011    h = iLimit % pCache->nHash;
45012    iStop = pCache->iMaxKey % pCache->nHash;
45013    TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
45014  }else{
45015    /* This is the general case where many pages are being removed.
45016    ** It is necessary to scan the entire hash table */
45017    h = pCache->nHash/2;
45018    iStop = h - 1;
45019  }
45020  for(;;){
45021    PgHdr1 **pp;
45022    PgHdr1 *pPage;
45023    assert( h<pCache->nHash );
45024    pp = &pCache->apHash[h];
45025    while( (pPage = *pp)!=0 ){
45026      if( pPage->iKey>=iLimit ){
45027        pCache->nPage--;
45028        *pp = pPage->pNext;
45029        if( !pPage->isPinned ) pcache1PinPage(pPage);
45030        pcache1FreePage(pPage);
45031      }else{
45032        pp = &pPage->pNext;
45033        TESTONLY( if( nPage>=0 ) nPage++; )
45034      }
45035    }
45036    if( h==iStop ) break;
45037    h = (h+1) % pCache->nHash;
45038  }
45039  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
45040}
45041
45042/******************************************************************************/
45043/******** sqlite3_pcache Methods **********************************************/
45044
45045/*
45046** Implementation of the sqlite3_pcache.xInit method.
45047*/
45048static int pcache1Init(void *NotUsed){
45049  UNUSED_PARAMETER(NotUsed);
45050  assert( pcache1.isInit==0 );
45051  memset(&pcache1, 0, sizeof(pcache1));
45052
45053
45054  /*
45055  ** The pcache1.separateCache variable is true if each PCache has its own
45056  ** private PGroup (mode-1).  pcache1.separateCache is false if the single
45057  ** PGroup in pcache1.grp is used for all page caches (mode-2).
45058  **
45059  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
45060  **
45061  **   *  Use a unified cache in single-threaded applications that have
45062  **      configured a start-time buffer for use as page-cache memory using
45063  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
45064  **      pBuf argument.
45065  **
45066  **   *  Otherwise use separate caches (mode-1)
45067  */
45068#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45069  pcache1.separateCache = 0;
45070#elif SQLITE_THREADSAFE
45071  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
45072                          || sqlite3GlobalConfig.bCoreMutex>0;
45073#else
45074  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
45075#endif
45076
45077#if SQLITE_THREADSAFE
45078  if( sqlite3GlobalConfig.bCoreMutex ){
45079    pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
45080    pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
45081  }
45082#endif
45083  if( pcache1.separateCache
45084   && sqlite3GlobalConfig.nPage!=0
45085   && sqlite3GlobalConfig.pPage==0
45086  ){
45087    pcache1.nInitPage = sqlite3GlobalConfig.nPage;
45088  }else{
45089    pcache1.nInitPage = 0;
45090  }
45091  pcache1.grp.mxPinned = 10;
45092  pcache1.isInit = 1;
45093  return SQLITE_OK;
45094}
45095
45096/*
45097** Implementation of the sqlite3_pcache.xShutdown method.
45098** Note that the static mutex allocated in xInit does
45099** not need to be freed.
45100*/
45101static void pcache1Shutdown(void *NotUsed){
45102  UNUSED_PARAMETER(NotUsed);
45103  assert( pcache1.isInit!=0 );
45104  memset(&pcache1, 0, sizeof(pcache1));
45105}
45106
45107/* forward declaration */
45108static void pcache1Destroy(sqlite3_pcache *p);
45109
45110/*
45111** Implementation of the sqlite3_pcache.xCreate method.
45112**
45113** Allocate a new cache.
45114*/
45115static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
45116  PCache1 *pCache;      /* The newly created page cache */
45117  PGroup *pGroup;       /* The group the new page cache will belong to */
45118  int sz;               /* Bytes of memory required to allocate the new cache */
45119
45120  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
45121  assert( szExtra < 300 );
45122
45123  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
45124  pCache = (PCache1 *)sqlite3MallocZero(sz);
45125  if( pCache ){
45126    if( pcache1.separateCache ){
45127      pGroup = (PGroup*)&pCache[1];
45128      pGroup->mxPinned = 10;
45129    }else{
45130      pGroup = &pcache1.grp;
45131    }
45132    if( pGroup->lru.isAnchor==0 ){
45133      pGroup->lru.isAnchor = 1;
45134      pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
45135    }
45136    pCache->pGroup = pGroup;
45137    pCache->szPage = szPage;
45138    pCache->szExtra = szExtra;
45139    pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
45140    pCache->bPurgeable = (bPurgeable ? 1 : 0);
45141    pcache1EnterMutex(pGroup);
45142    pcache1ResizeHash(pCache);
45143    if( bPurgeable ){
45144      pCache->nMin = 10;
45145      pGroup->nMinPage += pCache->nMin;
45146      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45147    }
45148    pcache1LeaveMutex(pGroup);
45149    if( pCache->nHash==0 ){
45150      pcache1Destroy((sqlite3_pcache*)pCache);
45151      pCache = 0;
45152    }
45153  }
45154  return (sqlite3_pcache *)pCache;
45155}
45156
45157/*
45158** Implementation of the sqlite3_pcache.xCachesize method.
45159**
45160** Configure the cache_size limit for a cache.
45161*/
45162static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
45163  PCache1 *pCache = (PCache1 *)p;
45164  if( pCache->bPurgeable ){
45165    PGroup *pGroup = pCache->pGroup;
45166    pcache1EnterMutex(pGroup);
45167    pGroup->nMaxPage += (nMax - pCache->nMax);
45168    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45169    pCache->nMax = nMax;
45170    pCache->n90pct = pCache->nMax*9/10;
45171    pcache1EnforceMaxPage(pCache);
45172    pcache1LeaveMutex(pGroup);
45173  }
45174}
45175
45176/*
45177** Implementation of the sqlite3_pcache.xShrink method.
45178**
45179** Free up as much memory as possible.
45180*/
45181static void pcache1Shrink(sqlite3_pcache *p){
45182  PCache1 *pCache = (PCache1*)p;
45183  if( pCache->bPurgeable ){
45184    PGroup *pGroup = pCache->pGroup;
45185    int savedMaxPage;
45186    pcache1EnterMutex(pGroup);
45187    savedMaxPage = pGroup->nMaxPage;
45188    pGroup->nMaxPage = 0;
45189    pcache1EnforceMaxPage(pCache);
45190    pGroup->nMaxPage = savedMaxPage;
45191    pcache1LeaveMutex(pGroup);
45192  }
45193}
45194
45195/*
45196** Implementation of the sqlite3_pcache.xPagecount method.
45197*/
45198static int pcache1Pagecount(sqlite3_pcache *p){
45199  int n;
45200  PCache1 *pCache = (PCache1*)p;
45201  pcache1EnterMutex(pCache->pGroup);
45202  n = pCache->nPage;
45203  pcache1LeaveMutex(pCache->pGroup);
45204  return n;
45205}
45206
45207
45208/*
45209** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
45210** in the header of the pcache1Fetch() procedure.
45211**
45212** This steps are broken out into a separate procedure because they are
45213** usually not needed, and by avoiding the stack initialization required
45214** for these steps, the main pcache1Fetch() procedure can run faster.
45215*/
45216static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
45217  PCache1 *pCache,
45218  unsigned int iKey,
45219  int createFlag
45220){
45221  unsigned int nPinned;
45222  PGroup *pGroup = pCache->pGroup;
45223  PgHdr1 *pPage = 0;
45224
45225  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
45226  assert( pCache->nPage >= pCache->nRecyclable );
45227  nPinned = pCache->nPage - pCache->nRecyclable;
45228  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
45229  assert( pCache->n90pct == pCache->nMax*9/10 );
45230  if( createFlag==1 && (
45231        nPinned>=pGroup->mxPinned
45232     || nPinned>=pCache->n90pct
45233     || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
45234  )){
45235    return 0;
45236  }
45237
45238  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
45239  assert( pCache->nHash>0 && pCache->apHash );
45240
45241  /* Step 4. Try to recycle a page. */
45242  if( pCache->bPurgeable
45243   && !pGroup->lru.pLruPrev->isAnchor
45244   && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
45245  ){
45246    PCache1 *pOther;
45247    pPage = pGroup->lru.pLruPrev;
45248    assert( pPage->isPinned==0 );
45249    pcache1RemoveFromHash(pPage, 0);
45250    pcache1PinPage(pPage);
45251    pOther = pPage->pCache;
45252    if( pOther->szAlloc != pCache->szAlloc ){
45253      pcache1FreePage(pPage);
45254      pPage = 0;
45255    }else{
45256      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
45257    }
45258  }
45259
45260  /* Step 5. If a usable page buffer has still not been found,
45261  ** attempt to allocate a new one.
45262  */
45263  if( !pPage ){
45264    pPage = pcache1AllocPage(pCache, createFlag==1);
45265  }
45266
45267  if( pPage ){
45268    unsigned int h = iKey % pCache->nHash;
45269    pCache->nPage++;
45270    pPage->iKey = iKey;
45271    pPage->pNext = pCache->apHash[h];
45272    pPage->pCache = pCache;
45273    pPage->pLruPrev = 0;
45274    pPage->pLruNext = 0;
45275    pPage->isPinned = 1;
45276    *(void **)pPage->page.pExtra = 0;
45277    pCache->apHash[h] = pPage;
45278    if( iKey>pCache->iMaxKey ){
45279      pCache->iMaxKey = iKey;
45280    }
45281  }
45282  return pPage;
45283}
45284
45285/*
45286** Implementation of the sqlite3_pcache.xFetch method.
45287**
45288** Fetch a page by key value.
45289**
45290** Whether or not a new page may be allocated by this function depends on
45291** the value of the createFlag argument.  0 means do not allocate a new
45292** page.  1 means allocate a new page if space is easily available.  2
45293** means to try really hard to allocate a new page.
45294**
45295** For a non-purgeable cache (a cache used as the storage for an in-memory
45296** database) there is really no difference between createFlag 1 and 2.  So
45297** the calling function (pcache.c) will never have a createFlag of 1 on
45298** a non-purgeable cache.
45299**
45300** There are three different approaches to obtaining space for a page,
45301** depending on the value of parameter createFlag (which may be 0, 1 or 2).
45302**
45303**   1. Regardless of the value of createFlag, the cache is searched for a
45304**      copy of the requested page. If one is found, it is returned.
45305**
45306**   2. If createFlag==0 and the page is not already in the cache, NULL is
45307**      returned.
45308**
45309**   3. If createFlag is 1, and the page is not already in the cache, then
45310**      return NULL (do not allocate a new page) if any of the following
45311**      conditions are true:
45312**
45313**       (a) the number of pages pinned by the cache is greater than
45314**           PCache1.nMax, or
45315**
45316**       (b) the number of pages pinned by the cache is greater than
45317**           the sum of nMax for all purgeable caches, less the sum of
45318**           nMin for all other purgeable caches, or
45319**
45320**   4. If none of the first three conditions apply and the cache is marked
45321**      as purgeable, and if one of the following is true:
45322**
45323**       (a) The number of pages allocated for the cache is already
45324**           PCache1.nMax, or
45325**
45326**       (b) The number of pages allocated for all purgeable caches is
45327**           already equal to or greater than the sum of nMax for all
45328**           purgeable caches,
45329**
45330**       (c) The system is under memory pressure and wants to avoid
45331**           unnecessary pages cache entry allocations
45332**
45333**      then attempt to recycle a page from the LRU list. If it is the right
45334**      size, return the recycled buffer. Otherwise, free the buffer and
45335**      proceed to step 5.
45336**
45337**   5. Otherwise, allocate and return a new page buffer.
45338**
45339** There are two versions of this routine.  pcache1FetchWithMutex() is
45340** the general case.  pcache1FetchNoMutex() is a faster implementation for
45341** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
45342** invokes the appropriate routine.
45343*/
45344static PgHdr1 *pcache1FetchNoMutex(
45345  sqlite3_pcache *p,
45346  unsigned int iKey,
45347  int createFlag
45348){
45349  PCache1 *pCache = (PCache1 *)p;
45350  PgHdr1 *pPage = 0;
45351
45352  /* Step 1: Search the hash table for an existing entry. */
45353  pPage = pCache->apHash[iKey % pCache->nHash];
45354  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
45355
45356  /* Step 2: If the page was found in the hash table, then return it.
45357  ** If the page was not in the hash table and createFlag is 0, abort.
45358  ** Otherwise (page not in hash and createFlag!=0) continue with
45359  ** subsequent steps to try to create the page. */
45360  if( pPage ){
45361    if( !pPage->isPinned ){
45362      return pcache1PinPage(pPage);
45363    }else{
45364      return pPage;
45365    }
45366  }else if( createFlag ){
45367    /* Steps 3, 4, and 5 implemented by this subroutine */
45368    return pcache1FetchStage2(pCache, iKey, createFlag);
45369  }else{
45370    return 0;
45371  }
45372}
45373#if PCACHE1_MIGHT_USE_GROUP_MUTEX
45374static PgHdr1 *pcache1FetchWithMutex(
45375  sqlite3_pcache *p,
45376  unsigned int iKey,
45377  int createFlag
45378){
45379  PCache1 *pCache = (PCache1 *)p;
45380  PgHdr1 *pPage;
45381
45382  pcache1EnterMutex(pCache->pGroup);
45383  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
45384  assert( pPage==0 || pCache->iMaxKey>=iKey );
45385  pcache1LeaveMutex(pCache->pGroup);
45386  return pPage;
45387}
45388#endif
45389static sqlite3_pcache_page *pcache1Fetch(
45390  sqlite3_pcache *p,
45391  unsigned int iKey,
45392  int createFlag
45393){
45394#if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
45395  PCache1 *pCache = (PCache1 *)p;
45396#endif
45397
45398  assert( offsetof(PgHdr1,page)==0 );
45399  assert( pCache->bPurgeable || createFlag!=1 );
45400  assert( pCache->bPurgeable || pCache->nMin==0 );
45401  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
45402  assert( pCache->nMin==0 || pCache->bPurgeable );
45403  assert( pCache->nHash>0 );
45404#if PCACHE1_MIGHT_USE_GROUP_MUTEX
45405  if( pCache->pGroup->mutex ){
45406    return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
45407  }else
45408#endif
45409  {
45410    return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
45411  }
45412}
45413
45414
45415/*
45416** Implementation of the sqlite3_pcache.xUnpin method.
45417**
45418** Mark a page as unpinned (eligible for asynchronous recycling).
45419*/
45420static void pcache1Unpin(
45421  sqlite3_pcache *p,
45422  sqlite3_pcache_page *pPg,
45423  int reuseUnlikely
45424){
45425  PCache1 *pCache = (PCache1 *)p;
45426  PgHdr1 *pPage = (PgHdr1 *)pPg;
45427  PGroup *pGroup = pCache->pGroup;
45428
45429  assert( pPage->pCache==pCache );
45430  pcache1EnterMutex(pGroup);
45431
45432  /* It is an error to call this function if the page is already
45433  ** part of the PGroup LRU list.
45434  */
45435  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
45436  assert( pPage->isPinned==1 );
45437
45438  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
45439    pcache1RemoveFromHash(pPage, 1);
45440  }else{
45441    /* Add the page to the PGroup LRU list. */
45442    PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
45443    pPage->pLruPrev = &pGroup->lru;
45444    (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
45445    *ppFirst = pPage;
45446    pCache->nRecyclable++;
45447    pPage->isPinned = 0;
45448  }
45449
45450  pcache1LeaveMutex(pCache->pGroup);
45451}
45452
45453/*
45454** Implementation of the sqlite3_pcache.xRekey method.
45455*/
45456static void pcache1Rekey(
45457  sqlite3_pcache *p,
45458  sqlite3_pcache_page *pPg,
45459  unsigned int iOld,
45460  unsigned int iNew
45461){
45462  PCache1 *pCache = (PCache1 *)p;
45463  PgHdr1 *pPage = (PgHdr1 *)pPg;
45464  PgHdr1 **pp;
45465  unsigned int h;
45466  assert( pPage->iKey==iOld );
45467  assert( pPage->pCache==pCache );
45468
45469  pcache1EnterMutex(pCache->pGroup);
45470
45471  h = iOld%pCache->nHash;
45472  pp = &pCache->apHash[h];
45473  while( (*pp)!=pPage ){
45474    pp = &(*pp)->pNext;
45475  }
45476  *pp = pPage->pNext;
45477
45478  h = iNew%pCache->nHash;
45479  pPage->iKey = iNew;
45480  pPage->pNext = pCache->apHash[h];
45481  pCache->apHash[h] = pPage;
45482  if( iNew>pCache->iMaxKey ){
45483    pCache->iMaxKey = iNew;
45484  }
45485
45486  pcache1LeaveMutex(pCache->pGroup);
45487}
45488
45489/*
45490** Implementation of the sqlite3_pcache.xTruncate method.
45491**
45492** Discard all unpinned pages in the cache with a page number equal to
45493** or greater than parameter iLimit. Any pinned pages with a page number
45494** equal to or greater than iLimit are implicitly unpinned.
45495*/
45496static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
45497  PCache1 *pCache = (PCache1 *)p;
45498  pcache1EnterMutex(pCache->pGroup);
45499  if( iLimit<=pCache->iMaxKey ){
45500    pcache1TruncateUnsafe(pCache, iLimit);
45501    pCache->iMaxKey = iLimit-1;
45502  }
45503  pcache1LeaveMutex(pCache->pGroup);
45504}
45505
45506/*
45507** Implementation of the sqlite3_pcache.xDestroy method.
45508**
45509** Destroy a cache allocated using pcache1Create().
45510*/
45511static void pcache1Destroy(sqlite3_pcache *p){
45512  PCache1 *pCache = (PCache1 *)p;
45513  PGroup *pGroup = pCache->pGroup;
45514  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
45515  pcache1EnterMutex(pGroup);
45516  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
45517  assert( pGroup->nMaxPage >= pCache->nMax );
45518  pGroup->nMaxPage -= pCache->nMax;
45519  assert( pGroup->nMinPage >= pCache->nMin );
45520  pGroup->nMinPage -= pCache->nMin;
45521  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45522  pcache1EnforceMaxPage(pCache);
45523  pcache1LeaveMutex(pGroup);
45524  sqlite3_free(pCache->pBulk);
45525  sqlite3_free(pCache->apHash);
45526  sqlite3_free(pCache);
45527}
45528
45529/*
45530** This function is called during initialization (sqlite3_initialize()) to
45531** install the default pluggable cache module, assuming the user has not
45532** already provided an alternative.
45533*/
45534SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
45535  static const sqlite3_pcache_methods2 defaultMethods = {
45536    1,                       /* iVersion */
45537    0,                       /* pArg */
45538    pcache1Init,             /* xInit */
45539    pcache1Shutdown,         /* xShutdown */
45540    pcache1Create,           /* xCreate */
45541    pcache1Cachesize,        /* xCachesize */
45542    pcache1Pagecount,        /* xPagecount */
45543    pcache1Fetch,            /* xFetch */
45544    pcache1Unpin,            /* xUnpin */
45545    pcache1Rekey,            /* xRekey */
45546    pcache1Truncate,         /* xTruncate */
45547    pcache1Destroy,          /* xDestroy */
45548    pcache1Shrink            /* xShrink */
45549  };
45550  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
45551}
45552
45553/*
45554** Return the size of the header on each page of this PCACHE implementation.
45555*/
45556SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
45557
45558/*
45559** Return the global mutex used by this PCACHE implementation.  The
45560** sqlite3_status() routine needs access to this mutex.
45561*/
45562SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
45563  return pcache1.mutex;
45564}
45565
45566#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45567/*
45568** This function is called to free superfluous dynamically allocated memory
45569** held by the pager system. Memory in use by any SQLite pager allocated
45570** by the current thread may be sqlite3_free()ed.
45571**
45572** nReq is the number of bytes of memory required. Once this much has
45573** been released, the function returns. The return value is the total number
45574** of bytes of memory released.
45575*/
45576SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
45577  int nFree = 0;
45578  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45579  assert( sqlite3_mutex_notheld(pcache1.mutex) );
45580  if( sqlite3GlobalConfig.nPage==0 ){
45581    PgHdr1 *p;
45582    pcache1EnterMutex(&pcache1.grp);
45583    while( (nReq<0 || nFree<nReq)
45584       &&  (p=pcache1.grp.lru.pLruPrev)!=0
45585       &&  p->isAnchor==0
45586    ){
45587      nFree += pcache1MemSize(p->page.pBuf);
45588#ifdef SQLITE_PCACHE_SEPARATE_HEADER
45589      nFree += sqlite3MemSize(p);
45590#endif
45591      assert( p->isPinned==0 );
45592      pcache1PinPage(p);
45593      pcache1RemoveFromHash(p, 1);
45594    }
45595    pcache1LeaveMutex(&pcache1.grp);
45596  }
45597  return nFree;
45598}
45599#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45600
45601#ifdef SQLITE_TEST
45602/*
45603** This function is used by test procedures to inspect the internal state
45604** of the global cache.
45605*/
45606SQLITE_PRIVATE void sqlite3PcacheStats(
45607  int *pnCurrent,      /* OUT: Total number of pages cached */
45608  int *pnMax,          /* OUT: Global maximum cache size */
45609  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
45610  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
45611){
45612  PgHdr1 *p;
45613  int nRecyclable = 0;
45614  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
45615    assert( p->isPinned==0 );
45616    nRecyclable++;
45617  }
45618  *pnCurrent = pcache1.grp.nCurrentPage;
45619  *pnMax = (int)pcache1.grp.nMaxPage;
45620  *pnMin = (int)pcache1.grp.nMinPage;
45621  *pnRecyclable = nRecyclable;
45622}
45623#endif
45624
45625/************** End of pcache1.c *********************************************/
45626/************** Begin file rowset.c ******************************************/
45627/*
45628** 2008 December 3
45629**
45630** The author disclaims copyright to this source code.  In place of
45631** a legal notice, here is a blessing:
45632**
45633**    May you do good and not evil.
45634**    May you find forgiveness for yourself and forgive others.
45635**    May you share freely, never taking more than you give.
45636**
45637*************************************************************************
45638**
45639** This module implements an object we call a "RowSet".
45640**
45641** The RowSet object is a collection of rowids.  Rowids
45642** are inserted into the RowSet in an arbitrary order.  Inserts
45643** can be intermixed with tests to see if a given rowid has been
45644** previously inserted into the RowSet.
45645**
45646** After all inserts are finished, it is possible to extract the
45647** elements of the RowSet in sorted order.  Once this extraction
45648** process has started, no new elements may be inserted.
45649**
45650** Hence, the primitive operations for a RowSet are:
45651**
45652**    CREATE
45653**    INSERT
45654**    TEST
45655**    SMALLEST
45656**    DESTROY
45657**
45658** The CREATE and DESTROY primitives are the constructor and destructor,
45659** obviously.  The INSERT primitive adds a new element to the RowSet.
45660** TEST checks to see if an element is already in the RowSet.  SMALLEST
45661** extracts the least value from the RowSet.
45662**
45663** The INSERT primitive might allocate additional memory.  Memory is
45664** allocated in chunks so most INSERTs do no allocation.  There is an
45665** upper bound on the size of allocated memory.  No memory is freed
45666** until DESTROY.
45667**
45668** The TEST primitive includes a "batch" number.  The TEST primitive
45669** will only see elements that were inserted before the last change
45670** in the batch number.  In other words, if an INSERT occurs between
45671** two TESTs where the TESTs have the same batch nubmer, then the
45672** value added by the INSERT will not be visible to the second TEST.
45673** The initial batch number is zero, so if the very first TEST contains
45674** a non-zero batch number, it will see all prior INSERTs.
45675**
45676** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
45677** that is attempted.
45678**
45679** The cost of an INSERT is roughly constant.  (Sometimes new memory
45680** has to be allocated on an INSERT.)  The cost of a TEST with a new
45681** batch number is O(NlogN) where N is the number of elements in the RowSet.
45682** The cost of a TEST using the same batch number is O(logN).  The cost
45683** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
45684** primitives are constant time.  The cost of DESTROY is O(N).
45685**
45686** TEST and SMALLEST may not be used by the same RowSet.  This used to
45687** be possible, but the feature was not used, so it was removed in order
45688** to simplify the code.
45689*/
45690/* #include "sqliteInt.h" */
45691
45692
45693/*
45694** Target size for allocation chunks.
45695*/
45696#define ROWSET_ALLOCATION_SIZE 1024
45697
45698/*
45699** The number of rowset entries per allocation chunk.
45700*/
45701#define ROWSET_ENTRY_PER_CHUNK  \
45702                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
45703
45704/*
45705** Each entry in a RowSet is an instance of the following object.
45706**
45707** This same object is reused to store a linked list of trees of RowSetEntry
45708** objects.  In that alternative use, pRight points to the next entry
45709** in the list, pLeft points to the tree, and v is unused.  The
45710** RowSet.pForest value points to the head of this forest list.
45711*/
45712struct RowSetEntry {
45713  i64 v;                        /* ROWID value for this entry */
45714  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
45715  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
45716};
45717
45718/*
45719** RowSetEntry objects are allocated in large chunks (instances of the
45720** following structure) to reduce memory allocation overhead.  The
45721** chunks are kept on a linked list so that they can be deallocated
45722** when the RowSet is destroyed.
45723*/
45724struct RowSetChunk {
45725  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
45726  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
45727};
45728
45729/*
45730** A RowSet in an instance of the following structure.
45731**
45732** A typedef of this structure if found in sqliteInt.h.
45733*/
45734struct RowSet {
45735  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
45736  sqlite3 *db;                   /* The database connection */
45737  struct RowSetEntry *pEntry;    /* List of entries using pRight */
45738  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
45739  struct RowSetEntry *pFresh;    /* Source of new entry objects */
45740  struct RowSetEntry *pForest;   /* List of binary trees of entries */
45741  u16 nFresh;                    /* Number of objects on pFresh */
45742  u16 rsFlags;                   /* Various flags */
45743  int iBatch;                    /* Current insert batch */
45744};
45745
45746/*
45747** Allowed values for RowSet.rsFlags
45748*/
45749#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
45750#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
45751
45752/*
45753** Turn bulk memory into a RowSet object.  N bytes of memory
45754** are available at pSpace.  The db pointer is used as a memory context
45755** for any subsequent allocations that need to occur.
45756** Return a pointer to the new RowSet object.
45757**
45758** It must be the case that N is sufficient to make a Rowset.  If not
45759** an assertion fault occurs.
45760**
45761** If N is larger than the minimum, use the surplus as an initial
45762** allocation of entries available to be filled.
45763*/
45764SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
45765  RowSet *p;
45766  assert( N >= ROUND8(sizeof(*p)) );
45767  p = pSpace;
45768  p->pChunk = 0;
45769  p->db = db;
45770  p->pEntry = 0;
45771  p->pLast = 0;
45772  p->pForest = 0;
45773  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
45774  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
45775  p->rsFlags = ROWSET_SORTED;
45776  p->iBatch = 0;
45777  return p;
45778}
45779
45780/*
45781** Deallocate all chunks from a RowSet.  This frees all memory that
45782** the RowSet has allocated over its lifetime.  This routine is
45783** the destructor for the RowSet.
45784*/
45785SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
45786  struct RowSetChunk *pChunk, *pNextChunk;
45787  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
45788    pNextChunk = pChunk->pNextChunk;
45789    sqlite3DbFree(p->db, pChunk);
45790  }
45791  p->pChunk = 0;
45792  p->nFresh = 0;
45793  p->pEntry = 0;
45794  p->pLast = 0;
45795  p->pForest = 0;
45796  p->rsFlags = ROWSET_SORTED;
45797}
45798
45799/*
45800** Allocate a new RowSetEntry object that is associated with the
45801** given RowSet.  Return a pointer to the new and completely uninitialized
45802** objected.
45803**
45804** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45805** routine returns NULL.
45806*/
45807static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
45808  assert( p!=0 );
45809  if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
45810    /* We could allocate a fresh RowSetEntry each time one is needed, but it
45811    ** is more efficient to pull a preallocated entry from the pool */
45812    struct RowSetChunk *pNew;
45813    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45814    if( pNew==0 ){
45815      return 0;
45816    }
45817    pNew->pNextChunk = p->pChunk;
45818    p->pChunk = pNew;
45819    p->pFresh = pNew->aEntry;
45820    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
45821  }
45822  p->nFresh--;
45823  return p->pFresh++;
45824}
45825
45826/*
45827** Insert a new value into a RowSet.
45828**
45829** The mallocFailed flag of the database connection is set if a
45830** memory allocation fails.
45831*/
45832SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
45833  struct RowSetEntry *pEntry;  /* The new entry */
45834  struct RowSetEntry *pLast;   /* The last prior entry */
45835
45836  /* This routine is never called after sqlite3RowSetNext() */
45837  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
45838
45839  pEntry = rowSetEntryAlloc(p);
45840  if( pEntry==0 ) return;
45841  pEntry->v = rowid;
45842  pEntry->pRight = 0;
45843  pLast = p->pLast;
45844  if( pLast ){
45845    if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
45846      /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45847      ** where possible */
45848      p->rsFlags &= ~ROWSET_SORTED;
45849    }
45850    pLast->pRight = pEntry;
45851  }else{
45852    p->pEntry = pEntry;
45853  }
45854  p->pLast = pEntry;
45855}
45856
45857/*
45858** Merge two lists of RowSetEntry objects.  Remove duplicates.
45859**
45860** The input lists are connected via pRight pointers and are
45861** assumed to each already be in sorted order.
45862*/
45863static struct RowSetEntry *rowSetEntryMerge(
45864  struct RowSetEntry *pA,    /* First sorted list to be merged */
45865  struct RowSetEntry *pB     /* Second sorted list to be merged */
45866){
45867  struct RowSetEntry head;
45868  struct RowSetEntry *pTail;
45869
45870  pTail = &head;
45871  assert( pA!=0 && pB!=0 );
45872  for(;;){
45873    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45874    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
45875    if( pA->v<=pB->v ){
45876      if( pA->v<pB->v ) pTail = pTail->pRight = pA;
45877      pA = pA->pRight;
45878      if( pA==0 ){
45879        pTail->pRight = pB;
45880        break;
45881      }
45882    }else{
45883      pTail = pTail->pRight = pB;
45884      pB = pB->pRight;
45885      if( pB==0 ){
45886        pTail->pRight = pA;
45887        break;
45888      }
45889    }
45890  }
45891  return head.pRight;
45892}
45893
45894/*
45895** Sort all elements on the list of RowSetEntry objects into order of
45896** increasing v.
45897*/
45898static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
45899  unsigned int i;
45900  struct RowSetEntry *pNext, *aBucket[40];
45901
45902  memset(aBucket, 0, sizeof(aBucket));
45903  while( pIn ){
45904    pNext = pIn->pRight;
45905    pIn->pRight = 0;
45906    for(i=0; aBucket[i]; i++){
45907      pIn = rowSetEntryMerge(aBucket[i], pIn);
45908      aBucket[i] = 0;
45909    }
45910    aBucket[i] = pIn;
45911    pIn = pNext;
45912  }
45913  pIn = aBucket[0];
45914  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
45915    if( aBucket[i]==0 ) continue;
45916    pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
45917  }
45918  return pIn;
45919}
45920
45921
45922/*
45923** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
45924** Convert this tree into a linked list connected by the pRight pointers
45925** and return pointers to the first and last elements of the new list.
45926*/
45927static void rowSetTreeToList(
45928  struct RowSetEntry *pIn,         /* Root of the input tree */
45929  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
45930  struct RowSetEntry **ppLast      /* Write tail of the output list here */
45931){
45932  assert( pIn!=0 );
45933  if( pIn->pLeft ){
45934    struct RowSetEntry *p;
45935    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
45936    p->pRight = pIn;
45937  }else{
45938    *ppFirst = pIn;
45939  }
45940  if( pIn->pRight ){
45941    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
45942  }else{
45943    *ppLast = pIn;
45944  }
45945  assert( (*ppLast)->pRight==0 );
45946}
45947
45948
45949/*
45950** Convert a sorted list of elements (connected by pRight) into a binary
45951** tree with depth of iDepth.  A depth of 1 means the tree contains a single
45952** node taken from the head of *ppList.  A depth of 2 means a tree with
45953** three nodes.  And so forth.
45954**
45955** Use as many entries from the input list as required and update the
45956** *ppList to point to the unused elements of the list.  If the input
45957** list contains too few elements, then construct an incomplete tree
45958** and leave *ppList set to NULL.
45959**
45960** Return a pointer to the root of the constructed binary tree.
45961*/
45962static struct RowSetEntry *rowSetNDeepTree(
45963  struct RowSetEntry **ppList,
45964  int iDepth
45965){
45966  struct RowSetEntry *p;         /* Root of the new tree */
45967  struct RowSetEntry *pLeft;     /* Left subtree */
45968  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
45969    /* Prevent unnecessary deep recursion when we run out of entries */
45970    return 0;
45971  }
45972  if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
45973    /* This branch causes a *balanced* tree to be generated.  A valid tree
45974    ** is still generated without this branch, but the tree is wildly
45975    ** unbalanced and inefficient. */
45976    pLeft = rowSetNDeepTree(ppList, iDepth-1);
45977    p = *ppList;
45978    if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
45979      /* It is safe to always return here, but the resulting tree
45980      ** would be unbalanced */
45981      return pLeft;
45982    }
45983    p->pLeft = pLeft;
45984    *ppList = p->pRight;
45985    p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45986  }else{
45987    p = *ppList;
45988    *ppList = p->pRight;
45989    p->pLeft = p->pRight = 0;
45990  }
45991  return p;
45992}
45993
45994/*
45995** Convert a sorted list of elements into a binary tree. Make the tree
45996** as deep as it needs to be in order to contain the entire list.
45997*/
45998static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
45999  int iDepth;           /* Depth of the tree so far */
46000  struct RowSetEntry *p;       /* Current tree root */
46001  struct RowSetEntry *pLeft;   /* Left subtree */
46002
46003  assert( pList!=0 );
46004  p = pList;
46005  pList = p->pRight;
46006  p->pLeft = p->pRight = 0;
46007  for(iDepth=1; pList; iDepth++){
46008    pLeft = p;
46009    p = pList;
46010    pList = p->pRight;
46011    p->pLeft = pLeft;
46012    p->pRight = rowSetNDeepTree(&pList, iDepth);
46013  }
46014  return p;
46015}
46016
46017/*
46018** Extract the smallest element from the RowSet.
46019** Write the element into *pRowid.  Return 1 on success.  Return
46020** 0 if the RowSet is already empty.
46021**
46022** After this routine has been called, the sqlite3RowSetInsert()
46023** routine may not be called again.
46024**
46025** This routine may not be called after sqlite3RowSetTest() has
46026** been used.  Older versions of RowSet allowed that, but as the
46027** capability was not used by the code generator, it was removed
46028** for code economy.
46029*/
46030SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
46031  assert( p!=0 );
46032  assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
46033
46034  /* Merge the forest into a single sorted list on first call */
46035  if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46036    if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46037      p->pEntry = rowSetEntrySort(p->pEntry);
46038    }
46039    p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
46040  }
46041
46042  /* Return the next entry on the list */
46043  if( p->pEntry ){
46044    *pRowid = p->pEntry->v;
46045    p->pEntry = p->pEntry->pRight;
46046    if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
46047      /* Free memory immediately, rather than waiting on sqlite3_finalize() */
46048      sqlite3RowSetClear(p);
46049    }
46050    return 1;
46051  }else{
46052    return 0;
46053  }
46054}
46055
46056/*
46057** Check to see if element iRowid was inserted into the rowset as
46058** part of any insert batch prior to iBatch.  Return 1 or 0.
46059**
46060** If this is the first test of a new batch and if there exist entries
46061** on pRowSet->pEntry, then sort those entries into the forest at
46062** pRowSet->pForest so that they can be tested.
46063*/
46064SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
46065  struct RowSetEntry *p, *pTree;
46066
46067  /* This routine is never called after sqlite3RowSetNext() */
46068  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
46069
46070  /* Sort entries into the forest on the first test of a new batch.
46071  ** To save unnecessary work, only do this when the batch number changes.
46072  */
46073  if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
46074    p = pRowSet->pEntry;
46075    if( p ){
46076      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
46077      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46078        /* Only sort the current set of entiries if they need it */
46079        p = rowSetEntrySort(p);
46080      }
46081      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46082        ppPrevTree = &pTree->pRight;
46083        if( pTree->pLeft==0 ){
46084          pTree->pLeft = rowSetListToTree(p);
46085          break;
46086        }else{
46087          struct RowSetEntry *pAux, *pTail;
46088          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
46089          pTree->pLeft = 0;
46090          p = rowSetEntryMerge(pAux, p);
46091        }
46092      }
46093      if( pTree==0 ){
46094        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
46095        if( pTree ){
46096          pTree->v = 0;
46097          pTree->pRight = 0;
46098          pTree->pLeft = rowSetListToTree(p);
46099        }
46100      }
46101      pRowSet->pEntry = 0;
46102      pRowSet->pLast = 0;
46103      pRowSet->rsFlags |= ROWSET_SORTED;
46104    }
46105    pRowSet->iBatch = iBatch;
46106  }
46107
46108  /* Test to see if the iRowid value appears anywhere in the forest.
46109  ** Return 1 if it does and 0 if not.
46110  */
46111  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46112    p = pTree->pLeft;
46113    while( p ){
46114      if( p->v<iRowid ){
46115        p = p->pRight;
46116      }else if( p->v>iRowid ){
46117        p = p->pLeft;
46118      }else{
46119        return 1;
46120      }
46121    }
46122  }
46123  return 0;
46124}
46125
46126/************** End of rowset.c **********************************************/
46127/************** Begin file pager.c *******************************************/
46128/*
46129** 2001 September 15
46130**
46131** The author disclaims copyright to this source code.  In place of
46132** a legal notice, here is a blessing:
46133**
46134**    May you do good and not evil.
46135**    May you find forgiveness for yourself and forgive others.
46136**    May you share freely, never taking more than you give.
46137**
46138*************************************************************************
46139** This is the implementation of the page cache subsystem or "pager".
46140**
46141** The pager is used to access a database disk file.  It implements
46142** atomic commit and rollback through the use of a journal file that
46143** is separate from the database file.  The pager also implements file
46144** locking to prevent two processes from writing the same database
46145** file simultaneously, or one process from reading the database while
46146** another is writing.
46147*/
46148#ifndef SQLITE_OMIT_DISKIO
46149/* #include "sqliteInt.h" */
46150/************** Include wal.h in the middle of pager.c ***********************/
46151/************** Begin file wal.h *********************************************/
46152/*
46153** 2010 February 1
46154**
46155** The author disclaims copyright to this source code.  In place of
46156** a legal notice, here is a blessing:
46157**
46158**    May you do good and not evil.
46159**    May you find forgiveness for yourself and forgive others.
46160**    May you share freely, never taking more than you give.
46161**
46162*************************************************************************
46163** This header file defines the interface to the write-ahead logging
46164** system. Refer to the comments below and the header comment attached to
46165** the implementation of each function in log.c for further details.
46166*/
46167
46168#ifndef SQLITE_WAL_H
46169#define SQLITE_WAL_H
46170
46171/* #include "sqliteInt.h" */
46172
46173/* Additional values that can be added to the sync_flags argument of
46174** sqlite3WalFrames():
46175*/
46176#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
46177#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
46178
46179#ifdef SQLITE_OMIT_WAL
46180# define sqlite3WalOpen(x,y,z)                   0
46181# define sqlite3WalLimit(x,y)
46182# define sqlite3WalClose(w,x,y,z)                0
46183# define sqlite3WalBeginReadTransaction(y,z)     0
46184# define sqlite3WalEndReadTransaction(z)
46185# define sqlite3WalDbsize(y)                     0
46186# define sqlite3WalBeginWriteTransaction(y)      0
46187# define sqlite3WalEndWriteTransaction(x)        0
46188# define sqlite3WalUndo(x,y,z)                   0
46189# define sqlite3WalSavepoint(y,z)
46190# define sqlite3WalSavepointUndo(y,z)            0
46191# define sqlite3WalFrames(u,v,w,x,y,z)           0
46192# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
46193# define sqlite3WalCallback(z)                   0
46194# define sqlite3WalExclusiveMode(y,z)            0
46195# define sqlite3WalHeapMemory(z)                 0
46196# define sqlite3WalFramesize(z)                  0
46197# define sqlite3WalFindFrame(x,y,z)              0
46198# define sqlite3WalFile(x)                       0
46199#else
46200
46201#define WAL_SAVEPOINT_NDATA 4
46202
46203/* Connection to a write-ahead log (WAL) file.
46204** There is one object of this type for each pager.
46205*/
46206typedef struct Wal Wal;
46207
46208/* Open and close a connection to a write-ahead log. */
46209SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
46210SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
46211
46212/* Set the limiting size of a WAL file. */
46213SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
46214
46215/* Used by readers to open (lock) and close (unlock) a snapshot.  A
46216** snapshot is like a read-transaction.  It is the state of the database
46217** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
46218** preserves the current state even if the other threads or processes
46219** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
46220** transaction and releases the lock.
46221*/
46222SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
46223SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
46224
46225/* Read a page from the write-ahead log, if it is present. */
46226SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
46227SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
46228
46229/* If the WAL is not empty, return the size of the database. */
46230SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
46231
46232/* Obtain or release the WRITER lock. */
46233SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
46234SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
46235
46236/* Undo any frames written (but not committed) to the log */
46237SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
46238
46239/* Return an integer that records the current (uncommitted) write
46240** position in the WAL */
46241SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
46242
46243/* Move the write position of the WAL back to iFrame.  Called in
46244** response to a ROLLBACK TO command. */
46245SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
46246
46247/* Write a frame or frames to the log. */
46248SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
46249
46250/* Copy pages from the log to the database file */
46251SQLITE_PRIVATE int sqlite3WalCheckpoint(
46252  Wal *pWal,                      /* Write-ahead log connection */
46253  int eMode,                      /* One of PASSIVE, FULL and RESTART */
46254  int (*xBusy)(void*),            /* Function to call when busy */
46255  void *pBusyArg,                 /* Context argument for xBusyHandler */
46256  int sync_flags,                 /* Flags to sync db file with (or 0) */
46257  int nBuf,                       /* Size of buffer nBuf */
46258  u8 *zBuf,                       /* Temporary buffer to use */
46259  int *pnLog,                     /* OUT: Number of frames in WAL */
46260  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46261);
46262
46263/* Return the value to pass to a sqlite3_wal_hook callback, the
46264** number of frames in the WAL at the point of the last commit since
46265** sqlite3WalCallback() was called.  If no commits have occurred since
46266** the last call, then return 0.
46267*/
46268SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
46269
46270/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
46271** by the pager layer on the database file.
46272*/
46273SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
46274
46275/* Return true if the argument is non-NULL and the WAL module is using
46276** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46277** WAL module is using shared-memory, return false.
46278*/
46279SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
46280
46281#ifdef SQLITE_ENABLE_SNAPSHOT
46282SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
46283SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
46284#endif
46285
46286#ifdef SQLITE_ENABLE_ZIPVFS
46287/* If the WAL file is not empty, return the number of bytes of content
46288** stored in each frame (i.e. the db page-size when the WAL was created).
46289*/
46290SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
46291#endif
46292
46293/* Return the sqlite3_file object for the WAL file */
46294SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
46295
46296#endif /* ifndef SQLITE_OMIT_WAL */
46297#endif /* SQLITE_WAL_H */
46298
46299/************** End of wal.h *************************************************/
46300/************** Continuing where we left off in pager.c **********************/
46301
46302
46303/******************* NOTES ON THE DESIGN OF THE PAGER ************************
46304**
46305** This comment block describes invariants that hold when using a rollback
46306** journal.  These invariants do not apply for journal_mode=WAL,
46307** journal_mode=MEMORY, or journal_mode=OFF.
46308**
46309** Within this comment block, a page is deemed to have been synced
46310** automatically as soon as it is written when PRAGMA synchronous=OFF.
46311** Otherwise, the page is not synced until the xSync method of the VFS
46312** is called successfully on the file containing the page.
46313**
46314** Definition:  A page of the database file is said to be "overwriteable" if
46315** one or more of the following are true about the page:
46316**
46317**     (a)  The original content of the page as it was at the beginning of
46318**          the transaction has been written into the rollback journal and
46319**          synced.
46320**
46321**     (b)  The page was a freelist leaf page at the start of the transaction.
46322**
46323**     (c)  The page number is greater than the largest page that existed in
46324**          the database file at the start of the transaction.
46325**
46326** (1) A page of the database file is never overwritten unless one of the
46327**     following are true:
46328**
46329**     (a) The page and all other pages on the same sector are overwriteable.
46330**
46331**     (b) The atomic page write optimization is enabled, and the entire
46332**         transaction other than the update of the transaction sequence
46333**         number consists of a single page change.
46334**
46335** (2) The content of a page written into the rollback journal exactly matches
46336**     both the content in the database when the rollback journal was written
46337**     and the content in the database at the beginning of the current
46338**     transaction.
46339**
46340** (3) Writes to the database file are an integer multiple of the page size
46341**     in length and are aligned on a page boundary.
46342**
46343** (4) Reads from the database file are either aligned on a page boundary and
46344**     an integer multiple of the page size in length or are taken from the
46345**     first 100 bytes of the database file.
46346**
46347** (5) All writes to the database file are synced prior to the rollback journal
46348**     being deleted, truncated, or zeroed.
46349**
46350** (6) If a master journal file is used, then all writes to the database file
46351**     are synced prior to the master journal being deleted.
46352**
46353** Definition: Two databases (or the same database at two points it time)
46354** are said to be "logically equivalent" if they give the same answer to
46355** all queries.  Note in particular the content of freelist leaf
46356** pages can be changed arbitrarily without affecting the logical equivalence
46357** of the database.
46358**
46359** (7) At any time, if any subset, including the empty set and the total set,
46360**     of the unsynced changes to a rollback journal are removed and the
46361**     journal is rolled back, the resulting database file will be logically
46362**     equivalent to the database file at the beginning of the transaction.
46363**
46364** (8) When a transaction is rolled back, the xTruncate method of the VFS
46365**     is called to restore the database file to the same size it was at
46366**     the beginning of the transaction.  (In some VFSes, the xTruncate
46367**     method is a no-op, but that does not change the fact the SQLite will
46368**     invoke it.)
46369**
46370** (9) Whenever the database file is modified, at least one bit in the range
46371**     of bytes from 24 through 39 inclusive will be changed prior to releasing
46372**     the EXCLUSIVE lock, thus signaling other connections on the same
46373**     database to flush their caches.
46374**
46375** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
46376**      than one billion transactions.
46377**
46378** (11) A database file is well-formed at the beginning and at the conclusion
46379**      of every transaction.
46380**
46381** (12) An EXCLUSIVE lock is held on the database file when writing to
46382**      the database file.
46383**
46384** (13) A SHARED lock is held on the database file while reading any
46385**      content out of the database file.
46386**
46387******************************************************************************/
46388
46389/*
46390** Macros for troubleshooting.  Normally turned off
46391*/
46392#if 0
46393int sqlite3PagerTrace=1;  /* True to enable tracing */
46394#define sqlite3DebugPrintf printf
46395#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
46396#else
46397#define PAGERTRACE(X)
46398#endif
46399
46400/*
46401** The following two macros are used within the PAGERTRACE() macros above
46402** to print out file-descriptors.
46403**
46404** PAGERID() takes a pointer to a Pager struct as its argument. The
46405** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
46406** struct as its argument.
46407*/
46408#define PAGERID(p) ((int)(p->fd))
46409#define FILEHANDLEID(fd) ((int)fd)
46410
46411/*
46412** The Pager.eState variable stores the current 'state' of a pager. A
46413** pager may be in any one of the seven states shown in the following
46414** state diagram.
46415**
46416**                            OPEN <------+------+
46417**                              |         |      |
46418**                              V         |      |
46419**               +---------> READER-------+      |
46420**               |              |                |
46421**               |              V                |
46422**               |<-------WRITER_LOCKED------> ERROR
46423**               |              |                ^
46424**               |              V                |
46425**               |<------WRITER_CACHEMOD-------->|
46426**               |              |                |
46427**               |              V                |
46428**               |<-------WRITER_DBMOD---------->|
46429**               |              |                |
46430**               |              V                |
46431**               +<------WRITER_FINISHED-------->+
46432**
46433**
46434** List of state transitions and the C [function] that performs each:
46435**
46436**   OPEN              -> READER              [sqlite3PagerSharedLock]
46437**   READER            -> OPEN                [pager_unlock]
46438**
46439**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
46440**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
46441**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
46442**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
46443**   WRITER_***        -> READER              [pager_end_transaction]
46444**
46445**   WRITER_***        -> ERROR               [pager_error]
46446**   ERROR             -> OPEN                [pager_unlock]
46447**
46448**
46449**  OPEN:
46450**
46451**    The pager starts up in this state. Nothing is guaranteed in this
46452**    state - the file may or may not be locked and the database size is
46453**    unknown. The database may not be read or written.
46454**
46455**    * No read or write transaction is active.
46456**    * Any lock, or no lock at all, may be held on the database file.
46457**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
46458**
46459**  READER:
46460**
46461**    In this state all the requirements for reading the database in
46462**    rollback (non-WAL) mode are met. Unless the pager is (or recently
46463**    was) in exclusive-locking mode, a user-level read transaction is
46464**    open. The database size is known in this state.
46465**
46466**    A connection running with locking_mode=normal enters this state when
46467**    it opens a read-transaction on the database and returns to state
46468**    OPEN after the read-transaction is completed. However a connection
46469**    running in locking_mode=exclusive (including temp databases) remains in
46470**    this state even after the read-transaction is closed. The only way
46471**    a locking_mode=exclusive connection can transition from READER to OPEN
46472**    is via the ERROR state (see below).
46473**
46474**    * A read transaction may be active (but a write-transaction cannot).
46475**    * A SHARED or greater lock is held on the database file.
46476**    * The dbSize variable may be trusted (even if a user-level read
46477**      transaction is not active). The dbOrigSize and dbFileSize variables
46478**      may not be trusted at this point.
46479**    * If the database is a WAL database, then the WAL connection is open.
46480**    * Even if a read-transaction is not open, it is guaranteed that
46481**      there is no hot-journal in the file-system.
46482**
46483**  WRITER_LOCKED:
46484**
46485**    The pager moves to this state from READER when a write-transaction
46486**    is first opened on the database. In WRITER_LOCKED state, all locks
46487**    required to start a write-transaction are held, but no actual
46488**    modifications to the cache or database have taken place.
46489**
46490**    In rollback mode, a RESERVED or (if the transaction was opened with
46491**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
46492**    moving to this state, but the journal file is not written to or opened
46493**    to in this state. If the transaction is committed or rolled back while
46494**    in WRITER_LOCKED state, all that is required is to unlock the database
46495**    file.
46496**
46497**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
46498**    If the connection is running with locking_mode=exclusive, an attempt
46499**    is made to obtain an EXCLUSIVE lock on the database file.
46500**
46501**    * A write transaction is active.
46502**    * If the connection is open in rollback-mode, a RESERVED or greater
46503**      lock is held on the database file.
46504**    * If the connection is open in WAL-mode, a WAL write transaction
46505**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
46506**      called).
46507**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
46508**    * The contents of the pager cache have not been modified.
46509**    * The journal file may or may not be open.
46510**    * Nothing (not even the first header) has been written to the journal.
46511**
46512**  WRITER_CACHEMOD:
46513**
46514**    A pager moves from WRITER_LOCKED state to this state when a page is
46515**    first modified by the upper layer. In rollback mode the journal file
46516**    is opened (if it is not already open) and a header written to the
46517**    start of it. The database file on disk has not been modified.
46518**
46519**    * A write transaction is active.
46520**    * A RESERVED or greater lock is held on the database file.
46521**    * The journal file is open and the first header has been written
46522**      to it, but the header has not been synced to disk.
46523**    * The contents of the page cache have been modified.
46524**
46525**  WRITER_DBMOD:
46526**
46527**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
46528**    when it modifies the contents of the database file. WAL connections
46529**    never enter this state (since they do not modify the database file,
46530**    just the log file).
46531**
46532**    * A write transaction is active.
46533**    * An EXCLUSIVE or greater lock is held on the database file.
46534**    * The journal file is open and the first header has been written
46535**      and synced to disk.
46536**    * The contents of the page cache have been modified (and possibly
46537**      written to disk).
46538**
46539**  WRITER_FINISHED:
46540**
46541**    It is not possible for a WAL connection to enter this state.
46542**
46543**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
46544**    state after the entire transaction has been successfully written into the
46545**    database file. In this state the transaction may be committed simply
46546**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
46547**    not possible to modify the database further. At this point, the upper
46548**    layer must either commit or rollback the transaction.
46549**
46550**    * A write transaction is active.
46551**    * An EXCLUSIVE or greater lock is held on the database file.
46552**    * All writing and syncing of journal and database data has finished.
46553**      If no error occurred, all that remains is to finalize the journal to
46554**      commit the transaction. If an error did occur, the caller will need
46555**      to rollback the transaction.
46556**
46557**  ERROR:
46558**
46559**    The ERROR state is entered when an IO or disk-full error (including
46560**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
46561**    difficult to be sure that the in-memory pager state (cache contents,
46562**    db size etc.) are consistent with the contents of the file-system.
46563**
46564**    Temporary pager files may enter the ERROR state, but in-memory pagers
46565**    cannot.
46566**
46567**    For example, if an IO error occurs while performing a rollback,
46568**    the contents of the page-cache may be left in an inconsistent state.
46569**    At this point it would be dangerous to change back to READER state
46570**    (as usually happens after a rollback). Any subsequent readers might
46571**    report database corruption (due to the inconsistent cache), and if
46572**    they upgrade to writers, they may inadvertently corrupt the database
46573**    file. To avoid this hazard, the pager switches into the ERROR state
46574**    instead of READER following such an error.
46575**
46576**    Once it has entered the ERROR state, any attempt to use the pager
46577**    to read or write data returns an error. Eventually, once all
46578**    outstanding transactions have been abandoned, the pager is able to
46579**    transition back to OPEN state, discarding the contents of the
46580**    page-cache and any other in-memory state at the same time. Everything
46581**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
46582**    when a read-transaction is next opened on the pager (transitioning
46583**    the pager into READER state). At that point the system has recovered
46584**    from the error.
46585**
46586**    Specifically, the pager jumps into the ERROR state if:
46587**
46588**      1. An error occurs while attempting a rollback. This happens in
46589**         function sqlite3PagerRollback().
46590**
46591**      2. An error occurs while attempting to finalize a journal file
46592**         following a commit in function sqlite3PagerCommitPhaseTwo().
46593**
46594**      3. An error occurs while attempting to write to the journal or
46595**         database file in function pagerStress() in order to free up
46596**         memory.
46597**
46598**    In other cases, the error is returned to the b-tree layer. The b-tree
46599**    layer then attempts a rollback operation. If the error condition
46600**    persists, the pager enters the ERROR state via condition (1) above.
46601**
46602**    Condition (3) is necessary because it can be triggered by a read-only
46603**    statement executed within a transaction. In this case, if the error
46604**    code were simply returned to the user, the b-tree layer would not
46605**    automatically attempt a rollback, as it assumes that an error in a
46606**    read-only statement cannot leave the pager in an internally inconsistent
46607**    state.
46608**
46609**    * The Pager.errCode variable is set to something other than SQLITE_OK.
46610**    * There are one or more outstanding references to pages (after the
46611**      last reference is dropped the pager should move back to OPEN state).
46612**    * The pager is not an in-memory pager.
46613**
46614**
46615** Notes:
46616**
46617**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
46618**     connection is open in WAL mode. A WAL connection is always in one
46619**     of the first four states.
46620**
46621**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
46622**     state. There are two exceptions: immediately after exclusive-mode has
46623**     been turned on (and before any read or write transactions are
46624**     executed), and when the pager is leaving the "error state".
46625**
46626**   * See also: assert_pager_state().
46627*/
46628#define PAGER_OPEN                  0
46629#define PAGER_READER                1
46630#define PAGER_WRITER_LOCKED         2
46631#define PAGER_WRITER_CACHEMOD       3
46632#define PAGER_WRITER_DBMOD          4
46633#define PAGER_WRITER_FINISHED       5
46634#define PAGER_ERROR                 6
46635
46636/*
46637** The Pager.eLock variable is almost always set to one of the
46638** following locking-states, according to the lock currently held on
46639** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46640** This variable is kept up to date as locks are taken and released by
46641** the pagerLockDb() and pagerUnlockDb() wrappers.
46642**
46643** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
46644** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
46645** the operation was successful. In these circumstances pagerLockDb() and
46646** pagerUnlockDb() take a conservative approach - eLock is always updated
46647** when unlocking the file, and only updated when locking the file if the
46648** VFS call is successful. This way, the Pager.eLock variable may be set
46649** to a less exclusive (lower) value than the lock that is actually held
46650** at the system level, but it is never set to a more exclusive value.
46651**
46652** This is usually safe. If an xUnlock fails or appears to fail, there may
46653** be a few redundant xLock() calls or a lock may be held for longer than
46654** required, but nothing really goes wrong.
46655**
46656** The exception is when the database file is unlocked as the pager moves
46657** from ERROR to OPEN state. At this point there may be a hot-journal file
46658** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
46659** transition, by the same pager or any other). If the call to xUnlock()
46660** fails at this point and the pager is left holding an EXCLUSIVE lock, this
46661** can confuse the call to xCheckReservedLock() call made later as part
46662** of hot-journal detection.
46663**
46664** xCheckReservedLock() is defined as returning true "if there is a RESERVED
46665** lock held by this process or any others". So xCheckReservedLock may
46666** return true because the caller itself is holding an EXCLUSIVE lock (but
46667** doesn't know it because of a previous error in xUnlock). If this happens
46668** a hot-journal may be mistaken for a journal being created by an active
46669** transaction in another process, causing SQLite to read from the database
46670** without rolling it back.
46671**
46672** To work around this, if a call to xUnlock() fails when unlocking the
46673** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
46674** is only changed back to a real locking state after a successful call
46675** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
46676** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
46677** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
46678** lock on the database file before attempting to roll it back. See function
46679** PagerSharedLock() for more detail.
46680**
46681** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
46682** PAGER_OPEN state.
46683*/
46684#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
46685
46686/*
46687** A macro used for invoking the codec if there is one
46688*/
46689#ifdef SQLITE_HAS_CODEC
46690# define CODEC1(P,D,N,X,E) \
46691    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
46692# define CODEC2(P,D,N,X,E,O) \
46693    if( P->xCodec==0 ){ O=(char*)D; }else \
46694    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
46695#else
46696# define CODEC1(P,D,N,X,E)   /* NO-OP */
46697# define CODEC2(P,D,N,X,E,O) O=(char*)D
46698#endif
46699
46700/*
46701** The maximum allowed sector size. 64KiB. If the xSectorsize() method
46702** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
46703** This could conceivably cause corruption following a power failure on
46704** such a system. This is currently an undocumented limit.
46705*/
46706#define MAX_SECTOR_SIZE 0x10000
46707
46708
46709/*
46710** An instance of the following structure is allocated for each active
46711** savepoint and statement transaction in the system. All such structures
46712** are stored in the Pager.aSavepoint[] array, which is allocated and
46713** resized using sqlite3Realloc().
46714**
46715** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
46716** set to 0. If a journal-header is written into the main journal while
46717** the savepoint is active, then iHdrOffset is set to the byte offset
46718** immediately following the last journal record written into the main
46719** journal before the journal-header. This is required during savepoint
46720** rollback (see pagerPlaybackSavepoint()).
46721*/
46722typedef struct PagerSavepoint PagerSavepoint;
46723struct PagerSavepoint {
46724  i64 iOffset;                 /* Starting offset in main journal */
46725  i64 iHdrOffset;              /* See above */
46726  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
46727  Pgno nOrig;                  /* Original number of pages in file */
46728  Pgno iSubRec;                /* Index of first record in sub-journal */
46729#ifndef SQLITE_OMIT_WAL
46730  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
46731#endif
46732};
46733
46734/*
46735** Bits of the Pager.doNotSpill flag.  See further description below.
46736*/
46737#define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
46738#define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
46739#define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
46740
46741/*
46742** An open page cache is an instance of struct Pager. A description of
46743** some of the more important member variables follows:
46744**
46745** eState
46746**
46747**   The current 'state' of the pager object. See the comment and state
46748**   diagram above for a description of the pager state.
46749**
46750** eLock
46751**
46752**   For a real on-disk database, the current lock held on the database file -
46753**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46754**
46755**   For a temporary or in-memory database (neither of which require any
46756**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
46757**   databases always have Pager.exclusiveMode==1, this tricks the pager
46758**   logic into thinking that it already has all the locks it will ever
46759**   need (and no reason to release them).
46760**
46761**   In some (obscure) circumstances, this variable may also be set to
46762**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
46763**   details.
46764**
46765** changeCountDone
46766**
46767**   This boolean variable is used to make sure that the change-counter
46768**   (the 4-byte header field at byte offset 24 of the database file) is
46769**   not updated more often than necessary.
46770**
46771**   It is set to true when the change-counter field is updated, which
46772**   can only happen if an exclusive lock is held on the database file.
46773**   It is cleared (set to false) whenever an exclusive lock is
46774**   relinquished on the database file. Each time a transaction is committed,
46775**   The changeCountDone flag is inspected. If it is true, the work of
46776**   updating the change-counter is omitted for the current transaction.
46777**
46778**   This mechanism means that when running in exclusive mode, a connection
46779**   need only update the change-counter once, for the first transaction
46780**   committed.
46781**
46782** setMaster
46783**
46784**   When PagerCommitPhaseOne() is called to commit a transaction, it may
46785**   (or may not) specify a master-journal name to be written into the
46786**   journal file before it is synced to disk.
46787**
46788**   Whether or not a journal file contains a master-journal pointer affects
46789**   the way in which the journal file is finalized after the transaction is
46790**   committed or rolled back when running in "journal_mode=PERSIST" mode.
46791**   If a journal file does not contain a master-journal pointer, it is
46792**   finalized by overwriting the first journal header with zeroes. If
46793**   it does contain a master-journal pointer the journal file is finalized
46794**   by truncating it to zero bytes, just as if the connection were
46795**   running in "journal_mode=truncate" mode.
46796**
46797**   Journal files that contain master journal pointers cannot be finalized
46798**   simply by overwriting the first journal-header with zeroes, as the
46799**   master journal pointer could interfere with hot-journal rollback of any
46800**   subsequently interrupted transaction that reuses the journal file.
46801**
46802**   The flag is cleared as soon as the journal file is finalized (either
46803**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
46804**   journal file from being successfully finalized, the setMaster flag
46805**   is cleared anyway (and the pager will move to ERROR state).
46806**
46807** doNotSpill
46808**
46809**   This variables control the behavior of cache-spills  (calls made by
46810**   the pcache module to the pagerStress() routine to write cached data
46811**   to the file-system in order to free up memory).
46812**
46813**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
46814**   writing to the database from pagerStress() is disabled altogether.
46815**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
46816**   comes up during savepoint rollback that requires the pcache module
46817**   to allocate a new page to prevent the journal file from being written
46818**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
46819**   case is a user preference.
46820**
46821**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
46822**   pagerStress() is permitted, but syncing the journal file is not.
46823**   This flag is set by sqlite3PagerWrite() when the file-system sector-size
46824**   is larger than the database page-size in order to prevent a journal sync
46825**   from happening in between the journalling of two pages on the same sector.
46826**
46827** subjInMemory
46828**
46829**   This is a boolean variable. If true, then any required sub-journal
46830**   is opened as an in-memory journal file. If false, then in-memory
46831**   sub-journals are only used for in-memory pager files.
46832**
46833**   This variable is updated by the upper layer each time a new
46834**   write-transaction is opened.
46835**
46836** dbSize, dbOrigSize, dbFileSize
46837**
46838**   Variable dbSize is set to the number of pages in the database file.
46839**   It is valid in PAGER_READER and higher states (all states except for
46840**   OPEN and ERROR).
46841**
46842**   dbSize is set based on the size of the database file, which may be
46843**   larger than the size of the database (the value stored at offset
46844**   28 of the database header by the btree). If the size of the file
46845**   is not an integer multiple of the page-size, the value stored in
46846**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
46847**   Except, any file that is greater than 0 bytes in size is considered
46848**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
46849**   to dbSize==1).
46850**
46851**   During a write-transaction, if pages with page-numbers greater than
46852**   dbSize are modified in the cache, dbSize is updated accordingly.
46853**   Similarly, if the database is truncated using PagerTruncateImage(),
46854**   dbSize is updated.
46855**
46856**   Variables dbOrigSize and dbFileSize are valid in states
46857**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
46858**   variable at the start of the transaction. It is used during rollback,
46859**   and to determine whether or not pages need to be journalled before
46860**   being modified.
46861**
46862**   Throughout a write-transaction, dbFileSize contains the size of
46863**   the file on disk in pages. It is set to a copy of dbSize when the
46864**   write-transaction is first opened, and updated when VFS calls are made
46865**   to write or truncate the database file on disk.
46866**
46867**   The only reason the dbFileSize variable is required is to suppress
46868**   unnecessary calls to xTruncate() after committing a transaction. If,
46869**   when a transaction is committed, the dbFileSize variable indicates
46870**   that the database file is larger than the database image (Pager.dbSize),
46871**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
46872**   to measure the database file on disk, and then truncates it if required.
46873**   dbFileSize is not used when rolling back a transaction. In this case
46874**   pager_truncate() is called unconditionally (which means there may be
46875**   a call to xFilesize() that is not strictly required). In either case,
46876**   pager_truncate() may cause the file to become smaller or larger.
46877**
46878** dbHintSize
46879**
46880**   The dbHintSize variable is used to limit the number of calls made to
46881**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
46882**
46883**   dbHintSize is set to a copy of the dbSize variable when a
46884**   write-transaction is opened (at the same time as dbFileSize and
46885**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
46886**   dbHintSize is increased to the number of pages that correspond to the
46887**   size-hint passed to the method call. See pager_write_pagelist() for
46888**   details.
46889**
46890** errCode
46891**
46892**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
46893**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
46894**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
46895**   sub-codes.
46896*/
46897struct Pager {
46898  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
46899  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
46900  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
46901  u8 useJournal;              /* Use a rollback journal on this file */
46902  u8 noSync;                  /* Do not sync the journal if true */
46903  u8 fullSync;                /* Do extra syncs of the journal for robustness */
46904  u8 extraSync;               /* sync directory after journal delete */
46905  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
46906  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
46907  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
46908  u8 tempFile;                /* zFilename is a temporary or immutable file */
46909  u8 noLock;                  /* Do not lock (except in WAL mode) */
46910  u8 readOnly;                /* True for a read-only database */
46911  u8 memDb;                   /* True to inhibit all file I/O */
46912
46913  /**************************************************************************
46914  ** The following block contains those class members that change during
46915  ** routine operation.  Class members not in this block are either fixed
46916  ** when the pager is first created or else only change when there is a
46917  ** significant mode change (such as changing the page_size, locking_mode,
46918  ** or the journal_mode).  From another view, these class members describe
46919  ** the "state" of the pager, while other class members describe the
46920  ** "configuration" of the pager.
46921  */
46922  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
46923  u8 eLock;                   /* Current lock held on database file */
46924  u8 changeCountDone;         /* Set after incrementing the change-counter */
46925  u8 setMaster;               /* True if a m-j name has been written to jrnl */
46926  u8 doNotSpill;              /* Do not spill the cache when non-zero */
46927  u8 subjInMemory;            /* True to use in-memory sub-journals */
46928  u8 bUseFetch;               /* True to use xFetch() */
46929  u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
46930  Pgno dbSize;                /* Number of pages in the database */
46931  Pgno dbOrigSize;            /* dbSize before the current transaction */
46932  Pgno dbFileSize;            /* Number of pages in the database file */
46933  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
46934  int errCode;                /* One of several kinds of errors */
46935  int nRec;                   /* Pages journalled since last j-header written */
46936  u32 cksumInit;              /* Quasi-random value added to every checksum */
46937  u32 nSubRec;                /* Number of records written to sub-journal */
46938  Bitvec *pInJournal;         /* One bit for each page in the database file */
46939  sqlite3_file *fd;           /* File descriptor for database */
46940  sqlite3_file *jfd;          /* File descriptor for main journal */
46941  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
46942  i64 journalOff;             /* Current write offset in the journal file */
46943  i64 journalHdr;             /* Byte offset to previous journal header */
46944  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
46945  PagerSavepoint *aSavepoint; /* Array of active savepoints */
46946  int nSavepoint;             /* Number of elements in aSavepoint[] */
46947  u32 iDataVersion;           /* Changes whenever database content changes */
46948  char dbFileVers[16];        /* Changes whenever database file changes */
46949
46950  int nMmapOut;               /* Number of mmap pages currently outstanding */
46951  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
46952  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
46953  /*
46954  ** End of the routinely-changing class members
46955  ***************************************************************************/
46956
46957  u16 nExtra;                 /* Add this many bytes to each in-memory page */
46958  i16 nReserve;               /* Number of unused bytes at end of each page */
46959  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
46960  u32 sectorSize;             /* Assumed sector size during rollback */
46961  int pageSize;               /* Number of bytes in a page */
46962  Pgno mxPgno;                /* Maximum allowed size of the database */
46963  i64 journalSizeLimit;       /* Size limit for persistent journal files */
46964  char *zFilename;            /* Name of the database file */
46965  char *zJournal;             /* Name of the journal file */
46966  int (*xBusyHandler)(void*); /* Function to call when busy */
46967  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
46968  int aStat[3];               /* Total cache hits, misses and writes */
46969#ifdef SQLITE_TEST
46970  int nRead;                  /* Database pages read */
46971#endif
46972  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
46973#ifdef SQLITE_HAS_CODEC
46974  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
46975  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
46976  void (*xCodecFree)(void*);             /* Destructor for the codec */
46977  void *pCodec;               /* First argument to xCodec... methods */
46978#endif
46979  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
46980  PCache *pPCache;            /* Pointer to page cache object */
46981#ifndef SQLITE_OMIT_WAL
46982  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
46983  char *zWal;                 /* File name for write-ahead log */
46984#endif
46985};
46986
46987/*
46988** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
46989** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
46990** or CACHE_WRITE to sqlite3_db_status().
46991*/
46992#define PAGER_STAT_HIT   0
46993#define PAGER_STAT_MISS  1
46994#define PAGER_STAT_WRITE 2
46995
46996/*
46997** The following global variables hold counters used for
46998** testing purposes only.  These variables do not exist in
46999** a non-testing build.  These variables are not thread-safe.
47000*/
47001#ifdef SQLITE_TEST
47002SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
47003SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
47004SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
47005# define PAGER_INCR(v)  v++
47006#else
47007# define PAGER_INCR(v)
47008#endif
47009
47010
47011
47012/*
47013** Journal files begin with the following magic string.  The data
47014** was obtained from /dev/random.  It is used only as a sanity check.
47015**
47016** Since version 2.8.0, the journal format contains additional sanity
47017** checking information.  If the power fails while the journal is being
47018** written, semi-random garbage data might appear in the journal
47019** file after power is restored.  If an attempt is then made
47020** to roll the journal back, the database could be corrupted.  The additional
47021** sanity checking data is an attempt to discover the garbage in the
47022** journal and ignore it.
47023**
47024** The sanity checking information for the new journal format consists
47025** of a 32-bit checksum on each page of data.  The checksum covers both
47026** the page number and the pPager->pageSize bytes of data for the page.
47027** This cksum is initialized to a 32-bit random value that appears in the
47028** journal file right after the header.  The random initializer is important,
47029** because garbage data that appears at the end of a journal is likely
47030** data that was once in other files that have now been deleted.  If the
47031** garbage data came from an obsolete journal file, the checksums might
47032** be correct.  But by initializing the checksum to random value which
47033** is different for every journal, we minimize that risk.
47034*/
47035static const unsigned char aJournalMagic[] = {
47036  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
47037};
47038
47039/*
47040** The size of the of each page record in the journal is given by
47041** the following macro.
47042*/
47043#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
47044
47045/*
47046** The journal header size for this pager. This is usually the same
47047** size as a single disk sector. See also setSectorSize().
47048*/
47049#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
47050
47051/*
47052** The macro MEMDB is true if we are dealing with an in-memory database.
47053** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
47054** the value of MEMDB will be a constant and the compiler will optimize
47055** out code that would never execute.
47056*/
47057#ifdef SQLITE_OMIT_MEMORYDB
47058# define MEMDB 0
47059#else
47060# define MEMDB pPager->memDb
47061#endif
47062
47063/*
47064** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
47065** interfaces to access the database using memory-mapped I/O.
47066*/
47067#if SQLITE_MAX_MMAP_SIZE>0
47068# define USEFETCH(x) ((x)->bUseFetch)
47069#else
47070# define USEFETCH(x) 0
47071#endif
47072
47073/*
47074** The maximum legal page number is (2^31 - 1).
47075*/
47076#define PAGER_MAX_PGNO 2147483647
47077
47078/*
47079** The argument to this macro is a file descriptor (type sqlite3_file*).
47080** Return 0 if it is not open, or non-zero (but not 1) if it is.
47081**
47082** This is so that expressions can be written as:
47083**
47084**   if( isOpen(pPager->jfd) ){ ...
47085**
47086** instead of
47087**
47088**   if( pPager->jfd->pMethods ){ ...
47089*/
47090#define isOpen(pFd) ((pFd)->pMethods!=0)
47091
47092/*
47093** Return true if this pager uses a write-ahead log instead of the usual
47094** rollback journal. Otherwise false.
47095*/
47096#ifndef SQLITE_OMIT_WAL
47097static int pagerUseWal(Pager *pPager){
47098  return (pPager->pWal!=0);
47099}
47100#else
47101# define pagerUseWal(x) 0
47102# define pagerRollbackWal(x) 0
47103# define pagerWalFrames(v,w,x,y) 0
47104# define pagerOpenWalIfPresent(z) SQLITE_OK
47105# define pagerBeginReadTransaction(z) SQLITE_OK
47106#endif
47107
47108#ifndef NDEBUG
47109/*
47110** Usage:
47111**
47112**   assert( assert_pager_state(pPager) );
47113**
47114** This function runs many asserts to try to find inconsistencies in
47115** the internal state of the Pager object.
47116*/
47117static int assert_pager_state(Pager *p){
47118  Pager *pPager = p;
47119
47120  /* State must be valid. */
47121  assert( p->eState==PAGER_OPEN
47122       || p->eState==PAGER_READER
47123       || p->eState==PAGER_WRITER_LOCKED
47124       || p->eState==PAGER_WRITER_CACHEMOD
47125       || p->eState==PAGER_WRITER_DBMOD
47126       || p->eState==PAGER_WRITER_FINISHED
47127       || p->eState==PAGER_ERROR
47128  );
47129
47130  /* Regardless of the current state, a temp-file connection always behaves
47131  ** as if it has an exclusive lock on the database file. It never updates
47132  ** the change-counter field, so the changeCountDone flag is always set.
47133  */
47134  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
47135  assert( p->tempFile==0 || pPager->changeCountDone );
47136
47137  /* If the useJournal flag is clear, the journal-mode must be "OFF".
47138  ** And if the journal-mode is "OFF", the journal file must not be open.
47139  */
47140  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
47141  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
47142
47143  /* Check that MEMDB implies noSync. And an in-memory journal. Since
47144  ** this means an in-memory pager performs no IO at all, it cannot encounter
47145  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
47146  ** a journal file. (although the in-memory journal implementation may
47147  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
47148  ** is therefore not possible for an in-memory pager to enter the ERROR
47149  ** state.
47150  */
47151  if( MEMDB ){
47152    assert( !isOpen(p->fd) );
47153    assert( p->noSync );
47154    assert( p->journalMode==PAGER_JOURNALMODE_OFF
47155         || p->journalMode==PAGER_JOURNALMODE_MEMORY
47156    );
47157    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
47158    assert( pagerUseWal(p)==0 );
47159  }
47160
47161  /* If changeCountDone is set, a RESERVED lock or greater must be held
47162  ** on the file.
47163  */
47164  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
47165  assert( p->eLock!=PENDING_LOCK );
47166
47167  switch( p->eState ){
47168    case PAGER_OPEN:
47169      assert( !MEMDB );
47170      assert( pPager->errCode==SQLITE_OK );
47171      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
47172      break;
47173
47174    case PAGER_READER:
47175      assert( pPager->errCode==SQLITE_OK );
47176      assert( p->eLock!=UNKNOWN_LOCK );
47177      assert( p->eLock>=SHARED_LOCK );
47178      break;
47179
47180    case PAGER_WRITER_LOCKED:
47181      assert( p->eLock!=UNKNOWN_LOCK );
47182      assert( pPager->errCode==SQLITE_OK );
47183      if( !pagerUseWal(pPager) ){
47184        assert( p->eLock>=RESERVED_LOCK );
47185      }
47186      assert( pPager->dbSize==pPager->dbOrigSize );
47187      assert( pPager->dbOrigSize==pPager->dbFileSize );
47188      assert( pPager->dbOrigSize==pPager->dbHintSize );
47189      assert( pPager->setMaster==0 );
47190      break;
47191
47192    case PAGER_WRITER_CACHEMOD:
47193      assert( p->eLock!=UNKNOWN_LOCK );
47194      assert( pPager->errCode==SQLITE_OK );
47195      if( !pagerUseWal(pPager) ){
47196        /* It is possible that if journal_mode=wal here that neither the
47197        ** journal file nor the WAL file are open. This happens during
47198        ** a rollback transaction that switches from journal_mode=off
47199        ** to journal_mode=wal.
47200        */
47201        assert( p->eLock>=RESERVED_LOCK );
47202        assert( isOpen(p->jfd)
47203             || p->journalMode==PAGER_JOURNALMODE_OFF
47204             || p->journalMode==PAGER_JOURNALMODE_WAL
47205        );
47206      }
47207      assert( pPager->dbOrigSize==pPager->dbFileSize );
47208      assert( pPager->dbOrigSize==pPager->dbHintSize );
47209      break;
47210
47211    case PAGER_WRITER_DBMOD:
47212      assert( p->eLock==EXCLUSIVE_LOCK );
47213      assert( pPager->errCode==SQLITE_OK );
47214      assert( !pagerUseWal(pPager) );
47215      assert( p->eLock>=EXCLUSIVE_LOCK );
47216      assert( isOpen(p->jfd)
47217           || p->journalMode==PAGER_JOURNALMODE_OFF
47218           || p->journalMode==PAGER_JOURNALMODE_WAL
47219      );
47220      assert( pPager->dbOrigSize<=pPager->dbHintSize );
47221      break;
47222
47223    case PAGER_WRITER_FINISHED:
47224      assert( p->eLock==EXCLUSIVE_LOCK );
47225      assert( pPager->errCode==SQLITE_OK );
47226      assert( !pagerUseWal(pPager) );
47227      assert( isOpen(p->jfd)
47228           || p->journalMode==PAGER_JOURNALMODE_OFF
47229           || p->journalMode==PAGER_JOURNALMODE_WAL
47230      );
47231      break;
47232
47233    case PAGER_ERROR:
47234      /* There must be at least one outstanding reference to the pager if
47235      ** in ERROR state. Otherwise the pager should have already dropped
47236      ** back to OPEN state.
47237      */
47238      assert( pPager->errCode!=SQLITE_OK );
47239      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
47240      break;
47241  }
47242
47243  return 1;
47244}
47245#endif /* ifndef NDEBUG */
47246
47247#ifdef SQLITE_DEBUG
47248/*
47249** Return a pointer to a human readable string in a static buffer
47250** containing the state of the Pager object passed as an argument. This
47251** is intended to be used within debuggers. For example, as an alternative
47252** to "print *pPager" in gdb:
47253**
47254** (gdb) printf "%s", print_pager_state(pPager)
47255*/
47256static char *print_pager_state(Pager *p){
47257  static char zRet[1024];
47258
47259  sqlite3_snprintf(1024, zRet,
47260      "Filename:      %s\n"
47261      "State:         %s errCode=%d\n"
47262      "Lock:          %s\n"
47263      "Locking mode:  locking_mode=%s\n"
47264      "Journal mode:  journal_mode=%s\n"
47265      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
47266      "Journal:       journalOff=%lld journalHdr=%lld\n"
47267      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
47268      , p->zFilename
47269      , p->eState==PAGER_OPEN            ? "OPEN" :
47270        p->eState==PAGER_READER          ? "READER" :
47271        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
47272        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
47273        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
47274        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
47275        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
47276      , (int)p->errCode
47277      , p->eLock==NO_LOCK         ? "NO_LOCK" :
47278        p->eLock==RESERVED_LOCK   ? "RESERVED" :
47279        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
47280        p->eLock==SHARED_LOCK     ? "SHARED" :
47281        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
47282      , p->exclusiveMode ? "exclusive" : "normal"
47283      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
47284        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
47285        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
47286        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
47287        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
47288        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
47289      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
47290      , p->journalOff, p->journalHdr
47291      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
47292  );
47293
47294  return zRet;
47295}
47296#endif
47297
47298/*
47299** Return true if it is necessary to write page *pPg into the sub-journal.
47300** A page needs to be written into the sub-journal if there exists one
47301** or more open savepoints for which:
47302**
47303**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
47304**   * The bit corresponding to the page-number is not set in
47305**     PagerSavepoint.pInSavepoint.
47306*/
47307static int subjRequiresPage(PgHdr *pPg){
47308  Pager *pPager = pPg->pPager;
47309  PagerSavepoint *p;
47310  Pgno pgno = pPg->pgno;
47311  int i;
47312  for(i=0; i<pPager->nSavepoint; i++){
47313    p = &pPager->aSavepoint[i];
47314    if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
47315      return 1;
47316    }
47317  }
47318  return 0;
47319}
47320
47321#ifdef SQLITE_DEBUG
47322/*
47323** Return true if the page is already in the journal file.
47324*/
47325static int pageInJournal(Pager *pPager, PgHdr *pPg){
47326  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
47327}
47328#endif
47329
47330/*
47331** Read a 32-bit integer from the given file descriptor.  Store the integer
47332** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
47333** error code is something goes wrong.
47334**
47335** All values are stored on disk as big-endian.
47336*/
47337static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
47338  unsigned char ac[4];
47339  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
47340  if( rc==SQLITE_OK ){
47341    *pRes = sqlite3Get4byte(ac);
47342  }
47343  return rc;
47344}
47345
47346/*
47347** Write a 32-bit integer into a string buffer in big-endian byte order.
47348*/
47349#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
47350
47351
47352/*
47353** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
47354** on success or an error code is something goes wrong.
47355*/
47356static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
47357  char ac[4];
47358  put32bits(ac, val);
47359  return sqlite3OsWrite(fd, ac, 4, offset);
47360}
47361
47362/*
47363** Unlock the database file to level eLock, which must be either NO_LOCK
47364** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
47365** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
47366**
47367** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47368** called, do not modify it. See the comment above the #define of
47369** UNKNOWN_LOCK for an explanation of this.
47370*/
47371static int pagerUnlockDb(Pager *pPager, int eLock){
47372  int rc = SQLITE_OK;
47373
47374  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
47375  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
47376  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
47377  if( isOpen(pPager->fd) ){
47378    assert( pPager->eLock>=eLock );
47379    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
47380    if( pPager->eLock!=UNKNOWN_LOCK ){
47381      pPager->eLock = (u8)eLock;
47382    }
47383    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
47384  }
47385  return rc;
47386}
47387
47388/*
47389** Lock the database file to level eLock, which must be either SHARED_LOCK,
47390** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
47391** Pager.eLock variable to the new locking state.
47392**
47393** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47394** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
47395** See the comment above the #define of UNKNOWN_LOCK for an explanation
47396** of this.
47397*/
47398static int pagerLockDb(Pager *pPager, int eLock){
47399  int rc = SQLITE_OK;
47400
47401  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
47402  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
47403    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
47404    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
47405      pPager->eLock = (u8)eLock;
47406      IOTRACE(("LOCK %p %d\n", pPager, eLock))
47407    }
47408  }
47409  return rc;
47410}
47411
47412/*
47413** This function determines whether or not the atomic-write optimization
47414** can be used with this pager. The optimization can be used if:
47415**
47416**  (a) the value returned by OsDeviceCharacteristics() indicates that
47417**      a database page may be written atomically, and
47418**  (b) the value returned by OsSectorSize() is less than or equal
47419**      to the page size.
47420**
47421** The optimization is also always enabled for temporary files. It is
47422** an error to call this function if pPager is opened on an in-memory
47423** database.
47424**
47425** If the optimization cannot be used, 0 is returned. If it can be used,
47426** then the value returned is the size of the journal file when it
47427** contains rollback data for exactly one page.
47428*/
47429#ifdef SQLITE_ENABLE_ATOMIC_WRITE
47430static int jrnlBufferSize(Pager *pPager){
47431  assert( !MEMDB );
47432  if( !pPager->tempFile ){
47433    int dc;                           /* Device characteristics */
47434    int nSector;                      /* Sector size */
47435    int szPage;                       /* Page size */
47436
47437    assert( isOpen(pPager->fd) );
47438    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
47439    nSector = pPager->sectorSize;
47440    szPage = pPager->pageSize;
47441
47442    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47443    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47444    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
47445      return 0;
47446    }
47447  }
47448
47449  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
47450}
47451#else
47452# define jrnlBufferSize(x) 0
47453#endif
47454
47455/*
47456** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
47457** on the cache using a hash function.  This is used for testing
47458** and debugging only.
47459*/
47460#ifdef SQLITE_CHECK_PAGES
47461/*
47462** Return a 32-bit hash of the page data for pPage.
47463*/
47464static u32 pager_datahash(int nByte, unsigned char *pData){
47465  u32 hash = 0;
47466  int i;
47467  for(i=0; i<nByte; i++){
47468    hash = (hash*1039) + pData[i];
47469  }
47470  return hash;
47471}
47472static u32 pager_pagehash(PgHdr *pPage){
47473  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
47474}
47475static void pager_set_pagehash(PgHdr *pPage){
47476  pPage->pageHash = pager_pagehash(pPage);
47477}
47478
47479/*
47480** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
47481** is defined, and NDEBUG is not defined, an assert() statement checks
47482** that the page is either dirty or still matches the calculated page-hash.
47483*/
47484#define CHECK_PAGE(x) checkPage(x)
47485static void checkPage(PgHdr *pPg){
47486  Pager *pPager = pPg->pPager;
47487  assert( pPager->eState!=PAGER_ERROR );
47488  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
47489}
47490
47491#else
47492#define pager_datahash(X,Y)  0
47493#define pager_pagehash(X)  0
47494#define pager_set_pagehash(X)
47495#define CHECK_PAGE(x)
47496#endif  /* SQLITE_CHECK_PAGES */
47497
47498/*
47499** When this is called the journal file for pager pPager must be open.
47500** This function attempts to read a master journal file name from the
47501** end of the file and, if successful, copies it into memory supplied
47502** by the caller. See comments above writeMasterJournal() for the format
47503** used to store a master journal file name at the end of a journal file.
47504**
47505** zMaster must point to a buffer of at least nMaster bytes allocated by
47506** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
47507** enough space to write the master journal name). If the master journal
47508** name in the journal is longer than nMaster bytes (including a
47509** nul-terminator), then this is handled as if no master journal name
47510** were present in the journal.
47511**
47512** If a master journal file name is present at the end of the journal
47513** file, then it is copied into the buffer pointed to by zMaster. A
47514** nul-terminator byte is appended to the buffer following the master
47515** journal file name.
47516**
47517** If it is determined that no master journal file name is present
47518** zMaster[0] is set to 0 and SQLITE_OK returned.
47519**
47520** If an error occurs while reading from the journal file, an SQLite
47521** error code is returned.
47522*/
47523static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
47524  int rc;                    /* Return code */
47525  u32 len;                   /* Length in bytes of master journal name */
47526  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
47527  u32 cksum;                 /* MJ checksum value read from journal */
47528  u32 u;                     /* Unsigned loop counter */
47529  unsigned char aMagic[8];   /* A buffer to hold the magic header */
47530  zMaster[0] = '\0';
47531
47532  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
47533   || szJ<16
47534   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
47535   || len>=nMaster
47536   || len==0
47537   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
47538   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
47539   || memcmp(aMagic, aJournalMagic, 8)
47540   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
47541  ){
47542    return rc;
47543  }
47544
47545  /* See if the checksum matches the master journal name */
47546  for(u=0; u<len; u++){
47547    cksum -= zMaster[u];
47548  }
47549  if( cksum ){
47550    /* If the checksum doesn't add up, then one or more of the disk sectors
47551    ** containing the master journal filename is corrupted. This means
47552    ** definitely roll back, so just return SQLITE_OK and report a (nul)
47553    ** master-journal filename.
47554    */
47555    len = 0;
47556  }
47557  zMaster[len] = '\0';
47558
47559  return SQLITE_OK;
47560}
47561
47562/*
47563** Return the offset of the sector boundary at or immediately
47564** following the value in pPager->journalOff, assuming a sector
47565** size of pPager->sectorSize bytes.
47566**
47567** i.e for a sector size of 512:
47568**
47569**   Pager.journalOff          Return value
47570**   ---------------------------------------
47571**   0                         0
47572**   512                       512
47573**   100                       512
47574**   2000                      2048
47575**
47576*/
47577static i64 journalHdrOffset(Pager *pPager){
47578  i64 offset = 0;
47579  i64 c = pPager->journalOff;
47580  if( c ){
47581    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
47582  }
47583  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
47584  assert( offset>=c );
47585  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
47586  return offset;
47587}
47588
47589/*
47590** The journal file must be open when this function is called.
47591**
47592** This function is a no-op if the journal file has not been written to
47593** within the current transaction (i.e. if Pager.journalOff==0).
47594**
47595** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
47596** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
47597** zero the 28-byte header at the start of the journal file. In either case,
47598** if the pager is not in no-sync mode, sync the journal file immediately
47599** after writing or truncating it.
47600**
47601** If Pager.journalSizeLimit is set to a positive, non-zero value, and
47602** following the truncation or zeroing described above the size of the
47603** journal file in bytes is larger than this value, then truncate the
47604** journal file to Pager.journalSizeLimit bytes. The journal file does
47605** not need to be synced following this operation.
47606**
47607** If an IO error occurs, abandon processing and return the IO error code.
47608** Otherwise, return SQLITE_OK.
47609*/
47610static int zeroJournalHdr(Pager *pPager, int doTruncate){
47611  int rc = SQLITE_OK;                               /* Return code */
47612  assert( isOpen(pPager->jfd) );
47613  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
47614  if( pPager->journalOff ){
47615    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
47616
47617    IOTRACE(("JZEROHDR %p\n", pPager))
47618    if( doTruncate || iLimit==0 ){
47619      rc = sqlite3OsTruncate(pPager->jfd, 0);
47620    }else{
47621      static const char zeroHdr[28] = {0};
47622      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
47623    }
47624    if( rc==SQLITE_OK && !pPager->noSync ){
47625      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
47626    }
47627
47628    /* At this point the transaction is committed but the write lock
47629    ** is still held on the file. If there is a size limit configured for
47630    ** the persistent journal and the journal file currently consumes more
47631    ** space than that limit allows for, truncate it now. There is no need
47632    ** to sync the file following this operation.
47633    */
47634    if( rc==SQLITE_OK && iLimit>0 ){
47635      i64 sz;
47636      rc = sqlite3OsFileSize(pPager->jfd, &sz);
47637      if( rc==SQLITE_OK && sz>iLimit ){
47638        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
47639      }
47640    }
47641  }
47642  return rc;
47643}
47644
47645/*
47646** The journal file must be open when this routine is called. A journal
47647** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
47648** current location.
47649**
47650** The format for the journal header is as follows:
47651** - 8 bytes: Magic identifying journal format.
47652** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
47653** - 4 bytes: Random number used for page hash.
47654** - 4 bytes: Initial database page count.
47655** - 4 bytes: Sector size used by the process that wrote this journal.
47656** - 4 bytes: Database page size.
47657**
47658** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
47659*/
47660static int writeJournalHdr(Pager *pPager){
47661  int rc = SQLITE_OK;                 /* Return code */
47662  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
47663  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
47664  u32 nWrite;                         /* Bytes of header sector written */
47665  int ii;                             /* Loop counter */
47666
47667  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
47668
47669  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
47670    nHeader = JOURNAL_HDR_SZ(pPager);
47671  }
47672
47673  /* If there are active savepoints and any of them were created
47674  ** since the most recent journal header was written, update the
47675  ** PagerSavepoint.iHdrOffset fields now.
47676  */
47677  for(ii=0; ii<pPager->nSavepoint; ii++){
47678    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
47679      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
47680    }
47681  }
47682
47683  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
47684
47685  /*
47686  ** Write the nRec Field - the number of page records that follow this
47687  ** journal header. Normally, zero is written to this value at this time.
47688  ** After the records are added to the journal (and the journal synced,
47689  ** if in full-sync mode), the zero is overwritten with the true number
47690  ** of records (see syncJournal()).
47691  **
47692  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
47693  ** reading the journal this value tells SQLite to assume that the
47694  ** rest of the journal file contains valid page records. This assumption
47695  ** is dangerous, as if a failure occurred whilst writing to the journal
47696  ** file it may contain some garbage data. There are two scenarios
47697  ** where this risk can be ignored:
47698  **
47699  **   * When the pager is in no-sync mode. Corruption can follow a
47700  **     power failure in this case anyway.
47701  **
47702  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
47703  **     that garbage data is never appended to the journal file.
47704  */
47705  assert( isOpen(pPager->fd) || pPager->noSync );
47706  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
47707   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
47708  ){
47709    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47710    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
47711  }else{
47712    memset(zHeader, 0, sizeof(aJournalMagic)+4);
47713  }
47714
47715  /* The random check-hash initializer */
47716  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
47717  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
47718  /* The initial database size */
47719  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
47720  /* The assumed sector size for this process */
47721  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
47722
47723  /* The page size */
47724  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
47725
47726  /* Initializing the tail of the buffer is not necessary.  Everything
47727  ** works find if the following memset() is omitted.  But initializing
47728  ** the memory prevents valgrind from complaining, so we are willing to
47729  ** take the performance hit.
47730  */
47731  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
47732         nHeader-(sizeof(aJournalMagic)+20));
47733
47734  /* In theory, it is only necessary to write the 28 bytes that the
47735  ** journal header consumes to the journal file here. Then increment the
47736  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
47737  ** record is written to the following sector (leaving a gap in the file
47738  ** that will be implicitly filled in by the OS).
47739  **
47740  ** However it has been discovered that on some systems this pattern can
47741  ** be significantly slower than contiguously writing data to the file,
47742  ** even if that means explicitly writing data to the block of
47743  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
47744  ** is done.
47745  **
47746  ** The loop is required here in case the sector-size is larger than the
47747  ** database page size. Since the zHeader buffer is only Pager.pageSize
47748  ** bytes in size, more than one call to sqlite3OsWrite() may be required
47749  ** to populate the entire journal header sector.
47750  */
47751  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
47752    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
47753    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
47754    assert( pPager->journalHdr <= pPager->journalOff );
47755    pPager->journalOff += nHeader;
47756  }
47757
47758  return rc;
47759}
47760
47761/*
47762** The journal file must be open when this is called. A journal header file
47763** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
47764** file. The current location in the journal file is given by
47765** pPager->journalOff. See comments above function writeJournalHdr() for
47766** a description of the journal header format.
47767**
47768** If the header is read successfully, *pNRec is set to the number of
47769** page records following this header and *pDbSize is set to the size of the
47770** database before the transaction began, in pages. Also, pPager->cksumInit
47771** is set to the value read from the journal header. SQLITE_OK is returned
47772** in this case.
47773**
47774** If the journal header file appears to be corrupted, SQLITE_DONE is
47775** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
47776** cannot be read from the journal file an error code is returned.
47777*/
47778static int readJournalHdr(
47779  Pager *pPager,               /* Pager object */
47780  int isHot,
47781  i64 journalSize,             /* Size of the open journal file in bytes */
47782  u32 *pNRec,                  /* OUT: Value read from the nRec field */
47783  u32 *pDbSize                 /* OUT: Value of original database size field */
47784){
47785  int rc;                      /* Return code */
47786  unsigned char aMagic[8];     /* A buffer to hold the magic header */
47787  i64 iHdrOff;                 /* Offset of journal header being read */
47788
47789  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
47790
47791  /* Advance Pager.journalOff to the start of the next sector. If the
47792  ** journal file is too small for there to be a header stored at this
47793  ** point, return SQLITE_DONE.
47794  */
47795  pPager->journalOff = journalHdrOffset(pPager);
47796  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
47797    return SQLITE_DONE;
47798  }
47799  iHdrOff = pPager->journalOff;
47800
47801  /* Read in the first 8 bytes of the journal header. If they do not match
47802  ** the  magic string found at the start of each journal header, return
47803  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
47804  ** proceed.
47805  */
47806  if( isHot || iHdrOff!=pPager->journalHdr ){
47807    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
47808    if( rc ){
47809      return rc;
47810    }
47811    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
47812      return SQLITE_DONE;
47813    }
47814  }
47815
47816  /* Read the first three 32-bit fields of the journal header: The nRec
47817  ** field, the checksum-initializer and the database size at the start
47818  ** of the transaction. Return an error code if anything goes wrong.
47819  */
47820  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
47821   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
47822   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
47823  ){
47824    return rc;
47825  }
47826
47827  if( pPager->journalOff==0 ){
47828    u32 iPageSize;               /* Page-size field of journal header */
47829    u32 iSectorSize;             /* Sector-size field of journal header */
47830
47831    /* Read the page-size and sector-size journal header fields. */
47832    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
47833     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
47834    ){
47835      return rc;
47836    }
47837
47838    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
47839    ** journal header to zero. In this case, assume that the Pager.pageSize
47840    ** variable is already set to the correct page size.
47841    */
47842    if( iPageSize==0 ){
47843      iPageSize = pPager->pageSize;
47844    }
47845
47846    /* Check that the values read from the page-size and sector-size fields
47847    ** are within range. To be 'in range', both values need to be a power
47848    ** of two greater than or equal to 512 or 32, and not greater than their
47849    ** respective compile time maximum limits.
47850    */
47851    if( iPageSize<512                  || iSectorSize<32
47852     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
47853     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
47854    ){
47855      /* If the either the page-size or sector-size in the journal-header is
47856      ** invalid, then the process that wrote the journal-header must have
47857      ** crashed before the header was synced. In this case stop reading
47858      ** the journal file here.
47859      */
47860      return SQLITE_DONE;
47861    }
47862
47863    /* Update the page-size to match the value read from the journal.
47864    ** Use a testcase() macro to make sure that malloc failure within
47865    ** PagerSetPagesize() is tested.
47866    */
47867    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
47868    testcase( rc!=SQLITE_OK );
47869
47870    /* Update the assumed sector-size to match the value used by
47871    ** the process that created this journal. If this journal was
47872    ** created by a process other than this one, then this routine
47873    ** is being called from within pager_playback(). The local value
47874    ** of Pager.sectorSize is restored at the end of that routine.
47875    */
47876    pPager->sectorSize = iSectorSize;
47877  }
47878
47879  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
47880  return rc;
47881}
47882
47883
47884/*
47885** Write the supplied master journal name into the journal file for pager
47886** pPager at the current location. The master journal name must be the last
47887** thing written to a journal file. If the pager is in full-sync mode, the
47888** journal file descriptor is advanced to the next sector boundary before
47889** anything is written. The format is:
47890**
47891**   + 4 bytes: PAGER_MJ_PGNO.
47892**   + N bytes: Master journal filename in utf-8.
47893**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
47894**   + 4 bytes: Master journal name checksum.
47895**   + 8 bytes: aJournalMagic[].
47896**
47897** The master journal page checksum is the sum of the bytes in the master
47898** journal name, where each byte is interpreted as a signed 8-bit integer.
47899**
47900** If zMaster is a NULL pointer (occurs for a single database transaction),
47901** this call is a no-op.
47902*/
47903static int writeMasterJournal(Pager *pPager, const char *zMaster){
47904  int rc;                          /* Return code */
47905  int nMaster;                     /* Length of string zMaster */
47906  i64 iHdrOff;                     /* Offset of header in journal file */
47907  i64 jrnlSize;                    /* Size of journal file on disk */
47908  u32 cksum = 0;                   /* Checksum of string zMaster */
47909
47910  assert( pPager->setMaster==0 );
47911  assert( !pagerUseWal(pPager) );
47912
47913  if( !zMaster
47914   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
47915   || !isOpen(pPager->jfd)
47916  ){
47917    return SQLITE_OK;
47918  }
47919  pPager->setMaster = 1;
47920  assert( pPager->journalHdr <= pPager->journalOff );
47921
47922  /* Calculate the length in bytes and the checksum of zMaster */
47923  for(nMaster=0; zMaster[nMaster]; nMaster++){
47924    cksum += zMaster[nMaster];
47925  }
47926
47927  /* If in full-sync mode, advance to the next disk sector before writing
47928  ** the master journal name. This is in case the previous page written to
47929  ** the journal has already been synced.
47930  */
47931  if( pPager->fullSync ){
47932    pPager->journalOff = journalHdrOffset(pPager);
47933  }
47934  iHdrOff = pPager->journalOff;
47935
47936  /* Write the master journal data to the end of the journal file. If
47937  ** an error occurs, return the error code to the caller.
47938  */
47939  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
47940   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
47941   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
47942   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
47943   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
47944                                 iHdrOff+4+nMaster+8)))
47945  ){
47946    return rc;
47947  }
47948  pPager->journalOff += (nMaster+20);
47949
47950  /* If the pager is in peristent-journal mode, then the physical
47951  ** journal-file may extend past the end of the master-journal name
47952  ** and 8 bytes of magic data just written to the file. This is
47953  ** dangerous because the code to rollback a hot-journal file
47954  ** will not be able to find the master-journal name to determine
47955  ** whether or not the journal is hot.
47956  **
47957  ** Easiest thing to do in this scenario is to truncate the journal
47958  ** file to the required size.
47959  */
47960  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
47961   && jrnlSize>pPager->journalOff
47962  ){
47963    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
47964  }
47965  return rc;
47966}
47967
47968/*
47969** Discard the entire contents of the in-memory page-cache.
47970*/
47971static void pager_reset(Pager *pPager){
47972  pPager->iDataVersion++;
47973  sqlite3BackupRestart(pPager->pBackup);
47974  sqlite3PcacheClear(pPager->pPCache);
47975}
47976
47977/*
47978** Return the pPager->iDataVersion value
47979*/
47980SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
47981  assert( pPager->eState>PAGER_OPEN );
47982  return pPager->iDataVersion;
47983}
47984
47985/*
47986** Free all structures in the Pager.aSavepoint[] array and set both
47987** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
47988** if it is open and the pager is not in exclusive mode.
47989*/
47990static void releaseAllSavepoints(Pager *pPager){
47991  int ii;               /* Iterator for looping through Pager.aSavepoint */
47992  for(ii=0; ii<pPager->nSavepoint; ii++){
47993    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
47994  }
47995  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
47996    sqlite3OsClose(pPager->sjfd);
47997  }
47998  sqlite3_free(pPager->aSavepoint);
47999  pPager->aSavepoint = 0;
48000  pPager->nSavepoint = 0;
48001  pPager->nSubRec = 0;
48002}
48003
48004/*
48005** Set the bit number pgno in the PagerSavepoint.pInSavepoint
48006** bitvecs of all open savepoints. Return SQLITE_OK if successful
48007** or SQLITE_NOMEM if a malloc failure occurs.
48008*/
48009static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
48010  int ii;                   /* Loop counter */
48011  int rc = SQLITE_OK;       /* Result code */
48012
48013  for(ii=0; ii<pPager->nSavepoint; ii++){
48014    PagerSavepoint *p = &pPager->aSavepoint[ii];
48015    if( pgno<=p->nOrig ){
48016      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
48017      testcase( rc==SQLITE_NOMEM );
48018      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48019    }
48020  }
48021  return rc;
48022}
48023
48024/*
48025** This function is a no-op if the pager is in exclusive mode and not
48026** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
48027** state.
48028**
48029** If the pager is not in exclusive-access mode, the database file is
48030** completely unlocked. If the file is unlocked and the file-system does
48031** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
48032** closed (if it is open).
48033**
48034** If the pager is in ERROR state when this function is called, the
48035** contents of the pager cache are discarded before switching back to
48036** the OPEN state. Regardless of whether the pager is in exclusive-mode
48037** or not, any journal file left in the file-system will be treated
48038** as a hot-journal and rolled back the next time a read-transaction
48039** is opened (by this or by any other connection).
48040*/
48041static void pager_unlock(Pager *pPager){
48042
48043  assert( pPager->eState==PAGER_READER
48044       || pPager->eState==PAGER_OPEN
48045       || pPager->eState==PAGER_ERROR
48046  );
48047
48048  sqlite3BitvecDestroy(pPager->pInJournal);
48049  pPager->pInJournal = 0;
48050  releaseAllSavepoints(pPager);
48051
48052  if( pagerUseWal(pPager) ){
48053    assert( !isOpen(pPager->jfd) );
48054    sqlite3WalEndReadTransaction(pPager->pWal);
48055    pPager->eState = PAGER_OPEN;
48056  }else if( !pPager->exclusiveMode ){
48057    int rc;                       /* Error code returned by pagerUnlockDb() */
48058    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
48059
48060    /* If the operating system support deletion of open files, then
48061    ** close the journal file when dropping the database lock.  Otherwise
48062    ** another connection with journal_mode=delete might delete the file
48063    ** out from under us.
48064    */
48065    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
48066    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
48067    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
48068    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
48069    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48070    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
48071    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
48072     || 1!=(pPager->journalMode & 5)
48073    ){
48074      sqlite3OsClose(pPager->jfd);
48075    }
48076
48077    /* If the pager is in the ERROR state and the call to unlock the database
48078    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
48079    ** above the #define for UNKNOWN_LOCK for an explanation of why this
48080    ** is necessary.
48081    */
48082    rc = pagerUnlockDb(pPager, NO_LOCK);
48083    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
48084      pPager->eLock = UNKNOWN_LOCK;
48085    }
48086
48087    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
48088    ** without clearing the error code. This is intentional - the error
48089    ** code is cleared and the cache reset in the block below.
48090    */
48091    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
48092    pPager->changeCountDone = 0;
48093    pPager->eState = PAGER_OPEN;
48094  }
48095
48096  /* If Pager.errCode is set, the contents of the pager cache cannot be
48097  ** trusted. Now that there are no outstanding references to the pager,
48098  ** it can safely move back to PAGER_OPEN state. This happens in both
48099  ** normal and exclusive-locking mode.
48100  */
48101  assert( pPager->errCode==SQLITE_OK || !MEMDB );
48102  if( pPager->errCode ){
48103    if( pPager->tempFile==0 ){
48104      pager_reset(pPager);
48105      pPager->changeCountDone = 0;
48106      pPager->eState = PAGER_OPEN;
48107    }else{
48108      pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
48109    }
48110    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48111    pPager->errCode = SQLITE_OK;
48112  }
48113
48114  pPager->journalOff = 0;
48115  pPager->journalHdr = 0;
48116  pPager->setMaster = 0;
48117}
48118
48119/*
48120** This function is called whenever an IOERR or FULL error that requires
48121** the pager to transition into the ERROR state may ahve occurred.
48122** The first argument is a pointer to the pager structure, the second
48123** the error-code about to be returned by a pager API function. The
48124** value returned is a copy of the second argument to this function.
48125**
48126** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
48127** IOERR sub-codes, the pager enters the ERROR state and the error code
48128** is stored in Pager.errCode. While the pager remains in the ERROR state,
48129** all major API calls on the Pager will immediately return Pager.errCode.
48130**
48131** The ERROR state indicates that the contents of the pager-cache
48132** cannot be trusted. This state can be cleared by completely discarding
48133** the contents of the pager-cache. If a transaction was active when
48134** the persistent error occurred, then the rollback journal may need
48135** to be replayed to restore the contents of the database file (as if
48136** it were a hot-journal).
48137*/
48138static int pager_error(Pager *pPager, int rc){
48139  int rc2 = rc & 0xff;
48140  assert( rc==SQLITE_OK || !MEMDB );
48141  assert(
48142       pPager->errCode==SQLITE_FULL ||
48143       pPager->errCode==SQLITE_OK ||
48144       (pPager->errCode & 0xff)==SQLITE_IOERR
48145  );
48146  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
48147    pPager->errCode = rc;
48148    pPager->eState = PAGER_ERROR;
48149  }
48150  return rc;
48151}
48152
48153static int pager_truncate(Pager *pPager, Pgno nPage);
48154
48155/*
48156** The write transaction open on pPager is being committed (bCommit==1)
48157** or rolled back (bCommit==0).
48158**
48159** Return TRUE if and only if all dirty pages should be flushed to disk.
48160**
48161** Rules:
48162**
48163**   *  For non-TEMP databases, always sync to disk.  This is necessary
48164**      for transactions to be durable.
48165**
48166**   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
48167**      file has been created already (via a spill on pagerStress()) and
48168**      when the number of dirty pages in memory exceeds 25% of the total
48169**      cache size.
48170*/
48171static int pagerFlushOnCommit(Pager *pPager, int bCommit){
48172  if( pPager->tempFile==0 ) return 1;
48173  if( !bCommit ) return 0;
48174  if( !isOpen(pPager->fd) ) return 0;
48175  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
48176}
48177
48178/*
48179** This routine ends a transaction. A transaction is usually ended by
48180** either a COMMIT or a ROLLBACK operation. This routine may be called
48181** after rollback of a hot-journal, or if an error occurs while opening
48182** the journal file or writing the very first journal-header of a
48183** database transaction.
48184**
48185** This routine is never called in PAGER_ERROR state. If it is called
48186** in PAGER_NONE or PAGER_SHARED state and the lock held is less
48187** exclusive than a RESERVED lock, it is a no-op.
48188**
48189** Otherwise, any active savepoints are released.
48190**
48191** If the journal file is open, then it is "finalized". Once a journal
48192** file has been finalized it is not possible to use it to roll back a
48193** transaction. Nor will it be considered to be a hot-journal by this
48194** or any other database connection. Exactly how a journal is finalized
48195** depends on whether or not the pager is running in exclusive mode and
48196** the current journal-mode (Pager.journalMode value), as follows:
48197**
48198**   journalMode==MEMORY
48199**     Journal file descriptor is simply closed. This destroys an
48200**     in-memory journal.
48201**
48202**   journalMode==TRUNCATE
48203**     Journal file is truncated to zero bytes in size.
48204**
48205**   journalMode==PERSIST
48206**     The first 28 bytes of the journal file are zeroed. This invalidates
48207**     the first journal header in the file, and hence the entire journal
48208**     file. An invalid journal file cannot be rolled back.
48209**
48210**   journalMode==DELETE
48211**     The journal file is closed and deleted using sqlite3OsDelete().
48212**
48213**     If the pager is running in exclusive mode, this method of finalizing
48214**     the journal file is never used. Instead, if the journalMode is
48215**     DELETE and the pager is in exclusive mode, the method described under
48216**     journalMode==PERSIST is used instead.
48217**
48218** After the journal is finalized, the pager moves to PAGER_READER state.
48219** If running in non-exclusive rollback mode, the lock on the file is
48220** downgraded to a SHARED_LOCK.
48221**
48222** SQLITE_OK is returned if no error occurs. If an error occurs during
48223** any of the IO operations to finalize the journal file or unlock the
48224** database then the IO error code is returned to the user. If the
48225** operation to finalize the journal file fails, then the code still
48226** tries to unlock the database file if not in exclusive mode. If the
48227** unlock operation fails as well, then the first error code related
48228** to the first error encountered (the journal finalization one) is
48229** returned.
48230*/
48231static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
48232  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
48233  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
48234
48235  /* Do nothing if the pager does not have an open write transaction
48236  ** or at least a RESERVED lock. This function may be called when there
48237  ** is no write-transaction active but a RESERVED or greater lock is
48238  ** held under two circumstances:
48239  **
48240  **   1. After a successful hot-journal rollback, it is called with
48241  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
48242  **
48243  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
48244  **      lock switches back to locking_mode=normal and then executes a
48245  **      read-transaction, this function is called with eState==PAGER_READER
48246  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
48247  */
48248  assert( assert_pager_state(pPager) );
48249  assert( pPager->eState!=PAGER_ERROR );
48250  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
48251    return SQLITE_OK;
48252  }
48253
48254  releaseAllSavepoints(pPager);
48255  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
48256  if( isOpen(pPager->jfd) ){
48257    assert( !pagerUseWal(pPager) );
48258
48259    /* Finalize the journal file. */
48260    if( sqlite3JournalIsInMemory(pPager->jfd) ){
48261      /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
48262      sqlite3OsClose(pPager->jfd);
48263    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
48264      if( pPager->journalOff==0 ){
48265        rc = SQLITE_OK;
48266      }else{
48267        rc = sqlite3OsTruncate(pPager->jfd, 0);
48268        if( rc==SQLITE_OK && pPager->fullSync ){
48269          /* Make sure the new file size is written into the inode right away.
48270          ** Otherwise the journal might resurrect following a power loss and
48271          ** cause the last transaction to roll back.  See
48272          ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
48273          */
48274          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
48275        }
48276      }
48277      pPager->journalOff = 0;
48278    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
48279      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
48280    ){
48281      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
48282      pPager->journalOff = 0;
48283    }else{
48284      /* This branch may be executed with Pager.journalMode==MEMORY if
48285      ** a hot-journal was just rolled back. In this case the journal
48286      ** file should be closed and deleted. If this connection writes to
48287      ** the database file, it will do so using an in-memory journal.
48288      */
48289      int bDelete = !pPager->tempFile;
48290      assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
48291      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
48292           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
48293           || pPager->journalMode==PAGER_JOURNALMODE_WAL
48294      );
48295      sqlite3OsClose(pPager->jfd);
48296      if( bDelete ){
48297        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
48298      }
48299    }
48300  }
48301
48302#ifdef SQLITE_CHECK_PAGES
48303  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
48304  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
48305    PgHdr *p = sqlite3PagerLookup(pPager, 1);
48306    if( p ){
48307      p->pageHash = 0;
48308      sqlite3PagerUnrefNotNull(p);
48309    }
48310  }
48311#endif
48312
48313  sqlite3BitvecDestroy(pPager->pInJournal);
48314  pPager->pInJournal = 0;
48315  pPager->nRec = 0;
48316  if( rc==SQLITE_OK ){
48317    if( pagerFlushOnCommit(pPager, bCommit) ){
48318      sqlite3PcacheCleanAll(pPager->pPCache);
48319    }else{
48320      sqlite3PcacheClearWritable(pPager->pPCache);
48321    }
48322    sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
48323  }
48324
48325  if( pagerUseWal(pPager) ){
48326    /* Drop the WAL write-lock, if any. Also, if the connection was in
48327    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
48328    ** lock held on the database file.
48329    */
48330    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
48331    assert( rc2==SQLITE_OK );
48332  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
48333    /* This branch is taken when committing a transaction in rollback-journal
48334    ** mode if the database file on disk is larger than the database image.
48335    ** At this point the journal has been finalized and the transaction
48336    ** successfully committed, but the EXCLUSIVE lock is still held on the
48337    ** file. So it is safe to truncate the database file to its minimum
48338    ** required size.  */
48339    assert( pPager->eLock==EXCLUSIVE_LOCK );
48340    rc = pager_truncate(pPager, pPager->dbSize);
48341  }
48342
48343  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
48344    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
48345    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
48346  }
48347
48348  if( !pPager->exclusiveMode
48349   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
48350  ){
48351    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
48352    pPager->changeCountDone = 0;
48353  }
48354  pPager->eState = PAGER_READER;
48355  pPager->setMaster = 0;
48356
48357  return (rc==SQLITE_OK?rc2:rc);
48358}
48359
48360/*
48361** Execute a rollback if a transaction is active and unlock the
48362** database file.
48363**
48364** If the pager has already entered the ERROR state, do not attempt
48365** the rollback at this time. Instead, pager_unlock() is called. The
48366** call to pager_unlock() will discard all in-memory pages, unlock
48367** the database file and move the pager back to OPEN state. If this
48368** means that there is a hot-journal left in the file-system, the next
48369** connection to obtain a shared lock on the pager (which may be this one)
48370** will roll it back.
48371**
48372** If the pager has not already entered the ERROR state, but an IO or
48373** malloc error occurs during a rollback, then this will itself cause
48374** the pager to enter the ERROR state. Which will be cleared by the
48375** call to pager_unlock(), as described above.
48376*/
48377static void pagerUnlockAndRollback(Pager *pPager){
48378  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
48379    assert( assert_pager_state(pPager) );
48380    if( pPager->eState>=PAGER_WRITER_LOCKED ){
48381      sqlite3BeginBenignMalloc();
48382      sqlite3PagerRollback(pPager);
48383      sqlite3EndBenignMalloc();
48384    }else if( !pPager->exclusiveMode ){
48385      assert( pPager->eState==PAGER_READER );
48386      pager_end_transaction(pPager, 0, 0);
48387    }
48388  }
48389  pager_unlock(pPager);
48390}
48391
48392/*
48393** Parameter aData must point to a buffer of pPager->pageSize bytes
48394** of data. Compute and return a checksum based ont the contents of the
48395** page of data and the current value of pPager->cksumInit.
48396**
48397** This is not a real checksum. It is really just the sum of the
48398** random initial value (pPager->cksumInit) and every 200th byte
48399** of the page data, starting with byte offset (pPager->pageSize%200).
48400** Each byte is interpreted as an 8-bit unsigned integer.
48401**
48402** Changing the formula used to compute this checksum results in an
48403** incompatible journal file format.
48404**
48405** If journal corruption occurs due to a power failure, the most likely
48406** scenario is that one end or the other of the record will be changed.
48407** It is much less likely that the two ends of the journal record will be
48408** correct and the middle be corrupt.  Thus, this "checksum" scheme,
48409** though fast and simple, catches the mostly likely kind of corruption.
48410*/
48411static u32 pager_cksum(Pager *pPager, const u8 *aData){
48412  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
48413  int i = pPager->pageSize-200;          /* Loop counter */
48414  while( i>0 ){
48415    cksum += aData[i];
48416    i -= 200;
48417  }
48418  return cksum;
48419}
48420
48421/*
48422** Report the current page size and number of reserved bytes back
48423** to the codec.
48424*/
48425#ifdef SQLITE_HAS_CODEC
48426static void pagerReportSize(Pager *pPager){
48427  if( pPager->xCodecSizeChng ){
48428    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
48429                           (int)pPager->nReserve);
48430  }
48431}
48432#else
48433# define pagerReportSize(X)     /* No-op if we do not support a codec */
48434#endif
48435
48436#ifdef SQLITE_HAS_CODEC
48437/*
48438** Make sure the number of reserved bits is the same in the destination
48439** pager as it is in the source.  This comes up when a VACUUM changes the
48440** number of reserved bits to the "optimal" amount.
48441*/
48442SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
48443  if( pDest->nReserve!=pSrc->nReserve ){
48444    pDest->nReserve = pSrc->nReserve;
48445    pagerReportSize(pDest);
48446  }
48447}
48448#endif
48449
48450/*
48451** Read a single page from either the journal file (if isMainJrnl==1) or
48452** from the sub-journal (if isMainJrnl==0) and playback that page.
48453** The page begins at offset *pOffset into the file. The *pOffset
48454** value is increased to the start of the next page in the journal.
48455**
48456** The main rollback journal uses checksums - the statement journal does
48457** not.
48458**
48459** If the page number of the page record read from the (sub-)journal file
48460** is greater than the current value of Pager.dbSize, then playback is
48461** skipped and SQLITE_OK is returned.
48462**
48463** If pDone is not NULL, then it is a record of pages that have already
48464** been played back.  If the page at *pOffset has already been played back
48465** (if the corresponding pDone bit is set) then skip the playback.
48466** Make sure the pDone bit corresponding to the *pOffset page is set
48467** prior to returning.
48468**
48469** If the page record is successfully read from the (sub-)journal file
48470** and played back, then SQLITE_OK is returned. If an IO error occurs
48471** while reading the record from the (sub-)journal file or while writing
48472** to the database file, then the IO error code is returned. If data
48473** is successfully read from the (sub-)journal file but appears to be
48474** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
48475** two circumstances:
48476**
48477**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
48478**   * If the record is being rolled back from the main journal file
48479**     and the checksum field does not match the record content.
48480**
48481** Neither of these two scenarios are possible during a savepoint rollback.
48482**
48483** If this is a savepoint rollback, then memory may have to be dynamically
48484** allocated by this function. If this is the case and an allocation fails,
48485** SQLITE_NOMEM is returned.
48486*/
48487static int pager_playback_one_page(
48488  Pager *pPager,                /* The pager being played back */
48489  i64 *pOffset,                 /* Offset of record to playback */
48490  Bitvec *pDone,                /* Bitvec of pages already played back */
48491  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
48492  int isSavepnt                 /* True for a savepoint rollback */
48493){
48494  int rc;
48495  PgHdr *pPg;                   /* An existing page in the cache */
48496  Pgno pgno;                    /* The page number of a page in journal */
48497  u32 cksum;                    /* Checksum used for sanity checking */
48498  char *aData;                  /* Temporary storage for the page */
48499  sqlite3_file *jfd;            /* The file descriptor for the journal file */
48500  int isSynced;                 /* True if journal page is synced */
48501
48502  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
48503  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
48504  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
48505  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
48506
48507  aData = pPager->pTmpSpace;
48508  assert( aData );         /* Temp storage must have already been allocated */
48509  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
48510
48511  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
48512  ** or savepoint rollback done at the request of the caller) or this is
48513  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
48514  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
48515  ** only reads from the main journal, not the sub-journal.
48516  */
48517  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
48518       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
48519  );
48520  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
48521
48522  /* Read the page number and page data from the journal or sub-journal
48523  ** file. Return an error code to the caller if an IO error occurs.
48524  */
48525  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
48526  rc = read32bits(jfd, *pOffset, &pgno);
48527  if( rc!=SQLITE_OK ) return rc;
48528  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
48529  if( rc!=SQLITE_OK ) return rc;
48530  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
48531
48532  /* Sanity checking on the page.  This is more important that I originally
48533  ** thought.  If a power failure occurs while the journal is being written,
48534  ** it could cause invalid data to be written into the journal.  We need to
48535  ** detect this invalid data (with high probability) and ignore it.
48536  */
48537  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
48538    assert( !isSavepnt );
48539    return SQLITE_DONE;
48540  }
48541  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
48542    return SQLITE_OK;
48543  }
48544  if( isMainJrnl ){
48545    rc = read32bits(jfd, (*pOffset)-4, &cksum);
48546    if( rc ) return rc;
48547    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
48548      return SQLITE_DONE;
48549    }
48550  }
48551
48552  /* If this page has already been played back before during the current
48553  ** rollback, then don't bother to play it back again.
48554  */
48555  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
48556    return rc;
48557  }
48558
48559  /* When playing back page 1, restore the nReserve setting
48560  */
48561  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
48562    pPager->nReserve = ((u8*)aData)[20];
48563    pagerReportSize(pPager);
48564  }
48565
48566  /* If the pager is in CACHEMOD state, then there must be a copy of this
48567  ** page in the pager cache. In this case just update the pager cache,
48568  ** not the database file. The page is left marked dirty in this case.
48569  **
48570  ** An exception to the above rule: If the database is in no-sync mode
48571  ** and a page is moved during an incremental vacuum then the page may
48572  ** not be in the pager cache. Later: if a malloc() or IO error occurs
48573  ** during a Movepage() call, then the page may not be in the cache
48574  ** either. So the condition described in the above paragraph is not
48575  ** assert()able.
48576  **
48577  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
48578  ** pager cache if it exists and the main file. The page is then marked
48579  ** not dirty. Since this code is only executed in PAGER_OPEN state for
48580  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
48581  ** if the pager is in OPEN state.
48582  **
48583  ** Ticket #1171:  The statement journal might contain page content that is
48584  ** different from the page content at the start of the transaction.
48585  ** This occurs when a page is changed prior to the start of a statement
48586  ** then changed again within the statement.  When rolling back such a
48587  ** statement we must not write to the original database unless we know
48588  ** for certain that original page contents are synced into the main rollback
48589  ** journal.  Otherwise, a power loss might leave modified data in the
48590  ** database file without an entry in the rollback journal that can
48591  ** restore the database to its original form.  Two conditions must be
48592  ** met before writing to the database files. (1) the database must be
48593  ** locked.  (2) we know that the original page content is fully synced
48594  ** in the main journal either because the page is not in cache or else
48595  ** the page is marked as needSync==0.
48596  **
48597  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
48598  ** is possible to fail a statement on a database that does not yet exist.
48599  ** Do not attempt to write if database file has never been opened.
48600  */
48601  if( pagerUseWal(pPager) ){
48602    pPg = 0;
48603  }else{
48604    pPg = sqlite3PagerLookup(pPager, pgno);
48605  }
48606  assert( pPg || !MEMDB );
48607  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48608  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48609           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48610           (isMainJrnl?"main-journal":"sub-journal")
48611  ));
48612  if( isMainJrnl ){
48613    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
48614  }else{
48615    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
48616  }
48617  if( isOpen(pPager->fd)
48618   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48619   && isSynced
48620  ){
48621    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
48622    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
48623    assert( !pagerUseWal(pPager) );
48624    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
48625    if( pgno>pPager->dbFileSize ){
48626      pPager->dbFileSize = pgno;
48627    }
48628    if( pPager->pBackup ){
48629      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
48630      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
48631      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
48632    }
48633  }else if( !isMainJrnl && pPg==0 ){
48634    /* If this is a rollback of a savepoint and data was not written to
48635    ** the database and the page is not in-memory, there is a potential
48636    ** problem. When the page is next fetched by the b-tree layer, it
48637    ** will be read from the database file, which may or may not be
48638    ** current.
48639    **
48640    ** There are a couple of different ways this can happen. All are quite
48641    ** obscure. When running in synchronous mode, this can only happen
48642    ** if the page is on the free-list at the start of the transaction, then
48643    ** populated, then moved using sqlite3PagerMovepage().
48644    **
48645    ** The solution is to add an in-memory page to the cache containing
48646    ** the data just read from the sub-journal. Mark the page as dirty
48647    ** and if the pager requires a journal-sync, then mark the page as
48648    ** requiring a journal-sync before it is written.
48649    */
48650    assert( isSavepnt );
48651    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
48652    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48653    rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48654    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48655    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48656    if( rc!=SQLITE_OK ) return rc;
48657    sqlite3PcacheMakeDirty(pPg);
48658  }
48659  if( pPg ){
48660    /* No page should ever be explicitly rolled back that is in use, except
48661    ** for page 1 which is held in use in order to keep the lock on the
48662    ** database active. However such a page may be rolled back as a result
48663    ** of an internal error resulting in an automatic call to
48664    ** sqlite3PagerRollback().
48665    */
48666    void *pData;
48667    pData = pPg->pData;
48668    memcpy(pData, (u8*)aData, pPager->pageSize);
48669    pPager->xReiniter(pPg);
48670    /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
48671    ** that call was dangerous and had no detectable benefit since the cache
48672    ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48673    ** has been removed. */
48674    pager_set_pagehash(pPg);
48675
48676    /* If this was page 1, then restore the value of Pager.dbFileVers.
48677    ** Do this before any decoding. */
48678    if( pgno==1 ){
48679      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
48680    }
48681
48682    /* Decode the page just read from disk */
48683    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
48684    sqlite3PcacheRelease(pPg);
48685  }
48686  return rc;
48687}
48688
48689/*
48690** Parameter zMaster is the name of a master journal file. A single journal
48691** file that referred to the master journal file has just been rolled back.
48692** This routine checks if it is possible to delete the master journal file,
48693** and does so if it is.
48694**
48695** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
48696** available for use within this function.
48697**
48698** When a master journal file is created, it is populated with the names
48699** of all of its child journals, one after another, formatted as utf-8
48700** encoded text. The end of each child journal file is marked with a
48701** nul-terminator byte (0x00). i.e. the entire contents of a master journal
48702** file for a transaction involving two databases might be:
48703**
48704**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
48705**
48706** A master journal file may only be deleted once all of its child
48707** journals have been rolled back.
48708**
48709** This function reads the contents of the master-journal file into
48710** memory and loops through each of the child journal names. For
48711** each child journal, it checks if:
48712**
48713**   * if the child journal exists, and if so
48714**   * if the child journal contains a reference to master journal
48715**     file zMaster
48716**
48717** If a child journal can be found that matches both of the criteria
48718** above, this function returns without doing anything. Otherwise, if
48719** no such child journal can be found, file zMaster is deleted from
48720** the file-system using sqlite3OsDelete().
48721**
48722** If an IO error within this function, an error code is returned. This
48723** function allocates memory by calling sqlite3Malloc(). If an allocation
48724** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
48725** occur, SQLITE_OK is returned.
48726**
48727** TODO: This function allocates a single block of memory to load
48728** the entire contents of the master journal file. This could be
48729** a couple of kilobytes or so - potentially larger than the page
48730** size.
48731*/
48732static int pager_delmaster(Pager *pPager, const char *zMaster){
48733  sqlite3_vfs *pVfs = pPager->pVfs;
48734  int rc;                   /* Return code */
48735  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
48736  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
48737  char *zMasterJournal = 0; /* Contents of master journal file */
48738  i64 nMasterJournal;       /* Size of master journal file */
48739  char *zJournal;           /* Pointer to one journal within MJ file */
48740  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
48741  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
48742
48743  /* Allocate space for both the pJournal and pMaster file descriptors.
48744  ** If successful, open the master journal file for reading.
48745  */
48746  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
48747  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
48748  if( !pMaster ){
48749    rc = SQLITE_NOMEM_BKPT;
48750  }else{
48751    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
48752    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
48753  }
48754  if( rc!=SQLITE_OK ) goto delmaster_out;
48755
48756  /* Load the entire master journal file into space obtained from
48757  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
48758  ** sufficient space (in zMasterPtr) to hold the names of master
48759  ** journal files extracted from regular rollback-journals.
48760  */
48761  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
48762  if( rc!=SQLITE_OK ) goto delmaster_out;
48763  nMasterPtr = pVfs->mxPathname+1;
48764  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
48765  if( !zMasterJournal ){
48766    rc = SQLITE_NOMEM_BKPT;
48767    goto delmaster_out;
48768  }
48769  zMasterPtr = &zMasterJournal[nMasterJournal+1];
48770  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
48771  if( rc!=SQLITE_OK ) goto delmaster_out;
48772  zMasterJournal[nMasterJournal] = 0;
48773
48774  zJournal = zMasterJournal;
48775  while( (zJournal-zMasterJournal)<nMasterJournal ){
48776    int exists;
48777    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
48778    if( rc!=SQLITE_OK ){
48779      goto delmaster_out;
48780    }
48781    if( exists ){
48782      /* One of the journals pointed to by the master journal exists.
48783      ** Open it and check if it points at the master journal. If
48784      ** so, return without deleting the master journal file.
48785      */
48786      int c;
48787      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
48788      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
48789      if( rc!=SQLITE_OK ){
48790        goto delmaster_out;
48791      }
48792
48793      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
48794      sqlite3OsClose(pJournal);
48795      if( rc!=SQLITE_OK ){
48796        goto delmaster_out;
48797      }
48798
48799      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
48800      if( c ){
48801        /* We have a match. Do not delete the master journal file. */
48802        goto delmaster_out;
48803      }
48804    }
48805    zJournal += (sqlite3Strlen30(zJournal)+1);
48806  }
48807
48808  sqlite3OsClose(pMaster);
48809  rc = sqlite3OsDelete(pVfs, zMaster, 0);
48810
48811delmaster_out:
48812  sqlite3_free(zMasterJournal);
48813  if( pMaster ){
48814    sqlite3OsClose(pMaster);
48815    assert( !isOpen(pJournal) );
48816    sqlite3_free(pMaster);
48817  }
48818  return rc;
48819}
48820
48821
48822/*
48823** This function is used to change the actual size of the database
48824** file in the file-system. This only happens when committing a transaction,
48825** or rolling back a transaction (including rolling back a hot-journal).
48826**
48827** If the main database file is not open, or the pager is not in either
48828** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
48829** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
48830** If the file on disk is currently larger than nPage pages, then use the VFS
48831** xTruncate() method to truncate it.
48832**
48833** Or, it might be the case that the file on disk is smaller than
48834** nPage pages. Some operating system implementations can get confused if
48835** you try to truncate a file to some size that is larger than it
48836** currently is, so detect this case and write a single zero byte to
48837** the end of the new file instead.
48838**
48839** If successful, return SQLITE_OK. If an IO error occurs while modifying
48840** the database file, return the error code to the caller.
48841*/
48842static int pager_truncate(Pager *pPager, Pgno nPage){
48843  int rc = SQLITE_OK;
48844  assert( pPager->eState!=PAGER_ERROR );
48845  assert( pPager->eState!=PAGER_READER );
48846
48847  if( isOpen(pPager->fd)
48848   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48849  ){
48850    i64 currentSize, newSize;
48851    int szPage = pPager->pageSize;
48852    assert( pPager->eLock==EXCLUSIVE_LOCK );
48853    /* TODO: Is it safe to use Pager.dbFileSize here? */
48854    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
48855    newSize = szPage*(i64)nPage;
48856    if( rc==SQLITE_OK && currentSize!=newSize ){
48857      if( currentSize>newSize ){
48858        rc = sqlite3OsTruncate(pPager->fd, newSize);
48859      }else if( (currentSize+szPage)<=newSize ){
48860        char *pTmp = pPager->pTmpSpace;
48861        memset(pTmp, 0, szPage);
48862        testcase( (newSize-szPage) == currentSize );
48863        testcase( (newSize-szPage) >  currentSize );
48864        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
48865      }
48866      if( rc==SQLITE_OK ){
48867        pPager->dbFileSize = nPage;
48868      }
48869    }
48870  }
48871  return rc;
48872}
48873
48874/*
48875** Return a sanitized version of the sector-size of OS file pFile. The
48876** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
48877*/
48878SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
48879  int iRet = sqlite3OsSectorSize(pFile);
48880  if( iRet<32 ){
48881    iRet = 512;
48882  }else if( iRet>MAX_SECTOR_SIZE ){
48883    assert( MAX_SECTOR_SIZE>=512 );
48884    iRet = MAX_SECTOR_SIZE;
48885  }
48886  return iRet;
48887}
48888
48889/*
48890** Set the value of the Pager.sectorSize variable for the given
48891** pager based on the value returned by the xSectorSize method
48892** of the open database file. The sector size will be used
48893** to determine the size and alignment of journal header and
48894** master journal pointers within created journal files.
48895**
48896** For temporary files the effective sector size is always 512 bytes.
48897**
48898** Otherwise, for non-temporary files, the effective sector size is
48899** the value returned by the xSectorSize() method rounded up to 32 if
48900** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
48901** is greater than MAX_SECTOR_SIZE.
48902**
48903** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
48904** the effective sector size to its minimum value (512).  The purpose of
48905** pPager->sectorSize is to define the "blast radius" of bytes that
48906** might change if a crash occurs while writing to a single byte in
48907** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
48908** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
48909** size.  For backwards compatibility of the rollback journal file format,
48910** we cannot reduce the effective sector size below 512.
48911*/
48912static void setSectorSize(Pager *pPager){
48913  assert( isOpen(pPager->fd) || pPager->tempFile );
48914
48915  if( pPager->tempFile
48916   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
48917              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
48918  ){
48919    /* Sector size doesn't matter for temporary files. Also, the file
48920    ** may not have been opened yet, in which case the OsSectorSize()
48921    ** call will segfault. */
48922    pPager->sectorSize = 512;
48923  }else{
48924    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
48925  }
48926}
48927
48928/*
48929** Playback the journal and thus restore the database file to
48930** the state it was in before we started making changes.
48931**
48932** The journal file format is as follows:
48933**
48934**  (1)  8 byte prefix.  A copy of aJournalMagic[].
48935**  (2)  4 byte big-endian integer which is the number of valid page records
48936**       in the journal.  If this value is 0xffffffff, then compute the
48937**       number of page records from the journal size.
48938**  (3)  4 byte big-endian integer which is the initial value for the
48939**       sanity checksum.
48940**  (4)  4 byte integer which is the number of pages to truncate the
48941**       database to during a rollback.
48942**  (5)  4 byte big-endian integer which is the sector size.  The header
48943**       is this many bytes in size.
48944**  (6)  4 byte big-endian integer which is the page size.
48945**  (7)  zero padding out to the next sector size.
48946**  (8)  Zero or more pages instances, each as follows:
48947**        +  4 byte page number.
48948**        +  pPager->pageSize bytes of data.
48949**        +  4 byte checksum
48950**
48951** When we speak of the journal header, we mean the first 7 items above.
48952** Each entry in the journal is an instance of the 8th item.
48953**
48954** Call the value from the second bullet "nRec".  nRec is the number of
48955** valid page entries in the journal.  In most cases, you can compute the
48956** value of nRec from the size of the journal file.  But if a power
48957** failure occurred while the journal was being written, it could be the
48958** case that the size of the journal file had already been increased but
48959** the extra entries had not yet made it safely to disk.  In such a case,
48960** the value of nRec computed from the file size would be too large.  For
48961** that reason, we always use the nRec value in the header.
48962**
48963** If the nRec value is 0xffffffff it means that nRec should be computed
48964** from the file size.  This value is used when the user selects the
48965** no-sync option for the journal.  A power failure could lead to corruption
48966** in this case.  But for things like temporary table (which will be
48967** deleted when the power is restored) we don't care.
48968**
48969** If the file opened as the journal file is not a well-formed
48970** journal file then all pages up to the first corrupted page are rolled
48971** back (or no pages if the journal header is corrupted). The journal file
48972** is then deleted and SQLITE_OK returned, just as if no corruption had
48973** been encountered.
48974**
48975** If an I/O or malloc() error occurs, the journal-file is not deleted
48976** and an error code is returned.
48977**
48978** The isHot parameter indicates that we are trying to rollback a journal
48979** that might be a hot journal.  Or, it could be that the journal is
48980** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
48981** If the journal really is hot, reset the pager cache prior rolling
48982** back any content.  If the journal is merely persistent, no reset is
48983** needed.
48984*/
48985static int pager_playback(Pager *pPager, int isHot){
48986  sqlite3_vfs *pVfs = pPager->pVfs;
48987  i64 szJ;                 /* Size of the journal file in bytes */
48988  u32 nRec;                /* Number of Records in the journal */
48989  u32 u;                   /* Unsigned loop counter */
48990  Pgno mxPg = 0;           /* Size of the original file in pages */
48991  int rc;                  /* Result code of a subroutine */
48992  int res = 1;             /* Value returned by sqlite3OsAccess() */
48993  char *zMaster = 0;       /* Name of master journal file if any */
48994  int needPagerReset;      /* True to reset page prior to first page rollback */
48995  int nPlayback = 0;       /* Total number of pages restored from journal */
48996
48997  /* Figure out how many records are in the journal.  Abort early if
48998  ** the journal is empty.
48999  */
49000  assert( isOpen(pPager->jfd) );
49001  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
49002  if( rc!=SQLITE_OK ){
49003    goto end_playback;
49004  }
49005
49006  /* Read the master journal name from the journal, if it is present.
49007  ** If a master journal file name is specified, but the file is not
49008  ** present on disk, then the journal is not hot and does not need to be
49009  ** played back.
49010  **
49011  ** TODO: Technically the following is an error because it assumes that
49012  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
49013  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
49014  ** mxPathname is 512, which is the same as the minimum allowable value
49015  ** for pageSize.
49016  */
49017  zMaster = pPager->pTmpSpace;
49018  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49019  if( rc==SQLITE_OK && zMaster[0] ){
49020    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49021  }
49022  zMaster = 0;
49023  if( rc!=SQLITE_OK || !res ){
49024    goto end_playback;
49025  }
49026  pPager->journalOff = 0;
49027  needPagerReset = isHot;
49028
49029  /* This loop terminates either when a readJournalHdr() or
49030  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
49031  ** occurs.
49032  */
49033  while( 1 ){
49034    /* Read the next journal header from the journal file.  If there are
49035    ** not enough bytes left in the journal file for a complete header, or
49036    ** it is corrupted, then a process must have failed while writing it.
49037    ** This indicates nothing more needs to be rolled back.
49038    */
49039    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
49040    if( rc!=SQLITE_OK ){
49041      if( rc==SQLITE_DONE ){
49042        rc = SQLITE_OK;
49043      }
49044      goto end_playback;
49045    }
49046
49047    /* If nRec is 0xffffffff, then this journal was created by a process
49048    ** working in no-sync mode. This means that the rest of the journal
49049    ** file consists of pages, there are no more journal headers. Compute
49050    ** the value of nRec based on this assumption.
49051    */
49052    if( nRec==0xffffffff ){
49053      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49054      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
49055    }
49056
49057    /* If nRec is 0 and this rollback is of a transaction created by this
49058    ** process and if this is the final header in the journal, then it means
49059    ** that this part of the journal was being filled but has not yet been
49060    ** synced to disk.  Compute the number of pages based on the remaining
49061    ** size of the file.
49062    **
49063    ** The third term of the test was added to fix ticket #2565.
49064    ** When rolling back a hot journal, nRec==0 always means that the next
49065    ** chunk of the journal contains zero pages to be rolled back.  But
49066    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
49067    ** the journal, it means that the journal might contain additional
49068    ** pages that need to be rolled back and that the number of pages
49069    ** should be computed based on the journal file size.
49070    */
49071    if( nRec==0 && !isHot &&
49072        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
49073      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
49074    }
49075
49076    /* If this is the first header read from the journal, truncate the
49077    ** database file back to its original size.
49078    */
49079    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49080      rc = pager_truncate(pPager, mxPg);
49081      if( rc!=SQLITE_OK ){
49082        goto end_playback;
49083      }
49084      pPager->dbSize = mxPg;
49085    }
49086
49087    /* Copy original pages out of the journal and back into the
49088    ** database file and/or page cache.
49089    */
49090    for(u=0; u<nRec; u++){
49091      if( needPagerReset ){
49092        pager_reset(pPager);
49093        needPagerReset = 0;
49094      }
49095      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
49096      if( rc==SQLITE_OK ){
49097        nPlayback++;
49098      }else{
49099        if( rc==SQLITE_DONE ){
49100          pPager->journalOff = szJ;
49101          break;
49102        }else if( rc==SQLITE_IOERR_SHORT_READ ){
49103          /* If the journal has been truncated, simply stop reading and
49104          ** processing the journal. This might happen if the journal was
49105          ** not completely written and synced prior to a crash.  In that
49106          ** case, the database should have never been written in the
49107          ** first place so it is OK to simply abandon the rollback. */
49108          rc = SQLITE_OK;
49109          goto end_playback;
49110        }else{
49111          /* If we are unable to rollback, quit and return the error
49112          ** code.  This will cause the pager to enter the error state
49113          ** so that no further harm will be done.  Perhaps the next
49114          ** process to come along will be able to rollback the database.
49115          */
49116          goto end_playback;
49117        }
49118      }
49119    }
49120  }
49121  /*NOTREACHED*/
49122  assert( 0 );
49123
49124end_playback:
49125  /* Following a rollback, the database file should be back in its original
49126  ** state prior to the start of the transaction, so invoke the
49127  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
49128  ** assertion that the transaction counter was modified.
49129  */
49130#ifdef SQLITE_DEBUG
49131  if( pPager->fd->pMethods ){
49132    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
49133  }
49134#endif
49135
49136  /* If this playback is happening automatically as a result of an IO or
49137  ** malloc error that occurred after the change-counter was updated but
49138  ** before the transaction was committed, then the change-counter
49139  ** modification may just have been reverted. If this happens in exclusive
49140  ** mode, then subsequent transactions performed by the connection will not
49141  ** update the change-counter at all. This may lead to cache inconsistency
49142  ** problems for other processes at some point in the future. So, just
49143  ** in case this has happened, clear the changeCountDone flag now.
49144  */
49145  pPager->changeCountDone = pPager->tempFile;
49146
49147  if( rc==SQLITE_OK ){
49148    zMaster = pPager->pTmpSpace;
49149    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49150    testcase( rc!=SQLITE_OK );
49151  }
49152  if( rc==SQLITE_OK
49153   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49154  ){
49155    rc = sqlite3PagerSync(pPager, 0);
49156  }
49157  if( rc==SQLITE_OK ){
49158    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
49159    testcase( rc!=SQLITE_OK );
49160  }
49161  if( rc==SQLITE_OK && zMaster[0] && res ){
49162    /* If there was a master journal and this routine will return success,
49163    ** see if it is possible to delete the master journal.
49164    */
49165    rc = pager_delmaster(pPager, zMaster);
49166    testcase( rc!=SQLITE_OK );
49167  }
49168  if( isHot && nPlayback ){
49169    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
49170                nPlayback, pPager->zJournal);
49171  }
49172
49173  /* The Pager.sectorSize variable may have been updated while rolling
49174  ** back a journal created by a process with a different sector size
49175  ** value. Reset it to the correct value for this process.
49176  */
49177  setSectorSize(pPager);
49178  return rc;
49179}
49180
49181
49182/*
49183** Read the content for page pPg out of the database file and into
49184** pPg->pData. A shared lock or greater must be held on the database
49185** file before this function is called.
49186**
49187** If page 1 is read, then the value of Pager.dbFileVers[] is set to
49188** the value read from the database file.
49189**
49190** If an IO error occurs, then the IO error is returned to the caller.
49191** Otherwise, SQLITE_OK is returned.
49192*/
49193static int readDbPage(PgHdr *pPg, u32 iFrame){
49194  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
49195  Pgno pgno = pPg->pgno;       /* Page number to read */
49196  int rc = SQLITE_OK;          /* Return code */
49197  int pgsz = pPager->pageSize; /* Number of bytes to read */
49198
49199  assert( pPager->eState>=PAGER_READER && !MEMDB );
49200  assert( isOpen(pPager->fd) );
49201
49202#ifndef SQLITE_OMIT_WAL
49203  if( iFrame ){
49204    /* Try to pull the page from the write-ahead log. */
49205    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
49206  }else
49207#endif
49208  {
49209    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
49210    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
49211    if( rc==SQLITE_IOERR_SHORT_READ ){
49212      rc = SQLITE_OK;
49213    }
49214  }
49215
49216  if( pgno==1 ){
49217    if( rc ){
49218      /* If the read is unsuccessful, set the dbFileVers[] to something
49219      ** that will never be a valid file version.  dbFileVers[] is a copy
49220      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
49221      ** zero or the size of the database in page. Bytes 32..35 and 35..39
49222      ** should be page numbers which are never 0xffffffff.  So filling
49223      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
49224      **
49225      ** For an encrypted database, the situation is more complex:  bytes
49226      ** 24..39 of the database are white noise.  But the probability of
49227      ** white noise equaling 16 bytes of 0xff is vanishingly small so
49228      ** we should still be ok.
49229      */
49230      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
49231    }else{
49232      u8 *dbFileVers = &((u8*)pPg->pData)[24];
49233      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
49234    }
49235  }
49236  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
49237
49238  PAGER_INCR(sqlite3_pager_readdb_count);
49239  PAGER_INCR(pPager->nRead);
49240  IOTRACE(("PGIN %p %d\n", pPager, pgno));
49241  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
49242               PAGERID(pPager), pgno, pager_pagehash(pPg)));
49243
49244  return rc;
49245}
49246
49247/*
49248** Update the value of the change-counter at offsets 24 and 92 in
49249** the header and the sqlite version number at offset 96.
49250**
49251** This is an unconditional update.  See also the pager_incr_changecounter()
49252** routine which only updates the change-counter if the update is actually
49253** needed, as determined by the pPager->changeCountDone state variable.
49254*/
49255static void pager_write_changecounter(PgHdr *pPg){
49256  u32 change_counter;
49257
49258  /* Increment the value just read and write it back to byte 24. */
49259  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
49260  put32bits(((char*)pPg->pData)+24, change_counter);
49261
49262  /* Also store the SQLite version number in bytes 96..99 and in
49263  ** bytes 92..95 store the change counter for which the version number
49264  ** is valid. */
49265  put32bits(((char*)pPg->pData)+92, change_counter);
49266  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
49267}
49268
49269#ifndef SQLITE_OMIT_WAL
49270/*
49271** This function is invoked once for each page that has already been
49272** written into the log file when a WAL transaction is rolled back.
49273** Parameter iPg is the page number of said page. The pCtx argument
49274** is actually a pointer to the Pager structure.
49275**
49276** If page iPg is present in the cache, and has no outstanding references,
49277** it is discarded. Otherwise, if there are one or more outstanding
49278** references, the page content is reloaded from the database. If the
49279** attempt to reload content from the database is required and fails,
49280** return an SQLite error code. Otherwise, SQLITE_OK.
49281*/
49282static int pagerUndoCallback(void *pCtx, Pgno iPg){
49283  int rc = SQLITE_OK;
49284  Pager *pPager = (Pager *)pCtx;
49285  PgHdr *pPg;
49286
49287  assert( pagerUseWal(pPager) );
49288  pPg = sqlite3PagerLookup(pPager, iPg);
49289  if( pPg ){
49290    if( sqlite3PcachePageRefcount(pPg)==1 ){
49291      sqlite3PcacheDrop(pPg);
49292    }else{
49293      u32 iFrame = 0;
49294      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
49295      if( rc==SQLITE_OK ){
49296        rc = readDbPage(pPg, iFrame);
49297      }
49298      if( rc==SQLITE_OK ){
49299        pPager->xReiniter(pPg);
49300      }
49301      sqlite3PagerUnrefNotNull(pPg);
49302    }
49303  }
49304
49305  /* Normally, if a transaction is rolled back, any backup processes are
49306  ** updated as data is copied out of the rollback journal and into the
49307  ** database. This is not generally possible with a WAL database, as
49308  ** rollback involves simply truncating the log file. Therefore, if one
49309  ** or more frames have already been written to the log (and therefore
49310  ** also copied into the backup databases) as part of this transaction,
49311  ** the backups must be restarted.
49312  */
49313  sqlite3BackupRestart(pPager->pBackup);
49314
49315  return rc;
49316}
49317
49318/*
49319** This function is called to rollback a transaction on a WAL database.
49320*/
49321static int pagerRollbackWal(Pager *pPager){
49322  int rc;                         /* Return Code */
49323  PgHdr *pList;                   /* List of dirty pages to revert */
49324
49325  /* For all pages in the cache that are currently dirty or have already
49326  ** been written (but not committed) to the log file, do one of the
49327  ** following:
49328  **
49329  **   + Discard the cached page (if refcount==0), or
49330  **   + Reload page content from the database (if refcount>0).
49331  */
49332  pPager->dbSize = pPager->dbOrigSize;
49333  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
49334  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49335  while( pList && rc==SQLITE_OK ){
49336    PgHdr *pNext = pList->pDirty;
49337    rc = pagerUndoCallback((void *)pPager, pList->pgno);
49338    pList = pNext;
49339  }
49340
49341  return rc;
49342}
49343
49344/*
49345** This function is a wrapper around sqlite3WalFrames(). As well as logging
49346** the contents of the list of pages headed by pList (connected by pDirty),
49347** this function notifies any active backup processes that the pages have
49348** changed.
49349**
49350** The list of pages passed into this routine is always sorted by page number.
49351** Hence, if page 1 appears anywhere on the list, it will be the first page.
49352*/
49353static int pagerWalFrames(
49354  Pager *pPager,                  /* Pager object */
49355  PgHdr *pList,                   /* List of frames to log */
49356  Pgno nTruncate,                 /* Database size after this commit */
49357  int isCommit                    /* True if this is a commit */
49358){
49359  int rc;                         /* Return code */
49360  int nList;                      /* Number of pages in pList */
49361  PgHdr *p;                       /* For looping over pages */
49362
49363  assert( pPager->pWal );
49364  assert( pList );
49365#ifdef SQLITE_DEBUG
49366  /* Verify that the page list is in accending order */
49367  for(p=pList; p && p->pDirty; p=p->pDirty){
49368    assert( p->pgno < p->pDirty->pgno );
49369  }
49370#endif
49371
49372  assert( pList->pDirty==0 || isCommit );
49373  if( isCommit ){
49374    /* If a WAL transaction is being committed, there is no point in writing
49375    ** any pages with page numbers greater than nTruncate into the WAL file.
49376    ** They will never be read by any client. So remove them from the pDirty
49377    ** list here. */
49378    PgHdr **ppNext = &pList;
49379    nList = 0;
49380    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
49381      if( p->pgno<=nTruncate ){
49382        ppNext = &p->pDirty;
49383        nList++;
49384      }
49385    }
49386    assert( pList );
49387  }else{
49388    nList = 1;
49389  }
49390  pPager->aStat[PAGER_STAT_WRITE] += nList;
49391
49392  if( pList->pgno==1 ) pager_write_changecounter(pList);
49393  rc = sqlite3WalFrames(pPager->pWal,
49394      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
49395  );
49396  if( rc==SQLITE_OK && pPager->pBackup ){
49397    for(p=pList; p; p=p->pDirty){
49398      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
49399    }
49400  }
49401
49402#ifdef SQLITE_CHECK_PAGES
49403  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49404  for(p=pList; p; p=p->pDirty){
49405    pager_set_pagehash(p);
49406  }
49407#endif
49408
49409  return rc;
49410}
49411
49412/*
49413** Begin a read transaction on the WAL.
49414**
49415** This routine used to be called "pagerOpenSnapshot()" because it essentially
49416** makes a snapshot of the database at the current point in time and preserves
49417** that snapshot for use by the reader in spite of concurrently changes by
49418** other writers or checkpointers.
49419*/
49420static int pagerBeginReadTransaction(Pager *pPager){
49421  int rc;                         /* Return code */
49422  int changed = 0;                /* True if cache must be reset */
49423
49424  assert( pagerUseWal(pPager) );
49425  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49426
49427  /* sqlite3WalEndReadTransaction() was not called for the previous
49428  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
49429  ** are in locking_mode=NORMAL and EndRead() was previously called,
49430  ** the duplicate call is harmless.
49431  */
49432  sqlite3WalEndReadTransaction(pPager->pWal);
49433
49434  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
49435  if( rc!=SQLITE_OK || changed ){
49436    pager_reset(pPager);
49437    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49438  }
49439
49440  return rc;
49441}
49442#endif
49443
49444/*
49445** This function is called as part of the transition from PAGER_OPEN
49446** to PAGER_READER state to determine the size of the database file
49447** in pages (assuming the page size currently stored in Pager.pageSize).
49448**
49449** If no error occurs, SQLITE_OK is returned and the size of the database
49450** in pages is stored in *pnPage. Otherwise, an error code (perhaps
49451** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
49452*/
49453static int pagerPagecount(Pager *pPager, Pgno *pnPage){
49454  Pgno nPage;                     /* Value to return via *pnPage */
49455
49456  /* Query the WAL sub-system for the database size. The WalDbsize()
49457  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
49458  ** if the database size is not available. The database size is not
49459  ** available from the WAL sub-system if the log file is empty or
49460  ** contains no valid committed transactions.
49461  */
49462  assert( pPager->eState==PAGER_OPEN );
49463  assert( pPager->eLock>=SHARED_LOCK );
49464  assert( isOpen(pPager->fd) );
49465  assert( pPager->tempFile==0 );
49466  nPage = sqlite3WalDbsize(pPager->pWal);
49467
49468  /* If the number of pages in the database is not available from the
49469  ** WAL sub-system, determine the page counte based on the size of
49470  ** the database file.  If the size of the database file is not an
49471  ** integer multiple of the page-size, round up the result.
49472  */
49473  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49474    i64 n = 0;                    /* Size of db file in bytes */
49475    int rc = sqlite3OsFileSize(pPager->fd, &n);
49476    if( rc!=SQLITE_OK ){
49477      return rc;
49478    }
49479    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49480  }
49481
49482  /* If the current number of pages in the file is greater than the
49483  ** configured maximum pager number, increase the allowed limit so
49484  ** that the file can be read.
49485  */
49486  if( nPage>pPager->mxPgno ){
49487    pPager->mxPgno = (Pgno)nPage;
49488  }
49489
49490  *pnPage = nPage;
49491  return SQLITE_OK;
49492}
49493
49494#ifndef SQLITE_OMIT_WAL
49495/*
49496** Check if the *-wal file that corresponds to the database opened by pPager
49497** exists if the database is not empy, or verify that the *-wal file does
49498** not exist (by deleting it) if the database file is empty.
49499**
49500** If the database is not empty and the *-wal file exists, open the pager
49501** in WAL mode.  If the database is empty or if no *-wal file exists and
49502** if no error occurs, make sure Pager.journalMode is not set to
49503** PAGER_JOURNALMODE_WAL.
49504**
49505** Return SQLITE_OK or an error code.
49506**
49507** The caller must hold a SHARED lock on the database file to call this
49508** function. Because an EXCLUSIVE lock on the db file is required to delete
49509** a WAL on a none-empty database, this ensures there is no race condition
49510** between the xAccess() below and an xDelete() being executed by some
49511** other connection.
49512*/
49513static int pagerOpenWalIfPresent(Pager *pPager){
49514  int rc = SQLITE_OK;
49515  assert( pPager->eState==PAGER_OPEN );
49516  assert( pPager->eLock>=SHARED_LOCK );
49517
49518  if( !pPager->tempFile ){
49519    int isWal;                    /* True if WAL file exists */
49520    Pgno nPage;                   /* Size of the database file */
49521
49522    rc = pagerPagecount(pPager, &nPage);
49523    if( rc ) return rc;
49524    if( nPage==0 ){
49525      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
49526      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
49527      isWal = 0;
49528    }else{
49529      rc = sqlite3OsAccess(
49530          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
49531      );
49532    }
49533    if( rc==SQLITE_OK ){
49534      if( isWal ){
49535        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
49536        rc = sqlite3PagerOpenWal(pPager, 0);
49537      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
49538        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
49539      }
49540    }
49541  }
49542  return rc;
49543}
49544#endif
49545
49546/*
49547** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
49548** the entire master journal file. The case pSavepoint==NULL occurs when
49549** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
49550** savepoint.
49551**
49552** When pSavepoint is not NULL (meaning a non-transaction savepoint is
49553** being rolled back), then the rollback consists of up to three stages,
49554** performed in the order specified:
49555**
49556**   * Pages are played back from the main journal starting at byte
49557**     offset PagerSavepoint.iOffset and continuing to
49558**     PagerSavepoint.iHdrOffset, or to the end of the main journal
49559**     file if PagerSavepoint.iHdrOffset is zero.
49560**
49561**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
49562**     back starting from the journal header immediately following
49563**     PagerSavepoint.iHdrOffset to the end of the main journal file.
49564**
49565**   * Pages are then played back from the sub-journal file, starting
49566**     with the PagerSavepoint.iSubRec and continuing to the end of
49567**     the journal file.
49568**
49569** Throughout the rollback process, each time a page is rolled back, the
49570** corresponding bit is set in a bitvec structure (variable pDone in the
49571** implementation below). This is used to ensure that a page is only
49572** rolled back the first time it is encountered in either journal.
49573**
49574** If pSavepoint is NULL, then pages are only played back from the main
49575** journal file. There is no need for a bitvec in this case.
49576**
49577** In either case, before playback commences the Pager.dbSize variable
49578** is reset to the value that it held at the start of the savepoint
49579** (or transaction). No page with a page-number greater than this value
49580** is played back. If one is encountered it is simply skipped.
49581*/
49582static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
49583  i64 szJ;                 /* Effective size of the main journal */
49584  i64 iHdrOff;             /* End of first segment of main-journal records */
49585  int rc = SQLITE_OK;      /* Return code */
49586  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
49587
49588  assert( pPager->eState!=PAGER_ERROR );
49589  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49590
49591  /* Allocate a bitvec to use to store the set of pages rolled back */
49592  if( pSavepoint ){
49593    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
49594    if( !pDone ){
49595      return SQLITE_NOMEM_BKPT;
49596    }
49597  }
49598
49599  /* Set the database size back to the value it was before the savepoint
49600  ** being reverted was opened.
49601  */
49602  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
49603  pPager->changeCountDone = pPager->tempFile;
49604
49605  if( !pSavepoint && pagerUseWal(pPager) ){
49606    return pagerRollbackWal(pPager);
49607  }
49608
49609  /* Use pPager->journalOff as the effective size of the main rollback
49610  ** journal.  The actual file might be larger than this in
49611  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
49612  ** past pPager->journalOff is off-limits to us.
49613  */
49614  szJ = pPager->journalOff;
49615  assert( pagerUseWal(pPager)==0 || szJ==0 );
49616
49617  /* Begin by rolling back records from the main journal starting at
49618  ** PagerSavepoint.iOffset and continuing to the next journal header.
49619  ** There might be records in the main journal that have a page number
49620  ** greater than the current database size (pPager->dbSize) but those
49621  ** will be skipped automatically.  Pages are added to pDone as they
49622  ** are played back.
49623  */
49624  if( pSavepoint && !pagerUseWal(pPager) ){
49625    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
49626    pPager->journalOff = pSavepoint->iOffset;
49627    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
49628      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49629    }
49630    assert( rc!=SQLITE_DONE );
49631  }else{
49632    pPager->journalOff = 0;
49633  }
49634
49635  /* Continue rolling back records out of the main journal starting at
49636  ** the first journal header seen and continuing until the effective end
49637  ** of the main journal file.  Continue to skip out-of-range pages and
49638  ** continue adding pages rolled back to pDone.
49639  */
49640  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
49641    u32 ii;            /* Loop counter */
49642    u32 nJRec = 0;     /* Number of Journal Records */
49643    u32 dummy;
49644    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
49645    assert( rc!=SQLITE_DONE );
49646
49647    /*
49648    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
49649    ** test is related to ticket #2565.  See the discussion in the
49650    ** pager_playback() function for additional information.
49651    */
49652    if( nJRec==0
49653     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
49654    ){
49655      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
49656    }
49657    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
49658      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49659    }
49660    assert( rc!=SQLITE_DONE );
49661  }
49662  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
49663
49664  /* Finally,  rollback pages from the sub-journal.  Page that were
49665  ** previously rolled back out of the main journal (and are hence in pDone)
49666  ** will be skipped.  Out-of-range pages are also skipped.
49667  */
49668  if( pSavepoint ){
49669    u32 ii;            /* Loop counter */
49670    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
49671
49672    if( pagerUseWal(pPager) ){
49673      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
49674    }
49675    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
49676      assert( offset==(i64)ii*(4+pPager->pageSize) );
49677      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
49678    }
49679    assert( rc!=SQLITE_DONE );
49680  }
49681
49682  sqlite3BitvecDestroy(pDone);
49683  if( rc==SQLITE_OK ){
49684    pPager->journalOff = szJ;
49685  }
49686
49687  return rc;
49688}
49689
49690/*
49691** Change the maximum number of in-memory pages that are allowed
49692** before attempting to recycle clean and unused pages.
49693*/
49694SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
49695  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
49696}
49697
49698/*
49699** Change the maximum number of in-memory pages that are allowed
49700** before attempting to spill pages to journal.
49701*/
49702SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
49703  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
49704}
49705
49706/*
49707** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
49708*/
49709static void pagerFixMaplimit(Pager *pPager){
49710#if SQLITE_MAX_MMAP_SIZE>0
49711  sqlite3_file *fd = pPager->fd;
49712  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
49713    sqlite3_int64 sz;
49714    sz = pPager->szMmap;
49715    pPager->bUseFetch = (sz>0);
49716    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
49717  }
49718#endif
49719}
49720
49721/*
49722** Change the maximum size of any memory mapping made of the database file.
49723*/
49724SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
49725  pPager->szMmap = szMmap;
49726  pagerFixMaplimit(pPager);
49727}
49728
49729/*
49730** Free as much memory as possible from the pager.
49731*/
49732SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
49733  sqlite3PcacheShrink(pPager->pPCache);
49734}
49735
49736/*
49737** Adjust settings of the pager to those specified in the pgFlags parameter.
49738**
49739** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
49740** of the database to damage due to OS crashes or power failures by
49741** changing the number of syncs()s when writing the journals.
49742** There are four levels:
49743**
49744**    OFF       sqlite3OsSync() is never called.  This is the default
49745**              for temporary and transient files.
49746**
49747**    NORMAL    The journal is synced once before writes begin on the
49748**              database.  This is normally adequate protection, but
49749**              it is theoretically possible, though very unlikely,
49750**              that an inopertune power failure could leave the journal
49751**              in a state which would cause damage to the database
49752**              when it is rolled back.
49753**
49754**    FULL      The journal is synced twice before writes begin on the
49755**              database (with some additional information - the nRec field
49756**              of the journal header - being written in between the two
49757**              syncs).  If we assume that writing a
49758**              single disk sector is atomic, then this mode provides
49759**              assurance that the journal will not be corrupted to the
49760**              point of causing damage to the database during rollback.
49761**
49762**    EXTRA     This is like FULL except that is also syncs the directory
49763**              that contains the rollback journal after the rollback
49764**              journal is unlinked.
49765**
49766** The above is for a rollback-journal mode.  For WAL mode, OFF continues
49767** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
49768** prior to the start of checkpoint and that the database file is synced
49769** at the conclusion of the checkpoint if the entire content of the WAL
49770** was written back into the database.  But no sync operations occur for
49771** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
49772** file is synced following each commit operation, in addition to the
49773** syncs associated with NORMAL.  There is no difference between FULL
49774** and EXTRA for WAL mode.
49775**
49776** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
49777** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
49778** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
49779** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
49780** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
49781** synchronous=FULL versus synchronous=NORMAL setting determines when
49782** the xSync primitive is called and is relevant to all platforms.
49783**
49784** Numeric values associated with these states are OFF==1, NORMAL=2,
49785** and FULL=3.
49786*/
49787#ifndef SQLITE_OMIT_PAGER_PRAGMAS
49788SQLITE_PRIVATE void sqlite3PagerSetFlags(
49789  Pager *pPager,        /* The pager to set safety level for */
49790  unsigned pgFlags      /* Various flags */
49791){
49792  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
49793  if( pPager->tempFile ){
49794    pPager->noSync = 1;
49795    pPager->fullSync = 0;
49796    pPager->extraSync = 0;
49797  }else{
49798    pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
49799    pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
49800    pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
49801  }
49802  if( pPager->noSync ){
49803    pPager->syncFlags = 0;
49804    pPager->ckptSyncFlags = 0;
49805  }else if( pgFlags & PAGER_FULLFSYNC ){
49806    pPager->syncFlags = SQLITE_SYNC_FULL;
49807    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49808  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
49809    pPager->syncFlags = SQLITE_SYNC_NORMAL;
49810    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49811  }else{
49812    pPager->syncFlags = SQLITE_SYNC_NORMAL;
49813    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
49814  }
49815  pPager->walSyncFlags = pPager->syncFlags;
49816  if( pPager->fullSync ){
49817    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
49818  }
49819  if( pgFlags & PAGER_CACHESPILL ){
49820    pPager->doNotSpill &= ~SPILLFLAG_OFF;
49821  }else{
49822    pPager->doNotSpill |= SPILLFLAG_OFF;
49823  }
49824}
49825#endif
49826
49827/*
49828** The following global variable is incremented whenever the library
49829** attempts to open a temporary file.  This information is used for
49830** testing and analysis only.
49831*/
49832#ifdef SQLITE_TEST
49833SQLITE_API int sqlite3_opentemp_count = 0;
49834#endif
49835
49836/*
49837** Open a temporary file.
49838**
49839** Write the file descriptor into *pFile. Return SQLITE_OK on success
49840** or some other error code if we fail. The OS will automatically
49841** delete the temporary file when it is closed.
49842**
49843** The flags passed to the VFS layer xOpen() call are those specified
49844** by parameter vfsFlags ORed with the following:
49845**
49846**     SQLITE_OPEN_READWRITE
49847**     SQLITE_OPEN_CREATE
49848**     SQLITE_OPEN_EXCLUSIVE
49849**     SQLITE_OPEN_DELETEONCLOSE
49850*/
49851static int pagerOpentemp(
49852  Pager *pPager,        /* The pager object */
49853  sqlite3_file *pFile,  /* Write the file descriptor here */
49854  int vfsFlags          /* Flags passed through to the VFS */
49855){
49856  int rc;               /* Return code */
49857
49858#ifdef SQLITE_TEST
49859  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
49860#endif
49861
49862  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
49863            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
49864  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
49865  assert( rc!=SQLITE_OK || isOpen(pFile) );
49866  return rc;
49867}
49868
49869/*
49870** Set the busy handler function.
49871**
49872** The pager invokes the busy-handler if sqlite3OsLock() returns
49873** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
49874** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
49875** lock. It does *not* invoke the busy handler when upgrading from
49876** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
49877** (which occurs during hot-journal rollback). Summary:
49878**
49879**   Transition                        | Invokes xBusyHandler
49880**   --------------------------------------------------------
49881**   NO_LOCK       -> SHARED_LOCK      | Yes
49882**   SHARED_LOCK   -> RESERVED_LOCK    | No
49883**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
49884**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
49885**
49886** If the busy-handler callback returns non-zero, the lock is
49887** retried. If it returns zero, then the SQLITE_BUSY error is
49888** returned to the caller of the pager API function.
49889*/
49890SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
49891  Pager *pPager,                       /* Pager object */
49892  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
49893  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
49894){
49895  pPager->xBusyHandler = xBusyHandler;
49896  pPager->pBusyHandlerArg = pBusyHandlerArg;
49897
49898  if( isOpen(pPager->fd) ){
49899    void **ap = (void **)&pPager->xBusyHandler;
49900    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
49901    assert( ap[1]==pBusyHandlerArg );
49902    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
49903  }
49904}
49905
49906/*
49907** Change the page size used by the Pager object. The new page size
49908** is passed in *pPageSize.
49909**
49910** If the pager is in the error state when this function is called, it
49911** is a no-op. The value returned is the error state error code (i.e.
49912** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
49913**
49914** Otherwise, if all of the following are true:
49915**
49916**   * the new page size (value of *pPageSize) is valid (a power
49917**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
49918**
49919**   * there are no outstanding page references, and
49920**
49921**   * the database is either not an in-memory database or it is
49922**     an in-memory database that currently consists of zero pages.
49923**
49924** then the pager object page size is set to *pPageSize.
49925**
49926** If the page size is changed, then this function uses sqlite3PagerMalloc()
49927** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
49928** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
49929** In all other cases, SQLITE_OK is returned.
49930**
49931** If the page size is not changed, either because one of the enumerated
49932** conditions above is not true, the pager was in error state when this
49933** function was called, or because the memory allocation attempt failed,
49934** then *pPageSize is set to the old, retained page size before returning.
49935*/
49936SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
49937  int rc = SQLITE_OK;
49938
49939  /* It is not possible to do a full assert_pager_state() here, as this
49940  ** function may be called from within PagerOpen(), before the state
49941  ** of the Pager object is internally consistent.
49942  **
49943  ** At one point this function returned an error if the pager was in
49944  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
49945  ** there is at least one outstanding page reference, this function
49946  ** is a no-op for that case anyhow.
49947  */
49948
49949  u32 pageSize = *pPageSize;
49950  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
49951  if( (pPager->memDb==0 || pPager->dbSize==0)
49952   && sqlite3PcacheRefCount(pPager->pPCache)==0
49953   && pageSize && pageSize!=(u32)pPager->pageSize
49954  ){
49955    char *pNew = NULL;             /* New temp space */
49956    i64 nByte = 0;
49957
49958    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
49959      rc = sqlite3OsFileSize(pPager->fd, &nByte);
49960    }
49961    if( rc==SQLITE_OK ){
49962      pNew = (char *)sqlite3PageMalloc(pageSize);
49963      if( !pNew ) rc = SQLITE_NOMEM_BKPT;
49964    }
49965
49966    if( rc==SQLITE_OK ){
49967      pager_reset(pPager);
49968      rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
49969    }
49970    if( rc==SQLITE_OK ){
49971      sqlite3PageFree(pPager->pTmpSpace);
49972      pPager->pTmpSpace = pNew;
49973      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
49974      pPager->pageSize = pageSize;
49975    }else{
49976      sqlite3PageFree(pNew);
49977    }
49978  }
49979
49980  *pPageSize = pPager->pageSize;
49981  if( rc==SQLITE_OK ){
49982    if( nReserve<0 ) nReserve = pPager->nReserve;
49983    assert( nReserve>=0 && nReserve<1000 );
49984    pPager->nReserve = (i16)nReserve;
49985    pagerReportSize(pPager);
49986    pagerFixMaplimit(pPager);
49987  }
49988  return rc;
49989}
49990
49991/*
49992** Return a pointer to the "temporary page" buffer held internally
49993** by the pager.  This is a buffer that is big enough to hold the
49994** entire content of a database page.  This buffer is used internally
49995** during rollback and will be overwritten whenever a rollback
49996** occurs.  But other modules are free to use it too, as long as
49997** no rollbacks are happening.
49998*/
49999SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
50000  return pPager->pTmpSpace;
50001}
50002
50003/*
50004** Attempt to set the maximum database page count if mxPage is positive.
50005** Make no changes if mxPage is zero or negative.  And never reduce the
50006** maximum page count below the current size of the database.
50007**
50008** Regardless of mxPage, return the current maximum page count.
50009*/
50010SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
50011  if( mxPage>0 ){
50012    pPager->mxPgno = mxPage;
50013  }
50014  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
50015  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
50016  return pPager->mxPgno;
50017}
50018
50019/*
50020** The following set of routines are used to disable the simulated
50021** I/O error mechanism.  These routines are used to avoid simulated
50022** errors in places where we do not care about errors.
50023**
50024** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
50025** and generate no code.
50026*/
50027#ifdef SQLITE_TEST
50028SQLITE_API extern int sqlite3_io_error_pending;
50029SQLITE_API extern int sqlite3_io_error_hit;
50030static int saved_cnt;
50031void disable_simulated_io_errors(void){
50032  saved_cnt = sqlite3_io_error_pending;
50033  sqlite3_io_error_pending = -1;
50034}
50035void enable_simulated_io_errors(void){
50036  sqlite3_io_error_pending = saved_cnt;
50037}
50038#else
50039# define disable_simulated_io_errors()
50040# define enable_simulated_io_errors()
50041#endif
50042
50043/*
50044** Read the first N bytes from the beginning of the file into memory
50045** that pDest points to.
50046**
50047** If the pager was opened on a transient file (zFilename==""), or
50048** opened on a file less than N bytes in size, the output buffer is
50049** zeroed and SQLITE_OK returned. The rationale for this is that this
50050** function is used to read database headers, and a new transient or
50051** zero sized database has a header than consists entirely of zeroes.
50052**
50053** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
50054** the error code is returned to the caller and the contents of the
50055** output buffer undefined.
50056*/
50057SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
50058  int rc = SQLITE_OK;
50059  memset(pDest, 0, N);
50060  assert( isOpen(pPager->fd) || pPager->tempFile );
50061
50062  /* This routine is only called by btree immediately after creating
50063  ** the Pager object.  There has not been an opportunity to transition
50064  ** to WAL mode yet.
50065  */
50066  assert( !pagerUseWal(pPager) );
50067
50068  if( isOpen(pPager->fd) ){
50069    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
50070    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
50071    if( rc==SQLITE_IOERR_SHORT_READ ){
50072      rc = SQLITE_OK;
50073    }
50074  }
50075  return rc;
50076}
50077
50078/*
50079** This function may only be called when a read-transaction is open on
50080** the pager. It returns the total number of pages in the database.
50081**
50082** However, if the file is between 1 and <page-size> bytes in size, then
50083** this is considered a 1 page file.
50084*/
50085SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
50086  assert( pPager->eState>=PAGER_READER );
50087  assert( pPager->eState!=PAGER_WRITER_FINISHED );
50088  *pnPage = (int)pPager->dbSize;
50089}
50090
50091
50092/*
50093** Try to obtain a lock of type locktype on the database file. If
50094** a similar or greater lock is already held, this function is a no-op
50095** (returning SQLITE_OK immediately).
50096**
50097** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
50098** the busy callback if the lock is currently not available. Repeat
50099** until the busy callback returns false or until the attempt to
50100** obtain the lock succeeds.
50101**
50102** Return SQLITE_OK on success and an error code if we cannot obtain
50103** the lock. If the lock is obtained successfully, set the Pager.state
50104** variable to locktype before returning.
50105*/
50106static int pager_wait_on_lock(Pager *pPager, int locktype){
50107  int rc;                              /* Return code */
50108
50109  /* Check that this is either a no-op (because the requested lock is
50110  ** already held), or one of the transitions that the busy-handler
50111  ** may be invoked during, according to the comment above
50112  ** sqlite3PagerSetBusyhandler().
50113  */
50114  assert( (pPager->eLock>=locktype)
50115       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
50116       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
50117  );
50118
50119  do {
50120    rc = pagerLockDb(pPager, locktype);
50121  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
50122  return rc;
50123}
50124
50125/*
50126** Function assertTruncateConstraint(pPager) checks that one of the
50127** following is true for all dirty pages currently in the page-cache:
50128**
50129**   a) The page number is less than or equal to the size of the
50130**      current database image, in pages, OR
50131**
50132**   b) if the page content were written at this time, it would not
50133**      be necessary to write the current content out to the sub-journal
50134**      (as determined by function subjRequiresPage()).
50135**
50136** If the condition asserted by this function were not true, and the
50137** dirty page were to be discarded from the cache via the pagerStress()
50138** routine, pagerStress() would not write the current page content to
50139** the database file. If a savepoint transaction were rolled back after
50140** this happened, the correct behavior would be to restore the current
50141** content of the page. However, since this content is not present in either
50142** the database file or the portion of the rollback journal and
50143** sub-journal rolled back the content could not be restored and the
50144** database image would become corrupt. It is therefore fortunate that
50145** this circumstance cannot arise.
50146*/
50147#if defined(SQLITE_DEBUG)
50148static void assertTruncateConstraintCb(PgHdr *pPg){
50149  assert( pPg->flags&PGHDR_DIRTY );
50150  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
50151}
50152static void assertTruncateConstraint(Pager *pPager){
50153  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
50154}
50155#else
50156# define assertTruncateConstraint(pPager)
50157#endif
50158
50159/*
50160** Truncate the in-memory database file image to nPage pages. This
50161** function does not actually modify the database file on disk. It
50162** just sets the internal state of the pager object so that the
50163** truncation will be done when the current transaction is committed.
50164**
50165** This function is only called right before committing a transaction.
50166** Once this function has been called, the transaction must either be
50167** rolled back or committed. It is not safe to call this function and
50168** then continue writing to the database.
50169*/
50170SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
50171  assert( pPager->dbSize>=nPage );
50172  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
50173  pPager->dbSize = nPage;
50174
50175  /* At one point the code here called assertTruncateConstraint() to
50176  ** ensure that all pages being truncated away by this operation are,
50177  ** if one or more savepoints are open, present in the savepoint
50178  ** journal so that they can be restored if the savepoint is rolled
50179  ** back. This is no longer necessary as this function is now only
50180  ** called right before committing a transaction. So although the
50181  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
50182  ** they cannot be rolled back. So the assertTruncateConstraint() call
50183  ** is no longer correct. */
50184}
50185
50186
50187/*
50188** This function is called before attempting a hot-journal rollback. It
50189** syncs the journal file to disk, then sets pPager->journalHdr to the
50190** size of the journal file so that the pager_playback() routine knows
50191** that the entire journal file has been synced.
50192**
50193** Syncing a hot-journal to disk before attempting to roll it back ensures
50194** that if a power-failure occurs during the rollback, the process that
50195** attempts rollback following system recovery sees the same journal
50196** content as this process.
50197**
50198** If everything goes as planned, SQLITE_OK is returned. Otherwise,
50199** an SQLite error code.
50200*/
50201static int pagerSyncHotJournal(Pager *pPager){
50202  int rc = SQLITE_OK;
50203  if( !pPager->noSync ){
50204    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
50205  }
50206  if( rc==SQLITE_OK ){
50207    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
50208  }
50209  return rc;
50210}
50211
50212/*
50213** Obtain a reference to a memory mapped page object for page number pgno.
50214** The new object will use the pointer pData, obtained from xFetch().
50215** If successful, set *ppPage to point to the new page reference
50216** and return SQLITE_OK. Otherwise, return an SQLite error code and set
50217** *ppPage to zero.
50218**
50219** Page references obtained by calling this function should be released
50220** by calling pagerReleaseMapPage().
50221*/
50222static int pagerAcquireMapPage(
50223  Pager *pPager,                  /* Pager object */
50224  Pgno pgno,                      /* Page number */
50225  void *pData,                    /* xFetch()'d data for this page */
50226  PgHdr **ppPage                  /* OUT: Acquired page object */
50227){
50228  PgHdr *p;                       /* Memory mapped page to return */
50229
50230  if( pPager->pMmapFreelist ){
50231    *ppPage = p = pPager->pMmapFreelist;
50232    pPager->pMmapFreelist = p->pDirty;
50233    p->pDirty = 0;
50234    memset(p->pExtra, 0, pPager->nExtra);
50235  }else{
50236    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
50237    if( p==0 ){
50238      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
50239      return SQLITE_NOMEM_BKPT;
50240    }
50241    p->pExtra = (void *)&p[1];
50242    p->flags = PGHDR_MMAP;
50243    p->nRef = 1;
50244    p->pPager = pPager;
50245  }
50246
50247  assert( p->pExtra==(void *)&p[1] );
50248  assert( p->pPage==0 );
50249  assert( p->flags==PGHDR_MMAP );
50250  assert( p->pPager==pPager );
50251  assert( p->nRef==1 );
50252
50253  p->pgno = pgno;
50254  p->pData = pData;
50255  pPager->nMmapOut++;
50256
50257  return SQLITE_OK;
50258}
50259
50260/*
50261** Release a reference to page pPg. pPg must have been returned by an
50262** earlier call to pagerAcquireMapPage().
50263*/
50264static void pagerReleaseMapPage(PgHdr *pPg){
50265  Pager *pPager = pPg->pPager;
50266  pPager->nMmapOut--;
50267  pPg->pDirty = pPager->pMmapFreelist;
50268  pPager->pMmapFreelist = pPg;
50269
50270  assert( pPager->fd->pMethods->iVersion>=3 );
50271  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
50272}
50273
50274/*
50275** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
50276*/
50277static void pagerFreeMapHdrs(Pager *pPager){
50278  PgHdr *p;
50279  PgHdr *pNext;
50280  for(p=pPager->pMmapFreelist; p; p=pNext){
50281    pNext = p->pDirty;
50282    sqlite3_free(p);
50283  }
50284}
50285
50286
50287/*
50288** Shutdown the page cache.  Free all memory and close all files.
50289**
50290** If a transaction was in progress when this routine is called, that
50291** transaction is rolled back.  All outstanding pages are invalidated
50292** and their memory is freed.  Any attempt to use a page associated
50293** with this page cache after this function returns will likely
50294** result in a coredump.
50295**
50296** This function always succeeds. If a transaction is active an attempt
50297** is made to roll it back. If an error occurs during the rollback
50298** a hot journal may be left in the filesystem but no error is returned
50299** to the caller.
50300*/
50301SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
50302  u8 *pTmp = (u8 *)pPager->pTmpSpace;
50303
50304  assert( assert_pager_state(pPager) );
50305  disable_simulated_io_errors();
50306  sqlite3BeginBenignMalloc();
50307  pagerFreeMapHdrs(pPager);
50308  /* pPager->errCode = 0; */
50309  pPager->exclusiveMode = 0;
50310#ifndef SQLITE_OMIT_WAL
50311  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
50312  pPager->pWal = 0;
50313#endif
50314  pager_reset(pPager);
50315  if( MEMDB ){
50316    pager_unlock(pPager);
50317  }else{
50318    /* If it is open, sync the journal file before calling UnlockAndRollback.
50319    ** If this is not done, then an unsynced portion of the open journal
50320    ** file may be played back into the database. If a power failure occurs
50321    ** while this is happening, the database could become corrupt.
50322    **
50323    ** If an error occurs while trying to sync the journal, shift the pager
50324    ** into the ERROR state. This causes UnlockAndRollback to unlock the
50325    ** database and close the journal file without attempting to roll it
50326    ** back or finalize it. The next database user will have to do hot-journal
50327    ** rollback before accessing the database file.
50328    */
50329    if( isOpen(pPager->jfd) ){
50330      pager_error(pPager, pagerSyncHotJournal(pPager));
50331    }
50332    pagerUnlockAndRollback(pPager);
50333  }
50334  sqlite3EndBenignMalloc();
50335  enable_simulated_io_errors();
50336  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
50337  IOTRACE(("CLOSE %p\n", pPager))
50338  sqlite3OsClose(pPager->jfd);
50339  sqlite3OsClose(pPager->fd);
50340  sqlite3PageFree(pTmp);
50341  sqlite3PcacheClose(pPager->pPCache);
50342
50343#ifdef SQLITE_HAS_CODEC
50344  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
50345#endif
50346
50347  assert( !pPager->aSavepoint && !pPager->pInJournal );
50348  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
50349
50350  sqlite3_free(pPager);
50351  return SQLITE_OK;
50352}
50353
50354#if !defined(NDEBUG) || defined(SQLITE_TEST)
50355/*
50356** Return the page number for page pPg.
50357*/
50358SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
50359  return pPg->pgno;
50360}
50361#endif
50362
50363/*
50364** Increment the reference count for page pPg.
50365*/
50366SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
50367  sqlite3PcacheRef(pPg);
50368}
50369
50370/*
50371** Sync the journal. In other words, make sure all the pages that have
50372** been written to the journal have actually reached the surface of the
50373** disk and can be restored in the event of a hot-journal rollback.
50374**
50375** If the Pager.noSync flag is set, then this function is a no-op.
50376** Otherwise, the actions required depend on the journal-mode and the
50377** device characteristics of the file-system, as follows:
50378**
50379**   * If the journal file is an in-memory journal file, no action need
50380**     be taken.
50381**
50382**   * Otherwise, if the device does not support the SAFE_APPEND property,
50383**     then the nRec field of the most recently written journal header
50384**     is updated to contain the number of journal records that have
50385**     been written following it. If the pager is operating in full-sync
50386**     mode, then the journal file is synced before this field is updated.
50387**
50388**   * If the device does not support the SEQUENTIAL property, then
50389**     journal file is synced.
50390**
50391** Or, in pseudo-code:
50392**
50393**   if( NOT <in-memory journal> ){
50394**     if( NOT SAFE_APPEND ){
50395**       if( <full-sync mode> ) xSync(<journal file>);
50396**       <update nRec field>
50397**     }
50398**     if( NOT SEQUENTIAL ) xSync(<journal file>);
50399**   }
50400**
50401** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
50402** page currently held in memory before returning SQLITE_OK. If an IO
50403** error is encountered, then the IO error code is returned to the caller.
50404*/
50405static int syncJournal(Pager *pPager, int newHdr){
50406  int rc;                         /* Return code */
50407
50408  assert( pPager->eState==PAGER_WRITER_CACHEMOD
50409       || pPager->eState==PAGER_WRITER_DBMOD
50410  );
50411  assert( assert_pager_state(pPager) );
50412  assert( !pagerUseWal(pPager) );
50413
50414  rc = sqlite3PagerExclusiveLock(pPager);
50415  if( rc!=SQLITE_OK ) return rc;
50416
50417  if( !pPager->noSync ){
50418    assert( !pPager->tempFile );
50419    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
50420      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50421      assert( isOpen(pPager->jfd) );
50422
50423      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50424        /* This block deals with an obscure problem. If the last connection
50425        ** that wrote to this database was operating in persistent-journal
50426        ** mode, then the journal file may at this point actually be larger
50427        ** than Pager.journalOff bytes. If the next thing in the journal
50428        ** file happens to be a journal-header (written as part of the
50429        ** previous connection's transaction), and a crash or power-failure
50430        ** occurs after nRec is updated but before this connection writes
50431        ** anything else to the journal file (or commits/rolls back its
50432        ** transaction), then SQLite may become confused when doing the
50433        ** hot-journal rollback following recovery. It may roll back all
50434        ** of this connections data, then proceed to rolling back the old,
50435        ** out-of-date data that follows it. Database corruption.
50436        **
50437        ** To work around this, if the journal file does appear to contain
50438        ** a valid header following Pager.journalOff, then write a 0x00
50439        ** byte to the start of it to prevent it from being recognized.
50440        **
50441        ** Variable iNextHdrOffset is set to the offset at which this
50442        ** problematic header will occur, if it exists. aMagic is used
50443        ** as a temporary buffer to inspect the first couple of bytes of
50444        ** the potential journal header.
50445        */
50446        i64 iNextHdrOffset;
50447        u8 aMagic[8];
50448        u8 zHeader[sizeof(aJournalMagic)+4];
50449
50450        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
50451        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
50452
50453        iNextHdrOffset = journalHdrOffset(pPager);
50454        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
50455        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
50456          static const u8 zerobyte = 0;
50457          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
50458        }
50459        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
50460          return rc;
50461        }
50462
50463        /* Write the nRec value into the journal file header. If in
50464        ** full-synchronous mode, sync the journal first. This ensures that
50465        ** all data has really hit the disk before nRec is updated to mark
50466        ** it as a candidate for rollback.
50467        **
50468        ** This is not required if the persistent media supports the
50469        ** SAFE_APPEND property. Because in this case it is not possible
50470        ** for garbage data to be appended to the file, the nRec field
50471        ** is populated with 0xFFFFFFFF when the journal header is written
50472        ** and never needs to be updated.
50473        */
50474        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50475          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50476          IOTRACE(("JSYNC %p\n", pPager))
50477          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
50478          if( rc!=SQLITE_OK ) return rc;
50479        }
50480        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
50481        rc = sqlite3OsWrite(
50482            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
50483        );
50484        if( rc!=SQLITE_OK ) return rc;
50485      }
50486      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50487        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50488        IOTRACE(("JSYNC %p\n", pPager))
50489        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
50490          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
50491        );
50492        if( rc!=SQLITE_OK ) return rc;
50493      }
50494
50495      pPager->journalHdr = pPager->journalOff;
50496      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50497        pPager->nRec = 0;
50498        rc = writeJournalHdr(pPager);
50499        if( rc!=SQLITE_OK ) return rc;
50500      }
50501    }else{
50502      pPager->journalHdr = pPager->journalOff;
50503    }
50504  }
50505
50506  /* Unless the pager is in noSync mode, the journal file was just
50507  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
50508  ** all pages.
50509  */
50510  sqlite3PcacheClearSyncFlags(pPager->pPCache);
50511  pPager->eState = PAGER_WRITER_DBMOD;
50512  assert( assert_pager_state(pPager) );
50513  return SQLITE_OK;
50514}
50515
50516/*
50517** The argument is the first in a linked list of dirty pages connected
50518** by the PgHdr.pDirty pointer. This function writes each one of the
50519** in-memory pages in the list to the database file. The argument may
50520** be NULL, representing an empty list. In this case this function is
50521** a no-op.
50522**
50523** The pager must hold at least a RESERVED lock when this function
50524** is called. Before writing anything to the database file, this lock
50525** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
50526** SQLITE_BUSY is returned and no data is written to the database file.
50527**
50528** If the pager is a temp-file pager and the actual file-system file
50529** is not yet open, it is created and opened before any data is
50530** written out.
50531**
50532** Once the lock has been upgraded and, if necessary, the file opened,
50533** the pages are written out to the database file in list order. Writing
50534** a page is skipped if it meets either of the following criteria:
50535**
50536**   * The page number is greater than Pager.dbSize, or
50537**   * The PGHDR_DONT_WRITE flag is set on the page.
50538**
50539** If writing out a page causes the database file to grow, Pager.dbFileSize
50540** is updated accordingly. If page 1 is written out, then the value cached
50541** in Pager.dbFileVers[] is updated to match the new value stored in
50542** the database file.
50543**
50544** If everything is successful, SQLITE_OK is returned. If an IO error
50545** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
50546** be obtained, SQLITE_BUSY is returned.
50547*/
50548static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50549  int rc = SQLITE_OK;                  /* Return code */
50550
50551  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50552  assert( !pagerUseWal(pPager) );
50553  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50554  assert( pPager->eLock==EXCLUSIVE_LOCK );
50555  assert( isOpen(pPager->fd) || pList->pDirty==0 );
50556
50557  /* If the file is a temp-file has not yet been opened, open it now. It
50558  ** is not possible for rc to be other than SQLITE_OK if this branch
50559  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50560  */
50561  if( !isOpen(pPager->fd) ){
50562    assert( pPager->tempFile && rc==SQLITE_OK );
50563    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
50564  }
50565
50566  /* Before the first write, give the VFS a hint of what the final
50567  ** file size will be.
50568  */
50569  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
50570  if( rc==SQLITE_OK
50571   && pPager->dbHintSize<pPager->dbSize
50572   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
50573  ){
50574    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
50575    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
50576    pPager->dbHintSize = pPager->dbSize;
50577  }
50578
50579  while( rc==SQLITE_OK && pList ){
50580    Pgno pgno = pList->pgno;
50581
50582    /* If there are dirty pages in the page cache with page numbers greater
50583    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
50584    ** make the file smaller (presumably by auto-vacuum code). Do not write
50585    ** any such pages to the file.
50586    **
50587    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
50588    ** set (set by sqlite3PagerDontWrite()).
50589    */
50590    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
50591      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
50592      char *pData;                                   /* Data to write */
50593
50594      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
50595      if( pList->pgno==1 ) pager_write_changecounter(pList);
50596
50597      /* Encode the database */
50598      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
50599
50600      /* Write out the page data. */
50601      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
50602
50603      /* If page 1 was just written, update Pager.dbFileVers to match
50604      ** the value now stored in the database file. If writing this
50605      ** page caused the database file to grow, update dbFileSize.
50606      */
50607      if( pgno==1 ){
50608        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
50609      }
50610      if( pgno>pPager->dbFileSize ){
50611        pPager->dbFileSize = pgno;
50612      }
50613      pPager->aStat[PAGER_STAT_WRITE]++;
50614
50615      /* Update any backup objects copying the contents of this pager. */
50616      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
50617
50618      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
50619                   PAGERID(pPager), pgno, pager_pagehash(pList)));
50620      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
50621      PAGER_INCR(sqlite3_pager_writedb_count);
50622    }else{
50623      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
50624    }
50625    pager_set_pagehash(pList);
50626    pList = pList->pDirty;
50627  }
50628
50629  return rc;
50630}
50631
50632/*
50633** Ensure that the sub-journal file is open. If it is already open, this
50634** function is a no-op.
50635**
50636** SQLITE_OK is returned if everything goes according to plan. An
50637** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
50638** fails.
50639*/
50640static int openSubJournal(Pager *pPager){
50641  int rc = SQLITE_OK;
50642  if( !isOpen(pPager->sjfd) ){
50643    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
50644      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
50645      | SQLITE_OPEN_DELETEONCLOSE;
50646    int nStmtSpill = sqlite3Config.nStmtSpill;
50647    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
50648      nStmtSpill = -1;
50649    }
50650    rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
50651  }
50652  return rc;
50653}
50654
50655/*
50656** Append a record of the current state of page pPg to the sub-journal.
50657**
50658** If successful, set the bit corresponding to pPg->pgno in the bitvecs
50659** for all open savepoints before returning.
50660**
50661** This function returns SQLITE_OK if everything is successful, an IO
50662** error code if the attempt to write to the sub-journal fails, or
50663** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
50664** bitvec.
50665*/
50666static int subjournalPage(PgHdr *pPg){
50667  int rc = SQLITE_OK;
50668  Pager *pPager = pPg->pPager;
50669  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
50670
50671    /* Open the sub-journal, if it has not already been opened */
50672    assert( pPager->useJournal );
50673    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
50674    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
50675    assert( pagerUseWal(pPager)
50676         || pageInJournal(pPager, pPg)
50677         || pPg->pgno>pPager->dbOrigSize
50678    );
50679    rc = openSubJournal(pPager);
50680
50681    /* If the sub-journal was opened successfully (or was already open),
50682    ** write the journal record into the file.  */
50683    if( rc==SQLITE_OK ){
50684      void *pData = pPg->pData;
50685      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
50686      char *pData2;
50687
50688      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
50689      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
50690      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
50691      if( rc==SQLITE_OK ){
50692        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
50693      }
50694    }
50695  }
50696  if( rc==SQLITE_OK ){
50697    pPager->nSubRec++;
50698    assert( pPager->nSavepoint>0 );
50699    rc = addToSavepointBitvecs(pPager, pPg->pgno);
50700  }
50701  return rc;
50702}
50703static int subjournalPageIfRequired(PgHdr *pPg){
50704  if( subjRequiresPage(pPg) ){
50705    return subjournalPage(pPg);
50706  }else{
50707    return SQLITE_OK;
50708  }
50709}
50710
50711/*
50712** This function is called by the pcache layer when it has reached some
50713** soft memory limit. The first argument is a pointer to a Pager object
50714** (cast as a void*). The pager is always 'purgeable' (not an in-memory
50715** database). The second argument is a reference to a page that is
50716** currently dirty but has no outstanding references. The page
50717** is always associated with the Pager object passed as the first
50718** argument.
50719**
50720** The job of this function is to make pPg clean by writing its contents
50721** out to the database file, if possible. This may involve syncing the
50722** journal file.
50723**
50724** If successful, sqlite3PcacheMakeClean() is called on the page and
50725** SQLITE_OK returned. If an IO error occurs while trying to make the
50726** page clean, the IO error code is returned. If the page cannot be
50727** made clean for some other reason, but no error occurs, then SQLITE_OK
50728** is returned by sqlite3PcacheMakeClean() is not called.
50729*/
50730static int pagerStress(void *p, PgHdr *pPg){
50731  Pager *pPager = (Pager *)p;
50732  int rc = SQLITE_OK;
50733
50734  assert( pPg->pPager==pPager );
50735  assert( pPg->flags&PGHDR_DIRTY );
50736
50737  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
50738  ** journal (and adding a new header) is not allowed.  This occurs
50739  ** during calls to sqlite3PagerWrite() while trying to journal multiple
50740  ** pages belonging to the same sector.
50741  **
50742  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
50743  ** regardless of whether or not a sync is required.  This is set during
50744  ** a rollback or by user request, respectively.
50745  **
50746  ** Spilling is also prohibited when in an error state since that could
50747  ** lead to database corruption.   In the current implementation it
50748  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
50749  ** while in the error state, hence it is impossible for this routine to
50750  ** be called in the error state.  Nevertheless, we include a NEVER()
50751  ** test for the error state as a safeguard against future changes.
50752  */
50753  if( NEVER(pPager->errCode) ) return SQLITE_OK;
50754  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
50755  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
50756  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
50757  if( pPager->doNotSpill
50758   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
50759      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
50760  ){
50761    return SQLITE_OK;
50762  }
50763
50764  pPg->pDirty = 0;
50765  if( pagerUseWal(pPager) ){
50766    /* Write a single frame for this page to the log. */
50767    rc = subjournalPageIfRequired(pPg);
50768    if( rc==SQLITE_OK ){
50769      rc = pagerWalFrames(pPager, pPg, 0, 0);
50770    }
50771  }else{
50772
50773    /* Sync the journal file if required. */
50774    if( pPg->flags&PGHDR_NEED_SYNC
50775     || pPager->eState==PAGER_WRITER_CACHEMOD
50776    ){
50777      rc = syncJournal(pPager, 1);
50778    }
50779
50780    /* Write the contents of the page out to the database file. */
50781    if( rc==SQLITE_OK ){
50782      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
50783      rc = pager_write_pagelist(pPager, pPg);
50784    }
50785  }
50786
50787  /* Mark the page as clean. */
50788  if( rc==SQLITE_OK ){
50789    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
50790    sqlite3PcacheMakeClean(pPg);
50791  }
50792
50793  return pager_error(pPager, rc);
50794}
50795
50796/*
50797** Flush all unreferenced dirty pages to disk.
50798*/
50799SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
50800  int rc = pPager->errCode;
50801  if( !MEMDB ){
50802    PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50803    assert( assert_pager_state(pPager) );
50804    while( rc==SQLITE_OK && pList ){
50805      PgHdr *pNext = pList->pDirty;
50806      if( pList->nRef==0 ){
50807        rc = pagerStress((void*)pPager, pList);
50808      }
50809      pList = pNext;
50810    }
50811  }
50812
50813  return rc;
50814}
50815
50816/*
50817** Allocate and initialize a new Pager object and put a pointer to it
50818** in *ppPager. The pager should eventually be freed by passing it
50819** to sqlite3PagerClose().
50820**
50821** The zFilename argument is the path to the database file to open.
50822** If zFilename is NULL then a randomly-named temporary file is created
50823** and used as the file to be cached. Temporary files are be deleted
50824** automatically when they are closed. If zFilename is ":memory:" then
50825** all information is held in cache. It is never written to disk.
50826** This can be used to implement an in-memory database.
50827**
50828** The nExtra parameter specifies the number of bytes of space allocated
50829** along with each page reference. This space is available to the user
50830** via the sqlite3PagerGetExtra() API.
50831**
50832** The flags argument is used to specify properties that affect the
50833** operation of the pager. It should be passed some bitwise combination
50834** of the PAGER_* flags.
50835**
50836** The vfsFlags parameter is a bitmask to pass to the flags parameter
50837** of the xOpen() method of the supplied VFS when opening files.
50838**
50839** If the pager object is allocated and the specified file opened
50840** successfully, SQLITE_OK is returned and *ppPager set to point to
50841** the new pager object. If an error occurs, *ppPager is set to NULL
50842** and error code returned. This function may return SQLITE_NOMEM
50843** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
50844** various SQLITE_IO_XXX errors.
50845*/
50846SQLITE_PRIVATE int sqlite3PagerOpen(
50847  sqlite3_vfs *pVfs,       /* The virtual file system to use */
50848  Pager **ppPager,         /* OUT: Return the Pager structure here */
50849  const char *zFilename,   /* Name of the database file to open */
50850  int nExtra,              /* Extra bytes append to each in-memory page */
50851  int flags,               /* flags controlling this file */
50852  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
50853  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
50854){
50855  u8 *pPtr;
50856  Pager *pPager = 0;       /* Pager object to allocate and return */
50857  int rc = SQLITE_OK;      /* Return code */
50858  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
50859  int memDb = 0;           /* True if this is an in-memory file */
50860  int readOnly = 0;        /* True if this is a read-only file */
50861  int journalFileSize;     /* Bytes to allocate for each journal fd */
50862  char *zPathname = 0;     /* Full path to database file */
50863  int nPathname = 0;       /* Number of bytes in zPathname */
50864  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
50865  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
50866  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
50867  const char *zUri = 0;    /* URI args to copy */
50868  int nUri = 0;            /* Number of bytes of URI args at *zUri */
50869
50870  /* Figure out how much space is required for each journal file-handle
50871  ** (there are two of them, the main journal and the sub-journal).  */
50872  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
50873
50874  /* Set the output variable to NULL in case an error occurs. */
50875  *ppPager = 0;
50876
50877#ifndef SQLITE_OMIT_MEMORYDB
50878  if( flags & PAGER_MEMORY ){
50879    memDb = 1;
50880    if( zFilename && zFilename[0] ){
50881      zPathname = sqlite3DbStrDup(0, zFilename);
50882      if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
50883      nPathname = sqlite3Strlen30(zPathname);
50884      zFilename = 0;
50885    }
50886  }
50887#endif
50888
50889  /* Compute and store the full pathname in an allocated buffer pointed
50890  ** to by zPathname, length nPathname. Or, if this is a temporary file,
50891  ** leave both nPathname and zPathname set to 0.
50892  */
50893  if( zFilename && zFilename[0] ){
50894    const char *z;
50895    nPathname = pVfs->mxPathname+1;
50896    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
50897    if( zPathname==0 ){
50898      return SQLITE_NOMEM_BKPT;
50899    }
50900    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
50901    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
50902    nPathname = sqlite3Strlen30(zPathname);
50903    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
50904    while( *z ){
50905      z += sqlite3Strlen30(z)+1;
50906      z += sqlite3Strlen30(z)+1;
50907    }
50908    nUri = (int)(&z[1] - zUri);
50909    assert( nUri>=0 );
50910    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
50911      /* This branch is taken when the journal path required by
50912      ** the database being opened will be more than pVfs->mxPathname
50913      ** bytes in length. This means the database cannot be opened,
50914      ** as it will not be possible to open the journal file or even
50915      ** check for a hot-journal before reading.
50916      */
50917      rc = SQLITE_CANTOPEN_BKPT;
50918    }
50919    if( rc!=SQLITE_OK ){
50920      sqlite3DbFree(0, zPathname);
50921      return rc;
50922    }
50923  }
50924
50925  /* Allocate memory for the Pager structure, PCache object, the
50926  ** three file descriptors, the database file name and the journal
50927  ** file name. The layout in memory is as follows:
50928  **
50929  **     Pager object                    (sizeof(Pager) bytes)
50930  **     PCache object                   (sqlite3PcacheSize() bytes)
50931  **     Database file handle            (pVfs->szOsFile bytes)
50932  **     Sub-journal file handle         (journalFileSize bytes)
50933  **     Main journal file handle        (journalFileSize bytes)
50934  **     Database file name              (nPathname+1 bytes)
50935  **     Journal file name               (nPathname+8+1 bytes)
50936  */
50937  pPtr = (u8 *)sqlite3MallocZero(
50938    ROUND8(sizeof(*pPager)) +      /* Pager structure */
50939    ROUND8(pcacheSize) +           /* PCache object */
50940    ROUND8(pVfs->szOsFile) +       /* The main db file */
50941    journalFileSize * 2 +          /* The two journal files */
50942    nPathname + 1 + nUri +         /* zFilename */
50943    nPathname + 8 + 2              /* zJournal */
50944#ifndef SQLITE_OMIT_WAL
50945    + nPathname + 4 + 2            /* zWal */
50946#endif
50947  );
50948  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
50949  if( !pPtr ){
50950    sqlite3DbFree(0, zPathname);
50951    return SQLITE_NOMEM_BKPT;
50952  }
50953  pPager =              (Pager*)(pPtr);
50954  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
50955  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
50956  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
50957  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
50958  pPager->zFilename =    (char*)(pPtr += journalFileSize);
50959  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
50960
50961  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
50962  if( zPathname ){
50963    assert( nPathname>0 );
50964    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
50965    memcpy(pPager->zFilename, zPathname, nPathname);
50966    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
50967    memcpy(pPager->zJournal, zPathname, nPathname);
50968    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
50969    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
50970#ifndef SQLITE_OMIT_WAL
50971    pPager->zWal = &pPager->zJournal[nPathname+8+1];
50972    memcpy(pPager->zWal, zPathname, nPathname);
50973    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
50974    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
50975#endif
50976    sqlite3DbFree(0, zPathname);
50977  }
50978  pPager->pVfs = pVfs;
50979  pPager->vfsFlags = vfsFlags;
50980
50981  /* Open the pager file.
50982  */
50983  if( zFilename && zFilename[0] ){
50984    int fout = 0;                    /* VFS flags returned by xOpen() */
50985    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
50986    assert( !memDb );
50987    readOnly = (fout&SQLITE_OPEN_READONLY);
50988
50989    /* If the file was successfully opened for read/write access,
50990    ** choose a default page size in case we have to create the
50991    ** database file. The default page size is the maximum of:
50992    **
50993    **    + SQLITE_DEFAULT_PAGE_SIZE,
50994    **    + The value returned by sqlite3OsSectorSize()
50995    **    + The largest page size that can be written atomically.
50996    */
50997    if( rc==SQLITE_OK ){
50998      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50999      if( !readOnly ){
51000        setSectorSize(pPager);
51001        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
51002        if( szPageDflt<pPager->sectorSize ){
51003          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
51004            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
51005          }else{
51006            szPageDflt = (u32)pPager->sectorSize;
51007          }
51008        }
51009#ifdef SQLITE_ENABLE_ATOMIC_WRITE
51010        {
51011          int ii;
51012          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
51013          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
51014          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
51015          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
51016            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
51017              szPageDflt = ii;
51018            }
51019          }
51020        }
51021#endif
51022      }
51023      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
51024      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
51025       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
51026          vfsFlags |= SQLITE_OPEN_READONLY;
51027          goto act_like_temp_file;
51028      }
51029    }
51030  }else{
51031    /* If a temporary file is requested, it is not opened immediately.
51032    ** In this case we accept the default page size and delay actually
51033    ** opening the file until the first call to OsWrite().
51034    **
51035    ** This branch is also run for an in-memory database. An in-memory
51036    ** database is the same as a temp-file that is never written out to
51037    ** disk and uses an in-memory rollback journal.
51038    **
51039    ** This branch also runs for files marked as immutable.
51040    */
51041act_like_temp_file:
51042    tempFile = 1;
51043    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
51044    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
51045    pPager->noLock = 1;                /* Do no locking */
51046    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
51047  }
51048
51049  /* The following call to PagerSetPagesize() serves to set the value of
51050  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
51051  */
51052  if( rc==SQLITE_OK ){
51053    assert( pPager->memDb==0 );
51054    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
51055    testcase( rc!=SQLITE_OK );
51056  }
51057
51058  /* Initialize the PCache object. */
51059  if( rc==SQLITE_OK ){
51060    assert( nExtra<1000 );
51061    nExtra = ROUND8(nExtra);
51062    rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
51063                       !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
51064  }
51065
51066  /* If an error occurred above, free the  Pager structure and close the file.
51067  */
51068  if( rc!=SQLITE_OK ){
51069    sqlite3OsClose(pPager->fd);
51070    sqlite3PageFree(pPager->pTmpSpace);
51071    sqlite3_free(pPager);
51072    return rc;
51073  }
51074
51075  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
51076  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
51077
51078  pPager->useJournal = (u8)useJournal;
51079  /* pPager->stmtOpen = 0; */
51080  /* pPager->stmtInUse = 0; */
51081  /* pPager->nRef = 0; */
51082  /* pPager->stmtSize = 0; */
51083  /* pPager->stmtJSize = 0; */
51084  /* pPager->nPage = 0; */
51085  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
51086  /* pPager->state = PAGER_UNLOCK; */
51087  /* pPager->errMask = 0; */
51088  pPager->tempFile = (u8)tempFile;
51089  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
51090          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
51091  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
51092  pPager->exclusiveMode = (u8)tempFile;
51093  pPager->changeCountDone = pPager->tempFile;
51094  pPager->memDb = (u8)memDb;
51095  pPager->readOnly = (u8)readOnly;
51096  assert( useJournal || pPager->tempFile );
51097  pPager->noSync = pPager->tempFile;
51098  if( pPager->noSync ){
51099    assert( pPager->fullSync==0 );
51100    assert( pPager->extraSync==0 );
51101    assert( pPager->syncFlags==0 );
51102    assert( pPager->walSyncFlags==0 );
51103    assert( pPager->ckptSyncFlags==0 );
51104  }else{
51105    pPager->fullSync = 1;
51106    pPager->extraSync = 0;
51107    pPager->syncFlags = SQLITE_SYNC_NORMAL;
51108    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
51109    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
51110  }
51111  /* pPager->pFirst = 0; */
51112  /* pPager->pFirstSynced = 0; */
51113  /* pPager->pLast = 0; */
51114  pPager->nExtra = (u16)nExtra;
51115  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
51116  assert( isOpen(pPager->fd) || tempFile );
51117  setSectorSize(pPager);
51118  if( !useJournal ){
51119    pPager->journalMode = PAGER_JOURNALMODE_OFF;
51120  }else if( memDb ){
51121    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
51122  }
51123  /* pPager->xBusyHandler = 0; */
51124  /* pPager->pBusyHandlerArg = 0; */
51125  pPager->xReiniter = xReinit;
51126  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
51127  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
51128
51129  *ppPager = pPager;
51130  return SQLITE_OK;
51131}
51132
51133
51134/* Verify that the database file has not be deleted or renamed out from
51135** under the pager.  Return SQLITE_OK if the database is still were it ought
51136** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
51137** code from sqlite3OsAccess()) if the database has gone missing.
51138*/
51139static int databaseIsUnmoved(Pager *pPager){
51140  int bHasMoved = 0;
51141  int rc;
51142
51143  if( pPager->tempFile ) return SQLITE_OK;
51144  if( pPager->dbSize==0 ) return SQLITE_OK;
51145  assert( pPager->zFilename && pPager->zFilename[0] );
51146  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
51147  if( rc==SQLITE_NOTFOUND ){
51148    /* If the HAS_MOVED file-control is unimplemented, assume that the file
51149    ** has not been moved.  That is the historical behavior of SQLite: prior to
51150    ** version 3.8.3, it never checked */
51151    rc = SQLITE_OK;
51152  }else if( rc==SQLITE_OK && bHasMoved ){
51153    rc = SQLITE_READONLY_DBMOVED;
51154  }
51155  return rc;
51156}
51157
51158
51159/*
51160** This function is called after transitioning from PAGER_UNLOCK to
51161** PAGER_SHARED state. It tests if there is a hot journal present in
51162** the file-system for the given pager. A hot journal is one that
51163** needs to be played back. According to this function, a hot-journal
51164** file exists if the following criteria are met:
51165**
51166**   * The journal file exists in the file system, and
51167**   * No process holds a RESERVED or greater lock on the database file, and
51168**   * The database file itself is greater than 0 bytes in size, and
51169**   * The first byte of the journal file exists and is not 0x00.
51170**
51171** If the current size of the database file is 0 but a journal file
51172** exists, that is probably an old journal left over from a prior
51173** database with the same name. In this case the journal file is
51174** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
51175** is returned.
51176**
51177** This routine does not check if there is a master journal filename
51178** at the end of the file. If there is, and that master journal file
51179** does not exist, then the journal file is not really hot. In this
51180** case this routine will return a false-positive. The pager_playback()
51181** routine will discover that the journal file is not really hot and
51182** will not roll it back.
51183**
51184** If a hot-journal file is found to exist, *pExists is set to 1 and
51185** SQLITE_OK returned. If no hot-journal file is present, *pExists is
51186** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
51187** to determine whether or not a hot-journal file exists, the IO error
51188** code is returned and the value of *pExists is undefined.
51189*/
51190static int hasHotJournal(Pager *pPager, int *pExists){
51191  sqlite3_vfs * const pVfs = pPager->pVfs;
51192  int rc = SQLITE_OK;           /* Return code */
51193  int exists = 1;               /* True if a journal file is present */
51194  int jrnlOpen = !!isOpen(pPager->jfd);
51195
51196  assert( pPager->useJournal );
51197  assert( isOpen(pPager->fd) );
51198  assert( pPager->eState==PAGER_OPEN );
51199
51200  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
51201    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
51202  ));
51203
51204  *pExists = 0;
51205  if( !jrnlOpen ){
51206    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
51207  }
51208  if( rc==SQLITE_OK && exists ){
51209    int locked = 0;             /* True if some process holds a RESERVED lock */
51210
51211    /* Race condition here:  Another process might have been holding the
51212    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
51213    ** call above, but then delete the journal and drop the lock before
51214    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
51215    ** is the case, this routine might think there is a hot journal when
51216    ** in fact there is none.  This results in a false-positive which will
51217    ** be dealt with by the playback routine.  Ticket #3883.
51218    */
51219    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
51220    if( rc==SQLITE_OK && !locked ){
51221      Pgno nPage;                 /* Number of pages in database file */
51222
51223      assert( pPager->tempFile==0 );
51224      rc = pagerPagecount(pPager, &nPage);
51225      if( rc==SQLITE_OK ){
51226        /* If the database is zero pages in size, that means that either (1) the
51227        ** journal is a remnant from a prior database with the same name where
51228        ** the database file but not the journal was deleted, or (2) the initial
51229        ** transaction that populates a new database is being rolled back.
51230        ** In either case, the journal file can be deleted.  However, take care
51231        ** not to delete the journal file if it is already open due to
51232        ** journal_mode=PERSIST.
51233        */
51234        if( nPage==0 && !jrnlOpen ){
51235          sqlite3BeginBenignMalloc();
51236          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
51237            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
51238            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
51239          }
51240          sqlite3EndBenignMalloc();
51241        }else{
51242          /* The journal file exists and no other connection has a reserved
51243          ** or greater lock on the database file. Now check that there is
51244          ** at least one non-zero bytes at the start of the journal file.
51245          ** If there is, then we consider this journal to be hot. If not,
51246          ** it can be ignored.
51247          */
51248          if( !jrnlOpen ){
51249            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
51250            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51251          }
51252          if( rc==SQLITE_OK ){
51253            u8 first = 0;
51254            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
51255            if( rc==SQLITE_IOERR_SHORT_READ ){
51256              rc = SQLITE_OK;
51257            }
51258            if( !jrnlOpen ){
51259              sqlite3OsClose(pPager->jfd);
51260            }
51261            *pExists = (first!=0);
51262          }else if( rc==SQLITE_CANTOPEN ){
51263            /* If we cannot open the rollback journal file in order to see if
51264            ** it has a zero header, that might be due to an I/O error, or
51265            ** it might be due to the race condition described above and in
51266            ** ticket #3883.  Either way, assume that the journal is hot.
51267            ** This might be a false positive.  But if it is, then the
51268            ** automatic journal playback and recovery mechanism will deal
51269            ** with it under an EXCLUSIVE lock where we do not need to
51270            ** worry so much with race conditions.
51271            */
51272            *pExists = 1;
51273            rc = SQLITE_OK;
51274          }
51275        }
51276      }
51277    }
51278  }
51279
51280  return rc;
51281}
51282
51283/*
51284** This function is called to obtain a shared lock on the database file.
51285** It is illegal to call sqlite3PagerGet() until after this function
51286** has been successfully called. If a shared-lock is already held when
51287** this function is called, it is a no-op.
51288**
51289** The following operations are also performed by this function.
51290**
51291**   1) If the pager is currently in PAGER_OPEN state (no lock held
51292**      on the database file), then an attempt is made to obtain a
51293**      SHARED lock on the database file. Immediately after obtaining
51294**      the SHARED lock, the file-system is checked for a hot-journal,
51295**      which is played back if present. Following any hot-journal
51296**      rollback, the contents of the cache are validated by checking
51297**      the 'change-counter' field of the database file header and
51298**      discarded if they are found to be invalid.
51299**
51300**   2) If the pager is running in exclusive-mode, and there are currently
51301**      no outstanding references to any pages, and is in the error state,
51302**      then an attempt is made to clear the error state by discarding
51303**      the contents of the page cache and rolling back any open journal
51304**      file.
51305**
51306** If everything is successful, SQLITE_OK is returned. If an IO error
51307** occurs while locking the database, checking for a hot-journal file or
51308** rolling back a journal file, the IO error code is returned.
51309*/
51310SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
51311  int rc = SQLITE_OK;                /* Return code */
51312
51313  /* This routine is only called from b-tree and only when there are no
51314  ** outstanding pages. This implies that the pager state should either
51315  ** be OPEN or READER. READER is only possible if the pager is or was in
51316  ** exclusive access mode.  */
51317  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
51318  assert( assert_pager_state(pPager) );
51319  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
51320  assert( pPager->errCode==SQLITE_OK );
51321
51322  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
51323    int bHotJournal = 1;          /* True if there exists a hot journal-file */
51324
51325    assert( !MEMDB );
51326    assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
51327
51328    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
51329    if( rc!=SQLITE_OK ){
51330      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
51331      goto failed;
51332    }
51333
51334    /* If a journal file exists, and there is no RESERVED lock on the
51335    ** database file, then it either needs to be played back or deleted.
51336    */
51337    if( pPager->eLock<=SHARED_LOCK ){
51338      rc = hasHotJournal(pPager, &bHotJournal);
51339    }
51340    if( rc!=SQLITE_OK ){
51341      goto failed;
51342    }
51343    if( bHotJournal ){
51344      if( pPager->readOnly ){
51345        rc = SQLITE_READONLY_ROLLBACK;
51346        goto failed;
51347      }
51348
51349      /* Get an EXCLUSIVE lock on the database file. At this point it is
51350      ** important that a RESERVED lock is not obtained on the way to the
51351      ** EXCLUSIVE lock. If it were, another process might open the
51352      ** database file, detect the RESERVED lock, and conclude that the
51353      ** database is safe to read while this process is still rolling the
51354      ** hot-journal back.
51355      **
51356      ** Because the intermediate RESERVED lock is not requested, any
51357      ** other process attempting to access the database file will get to
51358      ** this point in the code and fail to obtain its own EXCLUSIVE lock
51359      ** on the database file.
51360      **
51361      ** Unless the pager is in locking_mode=exclusive mode, the lock is
51362      ** downgraded to SHARED_LOCK before this function returns.
51363      */
51364      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51365      if( rc!=SQLITE_OK ){
51366        goto failed;
51367      }
51368
51369      /* If it is not already open and the file exists on disk, open the
51370      ** journal for read/write access. Write access is required because
51371      ** in exclusive-access mode the file descriptor will be kept open
51372      ** and possibly used for a transaction later on. Also, write-access
51373      ** is usually required to finalize the journal in journal_mode=persist
51374      ** mode (and also for journal_mode=truncate on some systems).
51375      **
51376      ** If the journal does not exist, it usually means that some
51377      ** other connection managed to get in and roll it back before
51378      ** this connection obtained the exclusive lock above. Or, it
51379      ** may mean that the pager was in the error-state when this
51380      ** function was called and the journal file does not exist.
51381      */
51382      if( !isOpen(pPager->jfd) ){
51383        sqlite3_vfs * const pVfs = pPager->pVfs;
51384        int bExists;              /* True if journal file exists */
51385        rc = sqlite3OsAccess(
51386            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
51387        if( rc==SQLITE_OK && bExists ){
51388          int fout = 0;
51389          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
51390          assert( !pPager->tempFile );
51391          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
51392          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51393          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
51394            rc = SQLITE_CANTOPEN_BKPT;
51395            sqlite3OsClose(pPager->jfd);
51396          }
51397        }
51398      }
51399
51400      /* Playback and delete the journal.  Drop the database write
51401      ** lock and reacquire the read lock. Purge the cache before
51402      ** playing back the hot-journal so that we don't end up with
51403      ** an inconsistent cache.  Sync the hot journal before playing
51404      ** it back since the process that crashed and left the hot journal
51405      ** probably did not sync it and we are required to always sync
51406      ** the journal before playing it back.
51407      */
51408      if( isOpen(pPager->jfd) ){
51409        assert( rc==SQLITE_OK );
51410        rc = pagerSyncHotJournal(pPager);
51411        if( rc==SQLITE_OK ){
51412          rc = pager_playback(pPager, !pPager->tempFile);
51413          pPager->eState = PAGER_OPEN;
51414        }
51415      }else if( !pPager->exclusiveMode ){
51416        pagerUnlockDb(pPager, SHARED_LOCK);
51417      }
51418
51419      if( rc!=SQLITE_OK ){
51420        /* This branch is taken if an error occurs while trying to open
51421        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
51422        ** pager_unlock() routine will be called before returning to unlock
51423        ** the file. If the unlock attempt fails, then Pager.eLock must be
51424        ** set to UNKNOWN_LOCK (see the comment above the #define for
51425        ** UNKNOWN_LOCK above for an explanation).
51426        **
51427        ** In order to get pager_unlock() to do this, set Pager.eState to
51428        ** PAGER_ERROR now. This is not actually counted as a transition
51429        ** to ERROR state in the state diagram at the top of this file,
51430        ** since we know that the same call to pager_unlock() will very
51431        ** shortly transition the pager object to the OPEN state. Calling
51432        ** assert_pager_state() would fail now, as it should not be possible
51433        ** to be in ERROR state when there are zero outstanding page
51434        ** references.
51435        */
51436        pager_error(pPager, rc);
51437        goto failed;
51438      }
51439
51440      assert( pPager->eState==PAGER_OPEN );
51441      assert( (pPager->eLock==SHARED_LOCK)
51442           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
51443      );
51444    }
51445
51446    if( !pPager->tempFile && pPager->hasHeldSharedLock ){
51447      /* The shared-lock has just been acquired then check to
51448      ** see if the database has been modified.  If the database has changed,
51449      ** flush the cache.  The hasHeldSharedLock flag prevents this from
51450      ** occurring on the very first access to a file, in order to save a
51451      ** single unnecessary sqlite3OsRead() call at the start-up.
51452      **
51453      ** Database changes are detected by looking at 15 bytes beginning
51454      ** at offset 24 into the file.  The first 4 of these 16 bytes are
51455      ** a 32-bit counter that is incremented with each change.  The
51456      ** other bytes change randomly with each file change when
51457      ** a codec is in use.
51458      **
51459      ** There is a vanishingly small chance that a change will not be
51460      ** detected.  The chance of an undetected change is so small that
51461      ** it can be neglected.
51462      */
51463      Pgno nPage = 0;
51464      char dbFileVers[sizeof(pPager->dbFileVers)];
51465
51466      rc = pagerPagecount(pPager, &nPage);
51467      if( rc ) goto failed;
51468
51469      if( nPage>0 ){
51470        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
51471        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
51472        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51473          goto failed;
51474        }
51475      }else{
51476        memset(dbFileVers, 0, sizeof(dbFileVers));
51477      }
51478
51479      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
51480        pager_reset(pPager);
51481
51482        /* Unmap the database file. It is possible that external processes
51483        ** may have truncated the database file and then extended it back
51484        ** to its original size while this process was not holding a lock.
51485        ** In this case there may exist a Pager.pMap mapping that appears
51486        ** to be the right size but is not actually valid. Avoid this
51487        ** possibility by unmapping the db here. */
51488        if( USEFETCH(pPager) ){
51489          sqlite3OsUnfetch(pPager->fd, 0, 0);
51490        }
51491      }
51492    }
51493
51494    /* If there is a WAL file in the file-system, open this database in WAL
51495    ** mode. Otherwise, the following function call is a no-op.
51496    */
51497    rc = pagerOpenWalIfPresent(pPager);
51498#ifndef SQLITE_OMIT_WAL
51499    assert( pPager->pWal==0 || rc==SQLITE_OK );
51500#endif
51501  }
51502
51503  if( pagerUseWal(pPager) ){
51504    assert( rc==SQLITE_OK );
51505    rc = pagerBeginReadTransaction(pPager);
51506  }
51507
51508  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51509    rc = pagerPagecount(pPager, &pPager->dbSize);
51510  }
51511
51512 failed:
51513  if( rc!=SQLITE_OK ){
51514    assert( !MEMDB );
51515    pager_unlock(pPager);
51516    assert( pPager->eState==PAGER_OPEN );
51517  }else{
51518    pPager->eState = PAGER_READER;
51519    pPager->hasHeldSharedLock = 1;
51520  }
51521  return rc;
51522}
51523
51524/*
51525** If the reference count has reached zero, rollback any active
51526** transaction and unlock the pager.
51527**
51528** Except, in locking_mode=EXCLUSIVE when there is nothing to in
51529** the rollback journal, the unlock is not performed and there is
51530** nothing to rollback, so this routine is a no-op.
51531*/
51532static void pagerUnlockIfUnused(Pager *pPager){
51533  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
51534    pagerUnlockAndRollback(pPager);
51535  }
51536}
51537
51538/*
51539** Acquire a reference to page number pgno in pager pPager (a page
51540** reference has type DbPage*). If the requested reference is
51541** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
51542**
51543** If the requested page is already in the cache, it is returned.
51544** Otherwise, a new page object is allocated and populated with data
51545** read from the database file. In some cases, the pcache module may
51546** choose not to allocate a new page object and may reuse an existing
51547** object with no outstanding references.
51548**
51549** The extra data appended to a page is always initialized to zeros the
51550** first time a page is loaded into memory. If the page requested is
51551** already in the cache when this function is called, then the extra
51552** data is left as it was when the page object was last used.
51553**
51554** If the database image is smaller than the requested page or if a
51555** non-zero value is passed as the noContent parameter and the
51556** requested page is not already stored in the cache, then no
51557** actual disk read occurs. In this case the memory image of the
51558** page is initialized to all zeros.
51559**
51560** If noContent is true, it means that we do not care about the contents
51561** of the page. This occurs in two scenarios:
51562**
51563**   a) When reading a free-list leaf page from the database, and
51564**
51565**   b) When a savepoint is being rolled back and we need to load
51566**      a new page into the cache to be filled with the data read
51567**      from the savepoint journal.
51568**
51569** If noContent is true, then the data returned is zeroed instead of
51570** being read from the database. Additionally, the bits corresponding
51571** to pgno in Pager.pInJournal (bitvec of pages already written to the
51572** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
51573** savepoints are set. This means if the page is made writable at any
51574** point in the future, using a call to sqlite3PagerWrite(), its contents
51575** will not be journaled. This saves IO.
51576**
51577** The acquisition might fail for several reasons.  In all cases,
51578** an appropriate error code is returned and *ppPage is set to NULL.
51579**
51580** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
51581** to find a page in the in-memory cache first.  If the page is not already
51582** in memory, this routine goes to disk to read it in whereas Lookup()
51583** just returns 0.  This routine acquires a read-lock the first time it
51584** has to go to disk, and could also playback an old journal if necessary.
51585** Since Lookup() never goes to disk, it never has to deal with locks
51586** or journal files.
51587*/
51588SQLITE_PRIVATE int sqlite3PagerGet(
51589  Pager *pPager,      /* The pager open on the database file */
51590  Pgno pgno,          /* Page number to fetch */
51591  DbPage **ppPage,    /* Write a pointer to the page here */
51592  int flags           /* PAGER_GET_XXX flags */
51593){
51594  int rc = SQLITE_OK;
51595  PgHdr *pPg = 0;
51596  u32 iFrame = 0;                 /* Frame to read from WAL file */
51597  const int noContent = (flags & PAGER_GET_NOCONTENT);
51598
51599  /* It is acceptable to use a read-only (mmap) page for any page except
51600  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
51601  ** flag was specified by the caller. And so long as the db is not a
51602  ** temporary or in-memory database.  */
51603  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
51604   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
51605#ifdef SQLITE_HAS_CODEC
51606   && pPager->xCodec==0
51607#endif
51608  );
51609
51610  /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
51611  ** allows the compiler optimizer to reuse the results of the "pgno>1"
51612  ** test in the previous statement, and avoid testing pgno==0 in the
51613  ** common case where pgno is large. */
51614  if( pgno<=1 && pgno==0 ){
51615    return SQLITE_CORRUPT_BKPT;
51616  }
51617  assert( pPager->eState>=PAGER_READER );
51618  assert( assert_pager_state(pPager) );
51619  assert( noContent==0 || bMmapOk==0 );
51620
51621  assert( pPager->hasHeldSharedLock==1 );
51622
51623  /* If the pager is in the error state, return an error immediately.
51624  ** Otherwise, request the page from the PCache layer. */
51625  if( pPager->errCode!=SQLITE_OK ){
51626    rc = pPager->errCode;
51627  }else{
51628    if( bMmapOk && pagerUseWal(pPager) ){
51629      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51630      if( rc!=SQLITE_OK ) goto pager_acquire_err;
51631    }
51632
51633    if( bMmapOk && iFrame==0 ){
51634      void *pData = 0;
51635
51636      rc = sqlite3OsFetch(pPager->fd,
51637          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51638      );
51639
51640      if( rc==SQLITE_OK && pData ){
51641        if( pPager->eState>PAGER_READER || pPager->tempFile ){
51642          pPg = sqlite3PagerLookup(pPager, pgno);
51643        }
51644        if( pPg==0 ){
51645          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51646        }else{
51647          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
51648        }
51649        if( pPg ){
51650          assert( rc==SQLITE_OK );
51651          *ppPage = pPg;
51652          return SQLITE_OK;
51653        }
51654      }
51655      if( rc!=SQLITE_OK ){
51656        goto pager_acquire_err;
51657      }
51658    }
51659
51660    {
51661      sqlite3_pcache_page *pBase;
51662      pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
51663      if( pBase==0 ){
51664        rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
51665        if( rc!=SQLITE_OK ) goto pager_acquire_err;
51666        if( pBase==0 ){
51667          pPg = *ppPage = 0;
51668          rc = SQLITE_NOMEM_BKPT;
51669          goto pager_acquire_err;
51670        }
51671      }
51672      pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
51673      assert( pPg!=0 );
51674    }
51675  }
51676
51677  if( rc!=SQLITE_OK ){
51678    /* Either the call to sqlite3PcacheFetch() returned an error or the
51679    ** pager was already in the error-state when this function was called.
51680    ** Set pPg to 0 and jump to the exception handler.  */
51681    pPg = 0;
51682    goto pager_acquire_err;
51683  }
51684  assert( pPg==(*ppPage) );
51685  assert( pPg->pgno==pgno );
51686  assert( pPg->pPager==pPager || pPg->pPager==0 );
51687
51688  if( pPg->pPager && !noContent ){
51689    /* In this case the pcache already contains an initialized copy of
51690    ** the page. Return without further ado.  */
51691    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
51692    pPager->aStat[PAGER_STAT_HIT]++;
51693    return SQLITE_OK;
51694
51695  }else{
51696    /* The pager cache has created a new page. Its content needs to
51697    ** be initialized.  */
51698
51699    pPg->pPager = pPager;
51700
51701    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
51702    ** number greater than this, or the unused locking-page, is requested. */
51703    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51704      rc = SQLITE_CORRUPT_BKPT;
51705      goto pager_acquire_err;
51706    }
51707
51708    assert( !isOpen(pPager->fd) || !MEMDB );
51709    if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51710      if( pgno>pPager->mxPgno ){
51711        rc = SQLITE_FULL;
51712        goto pager_acquire_err;
51713      }
51714      if( noContent ){
51715        /* Failure to set the bits in the InJournal bit-vectors is benign.
51716        ** It merely means that we might do some extra work to journal a
51717        ** page that does not need to be journaled.  Nevertheless, be sure
51718        ** to test the case where a malloc error occurs while trying to set
51719        ** a bit in a bit vector.
51720        */
51721        sqlite3BeginBenignMalloc();
51722        if( pgno<=pPager->dbOrigSize ){
51723          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
51724          testcase( rc==SQLITE_NOMEM );
51725        }
51726        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
51727        testcase( rc==SQLITE_NOMEM );
51728        sqlite3EndBenignMalloc();
51729      }
51730      memset(pPg->pData, 0, pPager->pageSize);
51731      IOTRACE(("ZERO %p %d\n", pPager, pgno));
51732    }else{
51733      if( pagerUseWal(pPager) && bMmapOk==0 ){
51734        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51735        if( rc!=SQLITE_OK ) goto pager_acquire_err;
51736      }
51737      assert( pPg->pPager==pPager );
51738      pPager->aStat[PAGER_STAT_MISS]++;
51739      rc = readDbPage(pPg, iFrame);
51740      if( rc!=SQLITE_OK ){
51741        goto pager_acquire_err;
51742      }
51743    }
51744    pager_set_pagehash(pPg);
51745  }
51746
51747  return SQLITE_OK;
51748
51749pager_acquire_err:
51750  assert( rc!=SQLITE_OK );
51751  if( pPg ){
51752    sqlite3PcacheDrop(pPg);
51753  }
51754  pagerUnlockIfUnused(pPager);
51755
51756  *ppPage = 0;
51757  return rc;
51758}
51759
51760/*
51761** Acquire a page if it is already in the in-memory cache.  Do
51762** not read the page from disk.  Return a pointer to the page,
51763** or 0 if the page is not in cache.
51764**
51765** See also sqlite3PagerGet().  The difference between this routine
51766** and sqlite3PagerGet() is that _get() will go to the disk and read
51767** in the page if the page is not already in cache.  This routine
51768** returns NULL if the page is not in cache or if a disk I/O error
51769** has ever happened.
51770*/
51771SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
51772  sqlite3_pcache_page *pPage;
51773  assert( pPager!=0 );
51774  assert( pgno!=0 );
51775  assert( pPager->pPCache!=0 );
51776  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
51777  assert( pPage==0 || pPager->hasHeldSharedLock );
51778  if( pPage==0 ) return 0;
51779  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
51780}
51781
51782/*
51783** Release a page reference.
51784**
51785** If the number of references to the page drop to zero, then the
51786** page is added to the LRU list.  When all references to all pages
51787** are released, a rollback occurs and the lock on the database is
51788** removed.
51789*/
51790SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
51791  Pager *pPager;
51792  assert( pPg!=0 );
51793  pPager = pPg->pPager;
51794  if( pPg->flags & PGHDR_MMAP ){
51795    pagerReleaseMapPage(pPg);
51796  }else{
51797    sqlite3PcacheRelease(pPg);
51798  }
51799  pagerUnlockIfUnused(pPager);
51800}
51801SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
51802  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
51803}
51804
51805/*
51806** This function is called at the start of every write transaction.
51807** There must already be a RESERVED or EXCLUSIVE lock on the database
51808** file when this routine is called.
51809**
51810** Open the journal file for pager pPager and write a journal header
51811** to the start of it. If there are active savepoints, open the sub-journal
51812** as well. This function is only used when the journal file is being
51813** opened to write a rollback log for a transaction. It is not used
51814** when opening a hot journal file to roll it back.
51815**
51816** If the journal file is already open (as it may be in exclusive mode),
51817** then this function just writes a journal header to the start of the
51818** already open file.
51819**
51820** Whether or not the journal file is opened by this function, the
51821** Pager.pInJournal bitvec structure is allocated.
51822**
51823** Return SQLITE_OK if everything is successful. Otherwise, return
51824** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
51825** an IO error code if opening or writing the journal file fails.
51826*/
51827static int pager_open_journal(Pager *pPager){
51828  int rc = SQLITE_OK;                        /* Return code */
51829  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
51830
51831  assert( pPager->eState==PAGER_WRITER_LOCKED );
51832  assert( assert_pager_state(pPager) );
51833  assert( pPager->pInJournal==0 );
51834
51835  /* If already in the error state, this function is a no-op.  But on
51836  ** the other hand, this routine is never called if we are already in
51837  ** an error state. */
51838  if( NEVER(pPager->errCode) ) return pPager->errCode;
51839
51840  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51841    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
51842    if( pPager->pInJournal==0 ){
51843      return SQLITE_NOMEM_BKPT;
51844    }
51845
51846    /* Open the journal file if it is not already open. */
51847    if( !isOpen(pPager->jfd) ){
51848      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51849        sqlite3MemJournalOpen(pPager->jfd);
51850      }else{
51851        int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
51852        int nSpill;
51853
51854        if( pPager->tempFile ){
51855          flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
51856          nSpill = sqlite3Config.nStmtSpill;
51857        }else{
51858          flags |= SQLITE_OPEN_MAIN_JOURNAL;
51859          nSpill = jrnlBufferSize(pPager);
51860        }
51861
51862        /* Verify that the database still has the same name as it did when
51863        ** it was originally opened. */
51864        rc = databaseIsUnmoved(pPager);
51865        if( rc==SQLITE_OK ){
51866          rc = sqlite3JournalOpen (
51867              pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
51868          );
51869        }
51870      }
51871      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51872    }
51873
51874
51875    /* Write the first journal header to the journal file and open
51876    ** the sub-journal if necessary.
51877    */
51878    if( rc==SQLITE_OK ){
51879      /* TODO: Check if all of these are really required. */
51880      pPager->nRec = 0;
51881      pPager->journalOff = 0;
51882      pPager->setMaster = 0;
51883      pPager->journalHdr = 0;
51884      rc = writeJournalHdr(pPager);
51885    }
51886  }
51887
51888  if( rc!=SQLITE_OK ){
51889    sqlite3BitvecDestroy(pPager->pInJournal);
51890    pPager->pInJournal = 0;
51891  }else{
51892    assert( pPager->eState==PAGER_WRITER_LOCKED );
51893    pPager->eState = PAGER_WRITER_CACHEMOD;
51894  }
51895
51896  return rc;
51897}
51898
51899/*
51900** Begin a write-transaction on the specified pager object. If a
51901** write-transaction has already been opened, this function is a no-op.
51902**
51903** If the exFlag argument is false, then acquire at least a RESERVED
51904** lock on the database file. If exFlag is true, then acquire at least
51905** an EXCLUSIVE lock. If such a lock is already held, no locking
51906** functions need be called.
51907**
51908** If the subjInMemory argument is non-zero, then any sub-journal opened
51909** within this transaction will be opened as an in-memory file. This
51910** has no effect if the sub-journal is already opened (as it may be when
51911** running in exclusive mode) or if the transaction does not require a
51912** sub-journal. If the subjInMemory argument is zero, then any required
51913** sub-journal is implemented in-memory if pPager is an in-memory database,
51914** or using a temporary file otherwise.
51915*/
51916SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
51917  int rc = SQLITE_OK;
51918
51919  if( pPager->errCode ) return pPager->errCode;
51920  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
51921  pPager->subjInMemory = (u8)subjInMemory;
51922
51923  if( ALWAYS(pPager->eState==PAGER_READER) ){
51924    assert( pPager->pInJournal==0 );
51925
51926    if( pagerUseWal(pPager) ){
51927      /* If the pager is configured to use locking_mode=exclusive, and an
51928      ** exclusive lock on the database is not already held, obtain it now.
51929      */
51930      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
51931        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51932        if( rc!=SQLITE_OK ){
51933          return rc;
51934        }
51935        (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
51936      }
51937
51938      /* Grab the write lock on the log file. If successful, upgrade to
51939      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
51940      ** The busy-handler is not invoked if another connection already
51941      ** holds the write-lock. If possible, the upper layer will call it.
51942      */
51943      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
51944    }else{
51945      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
51946      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
51947      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
51948      ** lock, but not when obtaining the RESERVED lock.
51949      */
51950      rc = pagerLockDb(pPager, RESERVED_LOCK);
51951      if( rc==SQLITE_OK && exFlag ){
51952        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
51953      }
51954    }
51955
51956    if( rc==SQLITE_OK ){
51957      /* Change to WRITER_LOCKED state.
51958      **
51959      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
51960      ** when it has an open transaction, but never to DBMOD or FINISHED.
51961      ** This is because in those states the code to roll back savepoint
51962      ** transactions may copy data from the sub-journal into the database
51963      ** file as well as into the page cache. Which would be incorrect in
51964      ** WAL mode.
51965      */
51966      pPager->eState = PAGER_WRITER_LOCKED;
51967      pPager->dbHintSize = pPager->dbSize;
51968      pPager->dbFileSize = pPager->dbSize;
51969      pPager->dbOrigSize = pPager->dbSize;
51970      pPager->journalOff = 0;
51971    }
51972
51973    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
51974    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
51975    assert( assert_pager_state(pPager) );
51976  }
51977
51978  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
51979  return rc;
51980}
51981
51982/*
51983** Write page pPg onto the end of the rollback journal.
51984*/
51985static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
51986  Pager *pPager = pPg->pPager;
51987  int rc;
51988  u32 cksum;
51989  char *pData2;
51990  i64 iOff = pPager->journalOff;
51991
51992  /* We should never write to the journal file the page that
51993  ** contains the database locks.  The following assert verifies
51994  ** that we do not. */
51995  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
51996
51997  assert( pPager->journalHdr<=pPager->journalOff );
51998  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51999  cksum = pager_cksum(pPager, (u8*)pData2);
52000
52001  /* Even if an IO or diskfull error occurs while journalling the
52002  ** page in the block above, set the need-sync flag for the page.
52003  ** Otherwise, when the transaction is rolled back, the logic in
52004  ** playback_one_page() will think that the page needs to be restored
52005  ** in the database file. And if an IO error occurs while doing so,
52006  ** then corruption may follow.
52007  */
52008  pPg->flags |= PGHDR_NEED_SYNC;
52009
52010  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
52011  if( rc!=SQLITE_OK ) return rc;
52012  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
52013  if( rc!=SQLITE_OK ) return rc;
52014  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
52015  if( rc!=SQLITE_OK ) return rc;
52016
52017  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
52018           pPager->journalOff, pPager->pageSize));
52019  PAGER_INCR(sqlite3_pager_writej_count);
52020  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
52021       PAGERID(pPager), pPg->pgno,
52022       ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
52023
52024  pPager->journalOff += 8 + pPager->pageSize;
52025  pPager->nRec++;
52026  assert( pPager->pInJournal!=0 );
52027  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
52028  testcase( rc==SQLITE_NOMEM );
52029  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52030  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
52031  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52032  return rc;
52033}
52034
52035/*
52036** Mark a single data page as writeable. The page is written into the
52037** main journal or sub-journal as required. If the page is written into
52038** one of the journals, the corresponding bit is set in the
52039** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
52040** of any open savepoints as appropriate.
52041*/
52042static int pager_write(PgHdr *pPg){
52043  Pager *pPager = pPg->pPager;
52044  int rc = SQLITE_OK;
52045
52046  /* This routine is not called unless a write-transaction has already
52047  ** been started. The journal file may or may not be open at this point.
52048  ** It is never called in the ERROR state.
52049  */
52050  assert( pPager->eState==PAGER_WRITER_LOCKED
52051       || pPager->eState==PAGER_WRITER_CACHEMOD
52052       || pPager->eState==PAGER_WRITER_DBMOD
52053  );
52054  assert( assert_pager_state(pPager) );
52055  assert( pPager->errCode==0 );
52056  assert( pPager->readOnly==0 );
52057  CHECK_PAGE(pPg);
52058
52059  /* The journal file needs to be opened. Higher level routines have already
52060  ** obtained the necessary locks to begin the write-transaction, but the
52061  ** rollback journal might not yet be open. Open it now if this is the case.
52062  **
52063  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
52064  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
52065  ** an error might occur and the pager would end up in WRITER_LOCKED state
52066  ** with pages marked as dirty in the cache.
52067  */
52068  if( pPager->eState==PAGER_WRITER_LOCKED ){
52069    rc = pager_open_journal(pPager);
52070    if( rc!=SQLITE_OK ) return rc;
52071  }
52072  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
52073  assert( assert_pager_state(pPager) );
52074
52075  /* Mark the page that is about to be modified as dirty. */
52076  sqlite3PcacheMakeDirty(pPg);
52077
52078  /* If a rollback journal is in use, them make sure the page that is about
52079  ** to change is in the rollback journal, or if the page is a new page off
52080  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
52081  */
52082  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
52083  if( pPager->pInJournal!=0
52084   && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
52085  ){
52086    assert( pagerUseWal(pPager)==0 );
52087    if( pPg->pgno<=pPager->dbOrigSize ){
52088      rc = pagerAddPageToRollbackJournal(pPg);
52089      if( rc!=SQLITE_OK ){
52090        return rc;
52091      }
52092    }else{
52093      if( pPager->eState!=PAGER_WRITER_DBMOD ){
52094        pPg->flags |= PGHDR_NEED_SYNC;
52095      }
52096      PAGERTRACE(("APPEND %d page %d needSync=%d\n",
52097              PAGERID(pPager), pPg->pgno,
52098             ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
52099    }
52100  }
52101
52102  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
52103  ** and before writing the page into the rollback journal.  Wait until now,
52104  ** after the page has been successfully journalled, before setting the
52105  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
52106  */
52107  pPg->flags |= PGHDR_WRITEABLE;
52108
52109  /* If the statement journal is open and the page is not in it,
52110  ** then write the page into the statement journal.
52111  */
52112  if( pPager->nSavepoint>0 ){
52113    rc = subjournalPageIfRequired(pPg);
52114  }
52115
52116  /* Update the database size and return. */
52117  if( pPager->dbSize<pPg->pgno ){
52118    pPager->dbSize = pPg->pgno;
52119  }
52120  return rc;
52121}
52122
52123/*
52124** This is a variant of sqlite3PagerWrite() that runs when the sector size
52125** is larger than the page size.  SQLite makes the (reasonable) assumption that
52126** all bytes of a sector are written together by hardware.  Hence, all bytes of
52127** a sector need to be journalled in case of a power loss in the middle of
52128** a write.
52129**
52130** Usually, the sector size is less than or equal to the page size, in which
52131** case pages can be individually written.  This routine only runs in the
52132** exceptional case where the page size is smaller than the sector size.
52133*/
52134static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
52135  int rc = SQLITE_OK;          /* Return code */
52136  Pgno nPageCount;             /* Total number of pages in database file */
52137  Pgno pg1;                    /* First page of the sector pPg is located on. */
52138  int nPage = 0;               /* Number of pages starting at pg1 to journal */
52139  int ii;                      /* Loop counter */
52140  int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
52141  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
52142  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
52143
52144  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
52145  ** a journal header to be written between the pages journaled by
52146  ** this function.
52147  */
52148  assert( !MEMDB );
52149  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
52150  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
52151
52152  /* This trick assumes that both the page-size and sector-size are
52153  ** an integer power of 2. It sets variable pg1 to the identifier
52154  ** of the first page of the sector pPg is located on.
52155  */
52156  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
52157
52158  nPageCount = pPager->dbSize;
52159  if( pPg->pgno>nPageCount ){
52160    nPage = (pPg->pgno - pg1)+1;
52161  }else if( (pg1+nPagePerSector-1)>nPageCount ){
52162    nPage = nPageCount+1-pg1;
52163  }else{
52164    nPage = nPagePerSector;
52165  }
52166  assert(nPage>0);
52167  assert(pg1<=pPg->pgno);
52168  assert((pg1+nPage)>pPg->pgno);
52169
52170  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
52171    Pgno pg = pg1+ii;
52172    PgHdr *pPage;
52173    if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
52174      if( pg!=PAGER_MJ_PGNO(pPager) ){
52175        rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
52176        if( rc==SQLITE_OK ){
52177          rc = pager_write(pPage);
52178          if( pPage->flags&PGHDR_NEED_SYNC ){
52179            needSync = 1;
52180          }
52181          sqlite3PagerUnrefNotNull(pPage);
52182        }
52183      }
52184    }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
52185      if( pPage->flags&PGHDR_NEED_SYNC ){
52186        needSync = 1;
52187      }
52188      sqlite3PagerUnrefNotNull(pPage);
52189    }
52190  }
52191
52192  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
52193  ** starting at pg1, then it needs to be set for all of them. Because
52194  ** writing to any of these nPage pages may damage the others, the
52195  ** journal file must contain sync()ed copies of all of them
52196  ** before any of them can be written out to the database file.
52197  */
52198  if( rc==SQLITE_OK && needSync ){
52199    assert( !MEMDB );
52200    for(ii=0; ii<nPage; ii++){
52201      PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
52202      if( pPage ){
52203        pPage->flags |= PGHDR_NEED_SYNC;
52204        sqlite3PagerUnrefNotNull(pPage);
52205      }
52206    }
52207  }
52208
52209  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
52210  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
52211  return rc;
52212}
52213
52214/*
52215** Mark a data page as writeable. This routine must be called before
52216** making changes to a page. The caller must check the return value
52217** of this function and be careful not to change any page data unless
52218** this routine returns SQLITE_OK.
52219**
52220** The difference between this function and pager_write() is that this
52221** function also deals with the special case where 2 or more pages
52222** fit on a single disk sector. In this case all co-resident pages
52223** must have been written to the journal file before returning.
52224**
52225** If an error occurs, SQLITE_NOMEM or an IO error code is returned
52226** as appropriate. Otherwise, SQLITE_OK.
52227*/
52228SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
52229  Pager *pPager = pPg->pPager;
52230  assert( (pPg->flags & PGHDR_MMAP)==0 );
52231  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52232  assert( assert_pager_state(pPager) );
52233  if( pPager->errCode ){
52234    return pPager->errCode;
52235  }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
52236    if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
52237    return SQLITE_OK;
52238  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
52239    assert( pPager->tempFile==0 );
52240    return pagerWriteLargeSector(pPg);
52241  }else{
52242    return pager_write(pPg);
52243  }
52244}
52245
52246/*
52247** Return TRUE if the page given in the argument was previously passed
52248** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
52249** to change the content of the page.
52250*/
52251#ifndef NDEBUG
52252SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
52253  return pPg->flags & PGHDR_WRITEABLE;
52254}
52255#endif
52256
52257/*
52258** A call to this routine tells the pager that it is not necessary to
52259** write the information on page pPg back to the disk, even though
52260** that page might be marked as dirty.  This happens, for example, when
52261** the page has been added as a leaf of the freelist and so its
52262** content no longer matters.
52263**
52264** The overlying software layer calls this routine when all of the data
52265** on the given page is unused. The pager marks the page as clean so
52266** that it does not get written to disk.
52267**
52268** Tests show that this optimization can quadruple the speed of large
52269** DELETE operations.
52270**
52271** This optimization cannot be used with a temp-file, as the page may
52272** have been dirty at the start of the transaction. In that case, if
52273** memory pressure forces page pPg out of the cache, the data does need
52274** to be written out to disk so that it may be read back in if the
52275** current transaction is rolled back.
52276*/
52277SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
52278  Pager *pPager = pPg->pPager;
52279  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
52280    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
52281    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
52282    pPg->flags |= PGHDR_DONT_WRITE;
52283    pPg->flags &= ~PGHDR_WRITEABLE;
52284    testcase( pPg->flags & PGHDR_NEED_SYNC );
52285    pager_set_pagehash(pPg);
52286  }
52287}
52288
52289/*
52290** This routine is called to increment the value of the database file
52291** change-counter, stored as a 4-byte big-endian integer starting at
52292** byte offset 24 of the pager file.  The secondary change counter at
52293** 92 is also updated, as is the SQLite version number at offset 96.
52294**
52295** But this only happens if the pPager->changeCountDone flag is false.
52296** To avoid excess churning of page 1, the update only happens once.
52297** See also the pager_write_changecounter() routine that does an
52298** unconditional update of the change counters.
52299**
52300** If the isDirectMode flag is zero, then this is done by calling
52301** sqlite3PagerWrite() on page 1, then modifying the contents of the
52302** page data. In this case the file will be updated when the current
52303** transaction is committed.
52304**
52305** The isDirectMode flag may only be non-zero if the library was compiled
52306** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
52307** if isDirect is non-zero, then the database file is updated directly
52308** by writing an updated version of page 1 using a call to the
52309** sqlite3OsWrite() function.
52310*/
52311static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
52312  int rc = SQLITE_OK;
52313
52314  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52315       || pPager->eState==PAGER_WRITER_DBMOD
52316  );
52317  assert( assert_pager_state(pPager) );
52318
52319  /* Declare and initialize constant integer 'isDirect'. If the
52320  ** atomic-write optimization is enabled in this build, then isDirect
52321  ** is initialized to the value passed as the isDirectMode parameter
52322  ** to this function. Otherwise, it is always set to zero.
52323  **
52324  ** The idea is that if the atomic-write optimization is not
52325  ** enabled at compile time, the compiler can omit the tests of
52326  ** 'isDirect' below, as well as the block enclosed in the
52327  ** "if( isDirect )" condition.
52328  */
52329#ifndef SQLITE_ENABLE_ATOMIC_WRITE
52330# define DIRECT_MODE 0
52331  assert( isDirectMode==0 );
52332  UNUSED_PARAMETER(isDirectMode);
52333#else
52334# define DIRECT_MODE isDirectMode
52335#endif
52336
52337  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
52338    PgHdr *pPgHdr;                /* Reference to page 1 */
52339
52340    assert( !pPager->tempFile && isOpen(pPager->fd) );
52341
52342    /* Open page 1 of the file for writing. */
52343    rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
52344    assert( pPgHdr==0 || rc==SQLITE_OK );
52345
52346    /* If page one was fetched successfully, and this function is not
52347    ** operating in direct-mode, make page 1 writable.  When not in
52348    ** direct mode, page 1 is always held in cache and hence the PagerGet()
52349    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
52350    */
52351    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
52352      rc = sqlite3PagerWrite(pPgHdr);
52353    }
52354
52355    if( rc==SQLITE_OK ){
52356      /* Actually do the update of the change counter */
52357      pager_write_changecounter(pPgHdr);
52358
52359      /* If running in direct mode, write the contents of page 1 to the file. */
52360      if( DIRECT_MODE ){
52361        const void *zBuf;
52362        assert( pPager->dbFileSize>0 );
52363        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
52364        if( rc==SQLITE_OK ){
52365          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
52366          pPager->aStat[PAGER_STAT_WRITE]++;
52367        }
52368        if( rc==SQLITE_OK ){
52369          /* Update the pager's copy of the change-counter. Otherwise, the
52370          ** next time a read transaction is opened the cache will be
52371          ** flushed (as the change-counter values will not match).  */
52372          const void *pCopy = (const void *)&((const char *)zBuf)[24];
52373          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
52374          pPager->changeCountDone = 1;
52375        }
52376      }else{
52377        pPager->changeCountDone = 1;
52378      }
52379    }
52380
52381    /* Release the page reference. */
52382    sqlite3PagerUnref(pPgHdr);
52383  }
52384  return rc;
52385}
52386
52387/*
52388** Sync the database file to disk. This is a no-op for in-memory databases
52389** or pages with the Pager.noSync flag set.
52390**
52391** If successful, or if called on a pager for which it is a no-op, this
52392** function returns SQLITE_OK. Otherwise, an IO error code is returned.
52393*/
52394SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
52395  int rc = SQLITE_OK;
52396
52397  if( isOpen(pPager->fd) ){
52398    void *pArg = (void*)zMaster;
52399    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
52400    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
52401  }
52402  if( rc==SQLITE_OK && !pPager->noSync ){
52403    assert( !MEMDB );
52404    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
52405  }
52406  return rc;
52407}
52408
52409/*
52410** This function may only be called while a write-transaction is active in
52411** rollback. If the connection is in WAL mode, this call is a no-op.
52412** Otherwise, if the connection does not already have an EXCLUSIVE lock on
52413** the database file, an attempt is made to obtain one.
52414**
52415** If the EXCLUSIVE lock is already held or the attempt to obtain it is
52416** successful, or the connection is in WAL mode, SQLITE_OK is returned.
52417** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
52418** returned.
52419*/
52420SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
52421  int rc = pPager->errCode;
52422  assert( assert_pager_state(pPager) );
52423  if( rc==SQLITE_OK ){
52424    assert( pPager->eState==PAGER_WRITER_CACHEMOD
52425         || pPager->eState==PAGER_WRITER_DBMOD
52426         || pPager->eState==PAGER_WRITER_LOCKED
52427    );
52428    assert( assert_pager_state(pPager) );
52429    if( 0==pagerUseWal(pPager) ){
52430      rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52431    }
52432  }
52433  return rc;
52434}
52435
52436/*
52437** Sync the database file for the pager pPager. zMaster points to the name
52438** of a master journal file that should be written into the individual
52439** journal file. zMaster may be NULL, which is interpreted as no master
52440** journal (a single database transaction).
52441**
52442** This routine ensures that:
52443**
52444**   * The database file change-counter is updated,
52445**   * the journal is synced (unless the atomic-write optimization is used),
52446**   * all dirty pages are written to the database file,
52447**   * the database file is truncated (if required), and
52448**   * the database file synced.
52449**
52450** The only thing that remains to commit the transaction is to finalize
52451** (delete, truncate or zero the first part of) the journal file (or
52452** delete the master journal file if specified).
52453**
52454** Note that if zMaster==NULL, this does not overwrite a previous value
52455** passed to an sqlite3PagerCommitPhaseOne() call.
52456**
52457** If the final parameter - noSync - is true, then the database file itself
52458** is not synced. The caller must call sqlite3PagerSync() directly to
52459** sync the database file before calling CommitPhaseTwo() to delete the
52460** journal file in this case.
52461*/
52462SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
52463  Pager *pPager,                  /* Pager object */
52464  const char *zMaster,            /* If not NULL, the master journal name */
52465  int noSync                      /* True to omit the xSync on the db file */
52466){
52467  int rc = SQLITE_OK;             /* Return code */
52468
52469  assert( pPager->eState==PAGER_WRITER_LOCKED
52470       || pPager->eState==PAGER_WRITER_CACHEMOD
52471       || pPager->eState==PAGER_WRITER_DBMOD
52472       || pPager->eState==PAGER_ERROR
52473  );
52474  assert( assert_pager_state(pPager) );
52475
52476  /* If a prior error occurred, report that error again. */
52477  if( NEVER(pPager->errCode) ) return pPager->errCode;
52478
52479  /* Provide the ability to easily simulate an I/O error during testing */
52480  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52481
52482  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
52483      pPager->zFilename, zMaster, pPager->dbSize));
52484
52485  /* If no database changes have been made, return early. */
52486  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52487
52488  assert( MEMDB==0 || pPager->tempFile );
52489  assert( isOpen(pPager->fd) || pPager->tempFile );
52490  if( 0==pagerFlushOnCommit(pPager, 1) ){
52491    /* If this is an in-memory db, or no pages have been written to, or this
52492    ** function has already been called, it is mostly a no-op.  However, any
52493    ** backup in progress needs to be restarted.  */
52494    sqlite3BackupRestart(pPager->pBackup);
52495  }else{
52496    if( pagerUseWal(pPager) ){
52497      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52498      PgHdr *pPageOne = 0;
52499      if( pList==0 ){
52500        /* Must have at least one page for the WAL commit flag.
52501        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
52502        rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
52503        pList = pPageOne;
52504        pList->pDirty = 0;
52505      }
52506      assert( rc==SQLITE_OK );
52507      if( ALWAYS(pList) ){
52508        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
52509      }
52510      sqlite3PagerUnref(pPageOne);
52511      if( rc==SQLITE_OK ){
52512        sqlite3PcacheCleanAll(pPager->pPCache);
52513      }
52514    }else{
52515      /* The following block updates the change-counter. Exactly how it
52516      ** does this depends on whether or not the atomic-update optimization
52517      ** was enabled at compile time, and if this transaction meets the
52518      ** runtime criteria to use the operation:
52519      **
52520      **    * The file-system supports the atomic-write property for
52521      **      blocks of size page-size, and
52522      **    * This commit is not part of a multi-file transaction, and
52523      **    * Exactly one page has been modified and store in the journal file.
52524      **
52525      ** If the optimization was not enabled at compile time, then the
52526      ** pager_incr_changecounter() function is called to update the change
52527      ** counter in 'indirect-mode'. If the optimization is compiled in but
52528      ** is not applicable to this transaction, call sqlite3JournalCreate()
52529      ** to make sure the journal file has actually been created, then call
52530      ** pager_incr_changecounter() to update the change-counter in indirect
52531      ** mode.
52532      **
52533      ** Otherwise, if the optimization is both enabled and applicable,
52534      ** then call pager_incr_changecounter() to update the change-counter
52535      ** in 'direct' mode. In this case the journal file will never be
52536      ** created for this transaction.
52537      */
52538  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52539      PgHdr *pPg;
52540      assert( isOpen(pPager->jfd)
52541           || pPager->journalMode==PAGER_JOURNALMODE_OFF
52542           || pPager->journalMode==PAGER_JOURNALMODE_WAL
52543      );
52544      if( !zMaster && isOpen(pPager->jfd)
52545       && pPager->journalOff==jrnlBufferSize(pPager)
52546       && pPager->dbSize>=pPager->dbOrigSize
52547       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
52548      ){
52549        /* Update the db file change counter via the direct-write method. The
52550        ** following call will modify the in-memory representation of page 1
52551        ** to include the updated change counter and then write page 1
52552        ** directly to the database file. Because of the atomic-write
52553        ** property of the host file-system, this is safe.
52554        */
52555        rc = pager_incr_changecounter(pPager, 1);
52556      }else{
52557        rc = sqlite3JournalCreate(pPager->jfd);
52558        if( rc==SQLITE_OK ){
52559          rc = pager_incr_changecounter(pPager, 0);
52560        }
52561      }
52562  #else
52563      rc = pager_incr_changecounter(pPager, 0);
52564  #endif
52565      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52566
52567      /* Write the master journal name into the journal file. If a master
52568      ** journal file name has already been written to the journal file,
52569      ** or if zMaster is NULL (no master journal), then this call is a no-op.
52570      */
52571      rc = writeMasterJournal(pPager, zMaster);
52572      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52573
52574      /* Sync the journal file and write all dirty pages to the database.
52575      ** If the atomic-update optimization is being used, this sync will not
52576      ** create the journal file or perform any real IO.
52577      **
52578      ** Because the change-counter page was just modified, unless the
52579      ** atomic-update optimization is used it is almost certain that the
52580      ** journal requires a sync here. However, in locking_mode=exclusive
52581      ** on a system under memory pressure it is just possible that this is
52582      ** not the case. In this case it is likely enough that the redundant
52583      ** xSync() call will be changed to a no-op by the OS anyhow.
52584      */
52585      rc = syncJournal(pPager, 0);
52586      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52587
52588      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
52589      if( rc!=SQLITE_OK ){
52590        assert( rc!=SQLITE_IOERR_BLOCKED );
52591        goto commit_phase_one_exit;
52592      }
52593      sqlite3PcacheCleanAll(pPager->pPCache);
52594
52595      /* If the file on disk is smaller than the database image, use
52596      ** pager_truncate to grow the file here. This can happen if the database
52597      ** image was extended as part of the current transaction and then the
52598      ** last page in the db image moved to the free-list. In this case the
52599      ** last page is never written out to disk, leaving the database file
52600      ** undersized. Fix this now if it is the case.  */
52601      if( pPager->dbSize>pPager->dbFileSize ){
52602        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
52603        assert( pPager->eState==PAGER_WRITER_DBMOD );
52604        rc = pager_truncate(pPager, nNew);
52605        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52606      }
52607
52608      /* Finally, sync the database file. */
52609      if( !noSync ){
52610        rc = sqlite3PagerSync(pPager, zMaster);
52611      }
52612      IOTRACE(("DBSYNC %p\n", pPager))
52613    }
52614  }
52615
52616commit_phase_one_exit:
52617  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
52618    pPager->eState = PAGER_WRITER_FINISHED;
52619  }
52620  return rc;
52621}
52622
52623
52624/*
52625** When this function is called, the database file has been completely
52626** updated to reflect the changes made by the current transaction and
52627** synced to disk. The journal file still exists in the file-system
52628** though, and if a failure occurs at this point it will eventually
52629** be used as a hot-journal and the current transaction rolled back.
52630**
52631** This function finalizes the journal file, either by deleting,
52632** truncating or partially zeroing it, so that it cannot be used
52633** for hot-journal rollback. Once this is done the transaction is
52634** irrevocably committed.
52635**
52636** If an error occurs, an IO error code is returned and the pager
52637** moves into the error state. Otherwise, SQLITE_OK is returned.
52638*/
52639SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
52640  int rc = SQLITE_OK;                  /* Return code */
52641
52642  /* This routine should not be called if a prior error has occurred.
52643  ** But if (due to a coding error elsewhere in the system) it does get
52644  ** called, just return the same error code without doing anything. */
52645  if( NEVER(pPager->errCode) ) return pPager->errCode;
52646
52647  assert( pPager->eState==PAGER_WRITER_LOCKED
52648       || pPager->eState==PAGER_WRITER_FINISHED
52649       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
52650  );
52651  assert( assert_pager_state(pPager) );
52652
52653  /* An optimization. If the database was not actually modified during
52654  ** this transaction, the pager is running in exclusive-mode and is
52655  ** using persistent journals, then this function is a no-op.
52656  **
52657  ** The start of the journal file currently contains a single journal
52658  ** header with the nRec field set to 0. If such a journal is used as
52659  ** a hot-journal during hot-journal rollback, 0 changes will be made
52660  ** to the database file. So there is no need to zero the journal
52661  ** header. Since the pager is in exclusive mode, there is no need
52662  ** to drop any locks either.
52663  */
52664  if( pPager->eState==PAGER_WRITER_LOCKED
52665   && pPager->exclusiveMode
52666   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
52667  ){
52668    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
52669    pPager->eState = PAGER_READER;
52670    return SQLITE_OK;
52671  }
52672
52673  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
52674  pPager->iDataVersion++;
52675  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
52676  return pager_error(pPager, rc);
52677}
52678
52679/*
52680** If a write transaction is open, then all changes made within the
52681** transaction are reverted and the current write-transaction is closed.
52682** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
52683** state if an error occurs.
52684**
52685** If the pager is already in PAGER_ERROR state when this function is called,
52686** it returns Pager.errCode immediately. No work is performed in this case.
52687**
52688** Otherwise, in rollback mode, this function performs two functions:
52689**
52690**   1) It rolls back the journal file, restoring all database file and
52691**      in-memory cache pages to the state they were in when the transaction
52692**      was opened, and
52693**
52694**   2) It finalizes the journal file, so that it is not used for hot
52695**      rollback at any point in the future.
52696**
52697** Finalization of the journal file (task 2) is only performed if the
52698** rollback is successful.
52699**
52700** In WAL mode, all cache-entries containing data modified within the
52701** current transaction are either expelled from the cache or reverted to
52702** their pre-transaction state by re-reading data from the database or
52703** WAL files. The WAL transaction is then closed.
52704*/
52705SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
52706  int rc = SQLITE_OK;                  /* Return code */
52707  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
52708
52709  /* PagerRollback() is a no-op if called in READER or OPEN state. If
52710  ** the pager is already in the ERROR state, the rollback is not
52711  ** attempted here. Instead, the error code is returned to the caller.
52712  */
52713  assert( assert_pager_state(pPager) );
52714  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
52715  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
52716
52717  if( pagerUseWal(pPager) ){
52718    int rc2;
52719    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
52720    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
52721    if( rc==SQLITE_OK ) rc = rc2;
52722  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
52723    int eState = pPager->eState;
52724    rc = pager_end_transaction(pPager, 0, 0);
52725    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
52726      /* This can happen using journal_mode=off. Move the pager to the error
52727      ** state to indicate that the contents of the cache may not be trusted.
52728      ** Any active readers will get SQLITE_ABORT.
52729      */
52730      pPager->errCode = SQLITE_ABORT;
52731      pPager->eState = PAGER_ERROR;
52732      return rc;
52733    }
52734  }else{
52735    rc = pager_playback(pPager, 0);
52736  }
52737
52738  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
52739  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
52740          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
52741          || rc==SQLITE_CANTOPEN
52742  );
52743
52744  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
52745  ** cache. So call pager_error() on the way out to make any error persistent.
52746  */
52747  return pager_error(pPager, rc);
52748}
52749
52750/*
52751** Return TRUE if the database file is opened read-only.  Return FALSE
52752** if the database is (in theory) writable.
52753*/
52754SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
52755  return pPager->readOnly;
52756}
52757
52758#ifdef SQLITE_DEBUG
52759/*
52760** Return the sum of the reference counts for all pages held by pPager.
52761*/
52762SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
52763  return sqlite3PcacheRefCount(pPager->pPCache);
52764}
52765#endif
52766
52767/*
52768** Return the approximate number of bytes of memory currently
52769** used by the pager and its associated cache.
52770*/
52771SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
52772  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
52773                                     + 5*sizeof(void*);
52774  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
52775           + sqlite3MallocSize(pPager)
52776           + pPager->pageSize;
52777}
52778
52779/*
52780** Return the number of references to the specified page.
52781*/
52782SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
52783  return sqlite3PcachePageRefcount(pPage);
52784}
52785
52786#ifdef SQLITE_TEST
52787/*
52788** This routine is used for testing and analysis only.
52789*/
52790SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
52791  static int a[11];
52792  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
52793  a[1] = sqlite3PcachePagecount(pPager->pPCache);
52794  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
52795  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
52796  a[4] = pPager->eState;
52797  a[5] = pPager->errCode;
52798  a[6] = pPager->aStat[PAGER_STAT_HIT];
52799  a[7] = pPager->aStat[PAGER_STAT_MISS];
52800  a[8] = 0;  /* Used to be pPager->nOvfl */
52801  a[9] = pPager->nRead;
52802  a[10] = pPager->aStat[PAGER_STAT_WRITE];
52803  return a;
52804}
52805#endif
52806
52807/*
52808** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
52809** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
52810** current cache hit or miss count, according to the value of eStat. If the
52811** reset parameter is non-zero, the cache hit or miss count is zeroed before
52812** returning.
52813*/
52814SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
52815
52816  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
52817       || eStat==SQLITE_DBSTATUS_CACHE_MISS
52818       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
52819  );
52820
52821  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
52822  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
52823  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
52824
52825  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
52826  if( reset ){
52827    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52828  }
52829}
52830
52831/*
52832** Return true if this is an in-memory or temp-file backed pager.
52833*/
52834SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
52835  return pPager->tempFile;
52836}
52837
52838/*
52839** Check that there are at least nSavepoint savepoints open. If there are
52840** currently less than nSavepoints open, then open one or more savepoints
52841** to make up the difference. If the number of savepoints is already
52842** equal to nSavepoint, then this function is a no-op.
52843**
52844** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
52845** occurs while opening the sub-journal file, then an IO error code is
52846** returned. Otherwise, SQLITE_OK.
52847*/
52848static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
52849  int rc = SQLITE_OK;                       /* Return code */
52850  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
52851  int ii;                                   /* Iterator variable */
52852  PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
52853
52854  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52855  assert( assert_pager_state(pPager) );
52856  assert( nSavepoint>nCurrent && pPager->useJournal );
52857
52858  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
52859  ** if the allocation fails. Otherwise, zero the new portion in case a
52860  ** malloc failure occurs while populating it in the for(...) loop below.
52861  */
52862  aNew = (PagerSavepoint *)sqlite3Realloc(
52863      pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
52864  );
52865  if( !aNew ){
52866    return SQLITE_NOMEM_BKPT;
52867  }
52868  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
52869  pPager->aSavepoint = aNew;
52870
52871  /* Populate the PagerSavepoint structures just allocated. */
52872  for(ii=nCurrent; ii<nSavepoint; ii++){
52873    aNew[ii].nOrig = pPager->dbSize;
52874    if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
52875      aNew[ii].iOffset = pPager->journalOff;
52876    }else{
52877      aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
52878    }
52879    aNew[ii].iSubRec = pPager->nSubRec;
52880    aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
52881    if( !aNew[ii].pInSavepoint ){
52882      return SQLITE_NOMEM_BKPT;
52883    }
52884    if( pagerUseWal(pPager) ){
52885      sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
52886    }
52887    pPager->nSavepoint = ii+1;
52888  }
52889  assert( pPager->nSavepoint==nSavepoint );
52890  assertTruncateConstraint(pPager);
52891  return rc;
52892}
52893SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
52894  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52895  assert( assert_pager_state(pPager) );
52896
52897  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
52898    return pagerOpenSavepoint(pPager, nSavepoint);
52899  }else{
52900    return SQLITE_OK;
52901  }
52902}
52903
52904
52905/*
52906** This function is called to rollback or release (commit) a savepoint.
52907** The savepoint to release or rollback need not be the most recently
52908** created savepoint.
52909**
52910** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
52911** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
52912** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
52913** that have occurred since the specified savepoint was created.
52914**
52915** The savepoint to rollback or release is identified by parameter
52916** iSavepoint. A value of 0 means to operate on the outermost savepoint
52917** (the first created). A value of (Pager.nSavepoint-1) means operate
52918** on the most recently created savepoint. If iSavepoint is greater than
52919** (Pager.nSavepoint-1), then this function is a no-op.
52920**
52921** If a negative value is passed to this function, then the current
52922** transaction is rolled back. This is different to calling
52923** sqlite3PagerRollback() because this function does not terminate
52924** the transaction or unlock the database, it just restores the
52925** contents of the database to its original state.
52926**
52927** In any case, all savepoints with an index greater than iSavepoint
52928** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
52929** then savepoint iSavepoint is also destroyed.
52930**
52931** This function may return SQLITE_NOMEM if a memory allocation fails,
52932** or an IO error code if an IO error occurs while rolling back a
52933** savepoint. If no errors occur, SQLITE_OK is returned.
52934*/
52935SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
52936  int rc = pPager->errCode;       /* Return code */
52937
52938  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52939  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
52940
52941  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
52942    int ii;            /* Iterator variable */
52943    int nNew;          /* Number of remaining savepoints after this op. */
52944
52945    /* Figure out how many savepoints will still be active after this
52946    ** operation. Store this value in nNew. Then free resources associated
52947    ** with any savepoints that are destroyed by this operation.
52948    */
52949    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
52950    for(ii=nNew; ii<pPager->nSavepoint; ii++){
52951      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
52952    }
52953    pPager->nSavepoint = nNew;
52954
52955    /* If this is a release of the outermost savepoint, truncate
52956    ** the sub-journal to zero bytes in size. */
52957    if( op==SAVEPOINT_RELEASE ){
52958      if( nNew==0 && isOpen(pPager->sjfd) ){
52959        /* Only truncate if it is an in-memory sub-journal. */
52960        if( sqlite3JournalIsInMemory(pPager->sjfd) ){
52961          rc = sqlite3OsTruncate(pPager->sjfd, 0);
52962          assert( rc==SQLITE_OK );
52963        }
52964        pPager->nSubRec = 0;
52965      }
52966    }
52967    /* Else this is a rollback operation, playback the specified savepoint.
52968    ** If this is a temp-file, it is possible that the journal file has
52969    ** not yet been opened. In this case there have been no changes to
52970    ** the database file, so the playback operation can be skipped.
52971    */
52972    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
52973      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
52974      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
52975      assert(rc!=SQLITE_DONE);
52976    }
52977  }
52978
52979  return rc;
52980}
52981
52982/*
52983** Return the full pathname of the database file.
52984**
52985** Except, if the pager is in-memory only, then return an empty string if
52986** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
52987** used to report the filename to the user, for compatibility with legacy
52988** behavior.  But when the Btree needs to know the filename for matching to
52989** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
52990** participate in shared-cache.
52991*/
52992SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
52993  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
52994}
52995
52996/*
52997** Return the VFS structure for the pager.
52998*/
52999SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
53000  return pPager->pVfs;
53001}
53002
53003/*
53004** Return the file handle for the database file associated
53005** with the pager.  This might return NULL if the file has
53006** not yet been opened.
53007*/
53008SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
53009  return pPager->fd;
53010}
53011
53012/*
53013** Return the file handle for the journal file (if it exists).
53014** This will be either the rollback journal or the WAL file.
53015*/
53016SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
53017#if SQLITE_OMIT_WAL
53018  return pPager->jfd;
53019#else
53020  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
53021#endif
53022}
53023
53024/*
53025** Return the full pathname of the journal file.
53026*/
53027SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
53028  return pPager->zJournal;
53029}
53030
53031#ifdef SQLITE_HAS_CODEC
53032/*
53033** Set or retrieve the codec for this pager
53034*/
53035SQLITE_PRIVATE void sqlite3PagerSetCodec(
53036  Pager *pPager,
53037  void *(*xCodec)(void*,void*,Pgno,int),
53038  void (*xCodecSizeChng)(void*,int,int),
53039  void (*xCodecFree)(void*),
53040  void *pCodec
53041){
53042  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
53043  pPager->xCodec = pPager->memDb ? 0 : xCodec;
53044  pPager->xCodecSizeChng = xCodecSizeChng;
53045  pPager->xCodecFree = xCodecFree;
53046  pPager->pCodec = pCodec;
53047  pagerReportSize(pPager);
53048}
53049SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
53050  return pPager->pCodec;
53051}
53052
53053/*
53054** This function is called by the wal module when writing page content
53055** into the log file.
53056**
53057** This function returns a pointer to a buffer containing the encrypted
53058** page content. If a malloc fails, this function may return NULL.
53059*/
53060SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
53061  void *aData = 0;
53062  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
53063  return aData;
53064}
53065
53066/*
53067** Return the current pager state
53068*/
53069SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
53070  return pPager->eState;
53071}
53072#endif /* SQLITE_HAS_CODEC */
53073
53074#ifndef SQLITE_OMIT_AUTOVACUUM
53075/*
53076** Move the page pPg to location pgno in the file.
53077**
53078** There must be no references to the page previously located at
53079** pgno (which we call pPgOld) though that page is allowed to be
53080** in cache.  If the page previously located at pgno is not already
53081** in the rollback journal, it is not put there by by this routine.
53082**
53083** References to the page pPg remain valid. Updating any
53084** meta-data associated with pPg (i.e. data stored in the nExtra bytes
53085** allocated along with the page) is the responsibility of the caller.
53086**
53087** A transaction must be active when this routine is called. It used to be
53088** required that a statement transaction was not active, but this restriction
53089** has been removed (CREATE INDEX needs to move a page when a statement
53090** transaction is active).
53091**
53092** If the fourth argument, isCommit, is non-zero, then this page is being
53093** moved as part of a database reorganization just before the transaction
53094** is being committed. In this case, it is guaranteed that the database page
53095** pPg refers to will not be written to again within this transaction.
53096**
53097** This function may return SQLITE_NOMEM or an IO error code if an error
53098** occurs. Otherwise, it returns SQLITE_OK.
53099*/
53100SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
53101  PgHdr *pPgOld;               /* The page being overwritten. */
53102  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
53103  int rc;                      /* Return code */
53104  Pgno origPgno;               /* The original page number */
53105
53106  assert( pPg->nRef>0 );
53107  assert( pPager->eState==PAGER_WRITER_CACHEMOD
53108       || pPager->eState==PAGER_WRITER_DBMOD
53109  );
53110  assert( assert_pager_state(pPager) );
53111
53112  /* In order to be able to rollback, an in-memory database must journal
53113  ** the page we are moving from.
53114  */
53115  assert( pPager->tempFile || !MEMDB );
53116  if( pPager->tempFile ){
53117    rc = sqlite3PagerWrite(pPg);
53118    if( rc ) return rc;
53119  }
53120
53121  /* If the page being moved is dirty and has not been saved by the latest
53122  ** savepoint, then save the current contents of the page into the
53123  ** sub-journal now. This is required to handle the following scenario:
53124  **
53125  **   BEGIN;
53126  **     <journal page X, then modify it in memory>
53127  **     SAVEPOINT one;
53128  **       <Move page X to location Y>
53129  **     ROLLBACK TO one;
53130  **
53131  ** If page X were not written to the sub-journal here, it would not
53132  ** be possible to restore its contents when the "ROLLBACK TO one"
53133  ** statement were is processed.
53134  **
53135  ** subjournalPage() may need to allocate space to store pPg->pgno into
53136  ** one or more savepoint bitvecs. This is the reason this function
53137  ** may return SQLITE_NOMEM.
53138  */
53139  if( (pPg->flags & PGHDR_DIRTY)!=0
53140   && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
53141  ){
53142    return rc;
53143  }
53144
53145  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
53146      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
53147  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
53148
53149  /* If the journal needs to be sync()ed before page pPg->pgno can
53150  ** be written to, store pPg->pgno in local variable needSyncPgno.
53151  **
53152  ** If the isCommit flag is set, there is no need to remember that
53153  ** the journal needs to be sync()ed before database page pPg->pgno
53154  ** can be written to. The caller has already promised not to write to it.
53155  */
53156  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
53157    needSyncPgno = pPg->pgno;
53158    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
53159            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
53160    assert( pPg->flags&PGHDR_DIRTY );
53161  }
53162
53163  /* If the cache contains a page with page-number pgno, remove it
53164  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
53165  ** page pgno before the 'move' operation, it needs to be retained
53166  ** for the page moved there.
53167  */
53168  pPg->flags &= ~PGHDR_NEED_SYNC;
53169  pPgOld = sqlite3PagerLookup(pPager, pgno);
53170  assert( !pPgOld || pPgOld->nRef==1 );
53171  if( pPgOld ){
53172    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
53173    if( pPager->tempFile ){
53174      /* Do not discard pages from an in-memory database since we might
53175      ** need to rollback later.  Just move the page out of the way. */
53176      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
53177    }else{
53178      sqlite3PcacheDrop(pPgOld);
53179    }
53180  }
53181
53182  origPgno = pPg->pgno;
53183  sqlite3PcacheMove(pPg, pgno);
53184  sqlite3PcacheMakeDirty(pPg);
53185
53186  /* For an in-memory database, make sure the original page continues
53187  ** to exist, in case the transaction needs to roll back.  Use pPgOld
53188  ** as the original page since it has already been allocated.
53189  */
53190  if( pPager->tempFile && pPgOld ){
53191    sqlite3PcacheMove(pPgOld, origPgno);
53192    sqlite3PagerUnrefNotNull(pPgOld);
53193  }
53194
53195  if( needSyncPgno ){
53196    /* If needSyncPgno is non-zero, then the journal file needs to be
53197    ** sync()ed before any data is written to database file page needSyncPgno.
53198    ** Currently, no such page exists in the page-cache and the
53199    ** "is journaled" bitvec flag has been set. This needs to be remedied by
53200    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
53201    ** flag.
53202    **
53203    ** If the attempt to load the page into the page-cache fails, (due
53204    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
53205    ** array. Otherwise, if the page is loaded and written again in
53206    ** this transaction, it may be written to the database file before
53207    ** it is synced into the journal file. This way, it may end up in
53208    ** the journal file twice, but that is not a problem.
53209    */
53210    PgHdr *pPgHdr;
53211    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
53212    if( rc!=SQLITE_OK ){
53213      if( needSyncPgno<=pPager->dbOrigSize ){
53214        assert( pPager->pTmpSpace!=0 );
53215        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
53216      }
53217      return rc;
53218    }
53219    pPgHdr->flags |= PGHDR_NEED_SYNC;
53220    sqlite3PcacheMakeDirty(pPgHdr);
53221    sqlite3PagerUnrefNotNull(pPgHdr);
53222  }
53223
53224  return SQLITE_OK;
53225}
53226#endif
53227
53228/*
53229** The page handle passed as the first argument refers to a dirty page
53230** with a page number other than iNew. This function changes the page's
53231** page number to iNew and sets the value of the PgHdr.flags field to
53232** the value passed as the third parameter.
53233*/
53234SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
53235  assert( pPg->pgno!=iNew );
53236  pPg->flags = flags;
53237  sqlite3PcacheMove(pPg, iNew);
53238}
53239
53240/*
53241** Return a pointer to the data for the specified page.
53242*/
53243SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
53244  assert( pPg->nRef>0 || pPg->pPager->memDb );
53245  return pPg->pData;
53246}
53247
53248/*
53249** Return a pointer to the Pager.nExtra bytes of "extra" space
53250** allocated along with the specified page.
53251*/
53252SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
53253  return pPg->pExtra;
53254}
53255
53256/*
53257** Get/set the locking-mode for this pager. Parameter eMode must be one
53258** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
53259** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
53260** the locking-mode is set to the value specified.
53261**
53262** The returned value is either PAGER_LOCKINGMODE_NORMAL or
53263** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
53264** locking-mode.
53265*/
53266SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
53267  assert( eMode==PAGER_LOCKINGMODE_QUERY
53268            || eMode==PAGER_LOCKINGMODE_NORMAL
53269            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
53270  assert( PAGER_LOCKINGMODE_QUERY<0 );
53271  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
53272  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
53273  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
53274    pPager->exclusiveMode = (u8)eMode;
53275  }
53276  return (int)pPager->exclusiveMode;
53277}
53278
53279/*
53280** Set the journal-mode for this pager. Parameter eMode must be one of:
53281**
53282**    PAGER_JOURNALMODE_DELETE
53283**    PAGER_JOURNALMODE_TRUNCATE
53284**    PAGER_JOURNALMODE_PERSIST
53285**    PAGER_JOURNALMODE_OFF
53286**    PAGER_JOURNALMODE_MEMORY
53287**    PAGER_JOURNALMODE_WAL
53288**
53289** The journalmode is set to the value specified if the change is allowed.
53290** The change may be disallowed for the following reasons:
53291**
53292**   *  An in-memory database can only have its journal_mode set to _OFF
53293**      or _MEMORY.
53294**
53295**   *  Temporary databases cannot have _WAL journalmode.
53296**
53297** The returned indicate the current (possibly updated) journal-mode.
53298*/
53299SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
53300  u8 eOld = pPager->journalMode;    /* Prior journalmode */
53301
53302#ifdef SQLITE_DEBUG
53303  /* The print_pager_state() routine is intended to be used by the debugger
53304  ** only.  We invoke it once here to suppress a compiler warning. */
53305  print_pager_state(pPager);
53306#endif
53307
53308
53309  /* The eMode parameter is always valid */
53310  assert(      eMode==PAGER_JOURNALMODE_DELETE
53311            || eMode==PAGER_JOURNALMODE_TRUNCATE
53312            || eMode==PAGER_JOURNALMODE_PERSIST
53313            || eMode==PAGER_JOURNALMODE_OFF
53314            || eMode==PAGER_JOURNALMODE_WAL
53315            || eMode==PAGER_JOURNALMODE_MEMORY );
53316
53317  /* This routine is only called from the OP_JournalMode opcode, and
53318  ** the logic there will never allow a temporary file to be changed
53319  ** to WAL mode.
53320  */
53321  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
53322
53323  /* Do allow the journalmode of an in-memory database to be set to
53324  ** anything other than MEMORY or OFF
53325  */
53326  if( MEMDB ){
53327    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
53328    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
53329      eMode = eOld;
53330    }
53331  }
53332
53333  if( eMode!=eOld ){
53334
53335    /* Change the journal mode. */
53336    assert( pPager->eState!=PAGER_ERROR );
53337    pPager->journalMode = (u8)eMode;
53338
53339    /* When transistioning from TRUNCATE or PERSIST to any other journal
53340    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
53341    ** delete the journal file.
53342    */
53343    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
53344    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
53345    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
53346    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
53347    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
53348    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
53349
53350    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
53351    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
53352
53353      /* In this case we would like to delete the journal file. If it is
53354      ** not possible, then that is not a problem. Deleting the journal file
53355      ** here is an optimization only.
53356      **
53357      ** Before deleting the journal file, obtain a RESERVED lock on the
53358      ** database file. This ensures that the journal file is not deleted
53359      ** while it is in use by some other client.
53360      */
53361      sqlite3OsClose(pPager->jfd);
53362      if( pPager->eLock>=RESERVED_LOCK ){
53363        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53364      }else{
53365        int rc = SQLITE_OK;
53366        int state = pPager->eState;
53367        assert( state==PAGER_OPEN || state==PAGER_READER );
53368        if( state==PAGER_OPEN ){
53369          rc = sqlite3PagerSharedLock(pPager);
53370        }
53371        if( pPager->eState==PAGER_READER ){
53372          assert( rc==SQLITE_OK );
53373          rc = pagerLockDb(pPager, RESERVED_LOCK);
53374        }
53375        if( rc==SQLITE_OK ){
53376          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53377        }
53378        if( rc==SQLITE_OK && state==PAGER_READER ){
53379          pagerUnlockDb(pPager, SHARED_LOCK);
53380        }else if( state==PAGER_OPEN ){
53381          pager_unlock(pPager);
53382        }
53383        assert( state==pPager->eState );
53384      }
53385    }else if( eMode==PAGER_JOURNALMODE_OFF ){
53386      sqlite3OsClose(pPager->jfd);
53387    }
53388  }
53389
53390  /* Return the new journal mode */
53391  return (int)pPager->journalMode;
53392}
53393
53394/*
53395** Return the current journal mode.
53396*/
53397SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
53398  return (int)pPager->journalMode;
53399}
53400
53401/*
53402** Return TRUE if the pager is in a state where it is OK to change the
53403** journalmode.  Journalmode changes can only happen when the database
53404** is unmodified.
53405*/
53406SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
53407  assert( assert_pager_state(pPager) );
53408  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
53409  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
53410  return 1;
53411}
53412
53413/*
53414** Get/set the size-limit used for persistent journal files.
53415**
53416** Setting the size limit to -1 means no limit is enforced.
53417** An attempt to set a limit smaller than -1 is a no-op.
53418*/
53419SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
53420  if( iLimit>=-1 ){
53421    pPager->journalSizeLimit = iLimit;
53422    sqlite3WalLimit(pPager->pWal, iLimit);
53423  }
53424  return pPager->journalSizeLimit;
53425}
53426
53427/*
53428** Return a pointer to the pPager->pBackup variable. The backup module
53429** in backup.c maintains the content of this variable. This module
53430** uses it opaquely as an argument to sqlite3BackupRestart() and
53431** sqlite3BackupUpdate() only.
53432*/
53433SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
53434  return &pPager->pBackup;
53435}
53436
53437#ifndef SQLITE_OMIT_VACUUM
53438/*
53439** Unless this is an in-memory or temporary database, clear the pager cache.
53440*/
53441SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
53442  assert( MEMDB==0 || pPager->tempFile );
53443  if( pPager->tempFile==0 ) pager_reset(pPager);
53444}
53445#endif
53446
53447
53448#ifndef SQLITE_OMIT_WAL
53449/*
53450** This function is called when the user invokes "PRAGMA wal_checkpoint",
53451** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
53452** or wal_blocking_checkpoint() API functions.
53453**
53454** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
53455*/
53456SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
53457  int rc = SQLITE_OK;
53458  if( pPager->pWal ){
53459    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
53460        (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
53461        pPager->pBusyHandlerArg,
53462        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
53463        pnLog, pnCkpt
53464    );
53465  }
53466  return rc;
53467}
53468
53469SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
53470  return sqlite3WalCallback(pPager->pWal);
53471}
53472
53473/*
53474** Return true if the underlying VFS for the given pager supports the
53475** primitives necessary for write-ahead logging.
53476*/
53477SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
53478  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
53479  if( pPager->noLock ) return 0;
53480  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
53481}
53482
53483/*
53484** Attempt to take an exclusive lock on the database file. If a PENDING lock
53485** is obtained instead, immediately release it.
53486*/
53487static int pagerExclusiveLock(Pager *pPager){
53488  int rc;                         /* Return code */
53489
53490  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53491  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53492  if( rc!=SQLITE_OK ){
53493    /* If the attempt to grab the exclusive lock failed, release the
53494    ** pending lock that may have been obtained instead.  */
53495    pagerUnlockDb(pPager, SHARED_LOCK);
53496  }
53497
53498  return rc;
53499}
53500
53501/*
53502** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
53503** exclusive-locking mode when this function is called, take an EXCLUSIVE
53504** lock on the database file and use heap-memory to store the wal-index
53505** in. Otherwise, use the normal shared-memory.
53506*/
53507static int pagerOpenWal(Pager *pPager){
53508  int rc = SQLITE_OK;
53509
53510  assert( pPager->pWal==0 && pPager->tempFile==0 );
53511  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53512
53513  /* If the pager is already in exclusive-mode, the WAL module will use
53514  ** heap-memory for the wal-index instead of the VFS shared-memory
53515  ** implementation. Take the exclusive lock now, before opening the WAL
53516  ** file, to make sure this is safe.
53517  */
53518  if( pPager->exclusiveMode ){
53519    rc = pagerExclusiveLock(pPager);
53520  }
53521
53522  /* Open the connection to the log file. If this operation fails,
53523  ** (e.g. due to malloc() failure), return an error code.
53524  */
53525  if( rc==SQLITE_OK ){
53526    rc = sqlite3WalOpen(pPager->pVfs,
53527        pPager->fd, pPager->zWal, pPager->exclusiveMode,
53528        pPager->journalSizeLimit, &pPager->pWal
53529    );
53530  }
53531  pagerFixMaplimit(pPager);
53532
53533  return rc;
53534}
53535
53536
53537/*
53538** The caller must be holding a SHARED lock on the database file to call
53539** this function.
53540**
53541** If the pager passed as the first argument is open on a real database
53542** file (not a temp file or an in-memory database), and the WAL file
53543** is not already open, make an attempt to open it now. If successful,
53544** return SQLITE_OK. If an error occurs or the VFS used by the pager does
53545** not support the xShmXXX() methods, return an error code. *pbOpen is
53546** not modified in either case.
53547**
53548** If the pager is open on a temp-file (or in-memory database), or if
53549** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
53550** without doing anything.
53551*/
53552SQLITE_PRIVATE int sqlite3PagerOpenWal(
53553  Pager *pPager,                  /* Pager object */
53554  int *pbOpen                     /* OUT: Set to true if call is a no-op */
53555){
53556  int rc = SQLITE_OK;             /* Return code */
53557
53558  assert( assert_pager_state(pPager) );
53559  assert( pPager->eState==PAGER_OPEN   || pbOpen );
53560  assert( pPager->eState==PAGER_READER || !pbOpen );
53561  assert( pbOpen==0 || *pbOpen==0 );
53562  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
53563
53564  if( !pPager->tempFile && !pPager->pWal ){
53565    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
53566
53567    /* Close any rollback journal previously open */
53568    sqlite3OsClose(pPager->jfd);
53569
53570    rc = pagerOpenWal(pPager);
53571    if( rc==SQLITE_OK ){
53572      pPager->journalMode = PAGER_JOURNALMODE_WAL;
53573      pPager->eState = PAGER_OPEN;
53574    }
53575  }else{
53576    *pbOpen = 1;
53577  }
53578
53579  return rc;
53580}
53581
53582/*
53583** This function is called to close the connection to the log file prior
53584** to switching from WAL to rollback mode.
53585**
53586** Before closing the log file, this function attempts to take an
53587** EXCLUSIVE lock on the database file. If this cannot be obtained, an
53588** error (SQLITE_BUSY) is returned and the log connection is not closed.
53589** If successful, the EXCLUSIVE lock is not released before returning.
53590*/
53591SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
53592  int rc = SQLITE_OK;
53593
53594  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
53595
53596  /* If the log file is not already open, but does exist in the file-system,
53597  ** it may need to be checkpointed before the connection can switch to
53598  ** rollback mode. Open it now so this can happen.
53599  */
53600  if( !pPager->pWal ){
53601    int logexists = 0;
53602    rc = pagerLockDb(pPager, SHARED_LOCK);
53603    if( rc==SQLITE_OK ){
53604      rc = sqlite3OsAccess(
53605          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
53606      );
53607    }
53608    if( rc==SQLITE_OK && logexists ){
53609      rc = pagerOpenWal(pPager);
53610    }
53611  }
53612
53613  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
53614  ** the database file, the log and log-summary files will be deleted.
53615  */
53616  if( rc==SQLITE_OK && pPager->pWal ){
53617    rc = pagerExclusiveLock(pPager);
53618    if( rc==SQLITE_OK ){
53619      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53620                           pPager->pageSize, (u8*)pPager->pTmpSpace);
53621      pPager->pWal = 0;
53622      pagerFixMaplimit(pPager);
53623      if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53624    }
53625  }
53626  return rc;
53627}
53628
53629#ifdef SQLITE_ENABLE_SNAPSHOT
53630/*
53631** If this is a WAL database, obtain a snapshot handle for the snapshot
53632** currently open. Otherwise, return an error.
53633*/
53634SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
53635  int rc = SQLITE_ERROR;
53636  if( pPager->pWal ){
53637    rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
53638  }
53639  return rc;
53640}
53641
53642/*
53643** If this is a WAL database, store a pointer to pSnapshot. Next time a
53644** read transaction is opened, attempt to read from the snapshot it
53645** identifies. If this is not a WAL database, return an error.
53646*/
53647SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
53648  int rc = SQLITE_OK;
53649  if( pPager->pWal ){
53650    sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
53651  }else{
53652    rc = SQLITE_ERROR;
53653  }
53654  return rc;
53655}
53656#endif /* SQLITE_ENABLE_SNAPSHOT */
53657#endif /* !SQLITE_OMIT_WAL */
53658
53659#ifdef SQLITE_ENABLE_ZIPVFS
53660/*
53661** A read-lock must be held on the pager when this function is called. If
53662** the pager is in WAL mode and the WAL file currently contains one or more
53663** frames, return the size in bytes of the page images stored within the
53664** WAL frames. Otherwise, if this is not a WAL database or the WAL file
53665** is empty, return 0.
53666*/
53667SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
53668  assert( pPager->eState>=PAGER_READER );
53669  return sqlite3WalFramesize(pPager->pWal);
53670}
53671#endif
53672
53673#endif /* SQLITE_OMIT_DISKIO */
53674
53675/************** End of pager.c ***********************************************/
53676/************** Begin file wal.c *********************************************/
53677/*
53678** 2010 February 1
53679**
53680** The author disclaims copyright to this source code.  In place of
53681** a legal notice, here is a blessing:
53682**
53683**    May you do good and not evil.
53684**    May you find forgiveness for yourself and forgive others.
53685**    May you share freely, never taking more than you give.
53686**
53687*************************************************************************
53688**
53689** This file contains the implementation of a write-ahead log (WAL) used in
53690** "journal_mode=WAL" mode.
53691**
53692** WRITE-AHEAD LOG (WAL) FILE FORMAT
53693**
53694** A WAL file consists of a header followed by zero or more "frames".
53695** Each frame records the revised content of a single page from the
53696** database file.  All changes to the database are recorded by writing
53697** frames into the WAL.  Transactions commit when a frame is written that
53698** contains a commit marker.  A single WAL can and usually does record
53699** multiple transactions.  Periodically, the content of the WAL is
53700** transferred back into the database file in an operation called a
53701** "checkpoint".
53702**
53703** A single WAL file can be used multiple times.  In other words, the
53704** WAL can fill up with frames and then be checkpointed and then new
53705** frames can overwrite the old ones.  A WAL always grows from beginning
53706** toward the end.  Checksums and counters attached to each frame are
53707** used to determine which frames within the WAL are valid and which
53708** are leftovers from prior checkpoints.
53709**
53710** The WAL header is 32 bytes in size and consists of the following eight
53711** big-endian 32-bit unsigned integer values:
53712**
53713**     0: Magic number.  0x377f0682 or 0x377f0683
53714**     4: File format version.  Currently 3007000
53715**     8: Database page size.  Example: 1024
53716**    12: Checkpoint sequence number
53717**    16: Salt-1, random integer incremented with each checkpoint
53718**    20: Salt-2, a different random integer changing with each ckpt
53719**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
53720**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
53721**
53722** Immediately following the wal-header are zero or more frames. Each
53723** frame consists of a 24-byte frame-header followed by a <page-size> bytes
53724** of page data. The frame-header is six big-endian 32-bit unsigned
53725** integer values, as follows:
53726**
53727**     0: Page number.
53728**     4: For commit records, the size of the database image in pages
53729**        after the commit. For all other records, zero.
53730**     8: Salt-1 (copied from the header)
53731**    12: Salt-2 (copied from the header)
53732**    16: Checksum-1.
53733**    20: Checksum-2.
53734**
53735** A frame is considered valid if and only if the following conditions are
53736** true:
53737**
53738**    (1) The salt-1 and salt-2 values in the frame-header match
53739**        salt values in the wal-header
53740**
53741**    (2) The checksum values in the final 8 bytes of the frame-header
53742**        exactly match the checksum computed consecutively on the
53743**        WAL header and the first 8 bytes and the content of all frames
53744**        up to and including the current frame.
53745**
53746** The checksum is computed using 32-bit big-endian integers if the
53747** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
53748** is computed using little-endian if the magic number is 0x377f0682.
53749** The checksum values are always stored in the frame header in a
53750** big-endian format regardless of which byte order is used to compute
53751** the checksum.  The checksum is computed by interpreting the input as
53752** an even number of unsigned 32-bit integers: x[0] through x[N].  The
53753** algorithm used for the checksum is as follows:
53754**
53755**   for i from 0 to n-1 step 2:
53756**     s0 += x[i] + s1;
53757**     s1 += x[i+1] + s0;
53758**   endfor
53759**
53760** Note that s0 and s1 are both weighted checksums using fibonacci weights
53761** in reverse order (the largest fibonacci weight occurs on the first element
53762** of the sequence being summed.)  The s1 value spans all 32-bit
53763** terms of the sequence whereas s0 omits the final term.
53764**
53765** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
53766** WAL is transferred into the database, then the database is VFS.xSync-ed.
53767** The VFS.xSync operations serve as write barriers - all writes launched
53768** before the xSync must complete before any write that launches after the
53769** xSync begins.
53770**
53771** After each checkpoint, the salt-1 value is incremented and the salt-2
53772** value is randomized.  This prevents old and new frames in the WAL from
53773** being considered valid at the same time and being checkpointing together
53774** following a crash.
53775**
53776** READER ALGORITHM
53777**
53778** To read a page from the database (call it page number P), a reader
53779** first checks the WAL to see if it contains page P.  If so, then the
53780** last valid instance of page P that is a followed by a commit frame
53781** or is a commit frame itself becomes the value read.  If the WAL
53782** contains no copies of page P that are valid and which are a commit
53783** frame or are followed by a commit frame, then page P is read from
53784** the database file.
53785**
53786** To start a read transaction, the reader records the index of the last
53787** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
53788** for all subsequent read operations.  New transactions can be appended
53789** to the WAL, but as long as the reader uses its original mxFrame value
53790** and ignores the newly appended content, it will see a consistent snapshot
53791** of the database from a single point in time.  This technique allows
53792** multiple concurrent readers to view different versions of the database
53793** content simultaneously.
53794**
53795** The reader algorithm in the previous paragraphs works correctly, but
53796** because frames for page P can appear anywhere within the WAL, the
53797** reader has to scan the entire WAL looking for page P frames.  If the
53798** WAL is large (multiple megabytes is typical) that scan can be slow,
53799** and read performance suffers.  To overcome this problem, a separate
53800** data structure called the wal-index is maintained to expedite the
53801** search for frames of a particular page.
53802**
53803** WAL-INDEX FORMAT
53804**
53805** Conceptually, the wal-index is shared memory, though VFS implementations
53806** might choose to implement the wal-index using a mmapped file.  Because
53807** the wal-index is shared memory, SQLite does not support journal_mode=WAL
53808** on a network filesystem.  All users of the database must be able to
53809** share memory.
53810**
53811** The wal-index is transient.  After a crash, the wal-index can (and should
53812** be) reconstructed from the original WAL file.  In fact, the VFS is required
53813** to either truncate or zero the header of the wal-index when the last
53814** connection to it closes.  Because the wal-index is transient, it can
53815** use an architecture-specific format; it does not have to be cross-platform.
53816** Hence, unlike the database and WAL file formats which store all values
53817** as big endian, the wal-index can store multi-byte values in the native
53818** byte order of the host computer.
53819**
53820** The purpose of the wal-index is to answer this question quickly:  Given
53821** a page number P and a maximum frame index M, return the index of the
53822** last frame in the wal before frame M for page P in the WAL, or return
53823** NULL if there are no frames for page P in the WAL prior to M.
53824**
53825** The wal-index consists of a header region, followed by an one or
53826** more index blocks.
53827**
53828** The wal-index header contains the total number of frames within the WAL
53829** in the mxFrame field.
53830**
53831** Each index block except for the first contains information on
53832** HASHTABLE_NPAGE frames. The first index block contains information on
53833** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
53834** HASHTABLE_NPAGE are selected so that together the wal-index header and
53835** first index block are the same size as all other index blocks in the
53836** wal-index.
53837**
53838** Each index block contains two sections, a page-mapping that contains the
53839** database page number associated with each wal frame, and a hash-table
53840** that allows readers to query an index block for a specific page number.
53841** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
53842** for the first index block) 32-bit page numbers. The first entry in the
53843** first index-block contains the database page number corresponding to the
53844** first frame in the WAL file. The first entry in the second index block
53845** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
53846** the log, and so on.
53847**
53848** The last index block in a wal-index usually contains less than the full
53849** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
53850** depending on the contents of the WAL file. This does not change the
53851** allocated size of the page-mapping array - the page-mapping array merely
53852** contains unused entries.
53853**
53854** Even without using the hash table, the last frame for page P
53855** can be found by scanning the page-mapping sections of each index block
53856** starting with the last index block and moving toward the first, and
53857** within each index block, starting at the end and moving toward the
53858** beginning.  The first entry that equals P corresponds to the frame
53859** holding the content for that page.
53860**
53861** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
53862** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
53863** hash table for each page number in the mapping section, so the hash
53864** table is never more than half full.  The expected number of collisions
53865** prior to finding a match is 1.  Each entry of the hash table is an
53866** 1-based index of an entry in the mapping section of the same
53867** index block.   Let K be the 1-based index of the largest entry in
53868** the mapping section.  (For index blocks other than the last, K will
53869** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
53870** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
53871** contain a value of 0.
53872**
53873** To look for page P in the hash table, first compute a hash iKey on
53874** P as follows:
53875**
53876**      iKey = (P * 383) % HASHTABLE_NSLOT
53877**
53878** Then start scanning entries of the hash table, starting with iKey
53879** (wrapping around to the beginning when the end of the hash table is
53880** reached) until an unused hash slot is found. Let the first unused slot
53881** be at index iUnused.  (iUnused might be less than iKey if there was
53882** wrap-around.) Because the hash table is never more than half full,
53883** the search is guaranteed to eventually hit an unused entry.  Let
53884** iMax be the value between iKey and iUnused, closest to iUnused,
53885** where aHash[iMax]==P.  If there is no iMax entry (if there exists
53886** no hash slot such that aHash[i]==p) then page P is not in the
53887** current index block.  Otherwise the iMax-th mapping entry of the
53888** current index block corresponds to the last entry that references
53889** page P.
53890**
53891** A hash search begins with the last index block and moves toward the
53892** first index block, looking for entries corresponding to page P.  On
53893** average, only two or three slots in each index block need to be
53894** examined in order to either find the last entry for page P, or to
53895** establish that no such entry exists in the block.  Each index block
53896** holds over 4000 entries.  So two or three index blocks are sufficient
53897** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
53898** comparisons (on average) suffice to either locate a frame in the
53899** WAL or to establish that the frame does not exist in the WAL.  This
53900** is much faster than scanning the entire 10MB WAL.
53901**
53902** Note that entries are added in order of increasing K.  Hence, one
53903** reader might be using some value K0 and a second reader that started
53904** at a later time (after additional transactions were added to the WAL
53905** and to the wal-index) might be using a different value K1, where K1>K0.
53906** Both readers can use the same hash table and mapping section to get
53907** the correct result.  There may be entries in the hash table with
53908** K>K0 but to the first reader, those entries will appear to be unused
53909** slots in the hash table and so the first reader will get an answer as
53910** if no values greater than K0 had ever been inserted into the hash table
53911** in the first place - which is what reader one wants.  Meanwhile, the
53912** second reader using K1 will see additional values that were inserted
53913** later, which is exactly what reader two wants.
53914**
53915** When a rollback occurs, the value of K is decreased. Hash table entries
53916** that correspond to frames greater than the new K value are removed
53917** from the hash table at this point.
53918*/
53919#ifndef SQLITE_OMIT_WAL
53920
53921/* #include "wal.h" */
53922
53923/*
53924** Trace output macros
53925*/
53926#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53927SQLITE_PRIVATE int sqlite3WalTrace = 0;
53928# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
53929#else
53930# define WALTRACE(X)
53931#endif
53932
53933/*
53934** The maximum (and only) versions of the wal and wal-index formats
53935** that may be interpreted by this version of SQLite.
53936**
53937** If a client begins recovering a WAL file and finds that (a) the checksum
53938** values in the wal-header are correct and (b) the version field is not
53939** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
53940**
53941** Similarly, if a client successfully reads a wal-index header (i.e. the
53942** checksum test is successful) and finds that the version field is not
53943** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
53944** returns SQLITE_CANTOPEN.
53945*/
53946#define WAL_MAX_VERSION      3007000
53947#define WALINDEX_MAX_VERSION 3007000
53948
53949/*
53950** Indices of various locking bytes.   WAL_NREADER is the number
53951** of available reader locks and should be at least 3.  The default
53952** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
53953*/
53954#define WAL_WRITE_LOCK         0
53955#define WAL_ALL_BUT_WRITE      1
53956#define WAL_CKPT_LOCK          1
53957#define WAL_RECOVER_LOCK       2
53958#define WAL_READ_LOCK(I)       (3+(I))
53959#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
53960
53961
53962/* Object declarations */
53963typedef struct WalIndexHdr WalIndexHdr;
53964typedef struct WalIterator WalIterator;
53965typedef struct WalCkptInfo WalCkptInfo;
53966
53967
53968/*
53969** The following object holds a copy of the wal-index header content.
53970**
53971** The actual header in the wal-index consists of two copies of this
53972** object followed by one instance of the WalCkptInfo object.
53973** For all versions of SQLite through 3.10.0 and probably beyond,
53974** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
53975** the total header size is 136 bytes.
53976**
53977** The szPage value can be any power of 2 between 512 and 32768, inclusive.
53978** Or it can be 1 to represent a 65536-byte page.  The latter case was
53979** added in 3.7.1 when support for 64K pages was added.
53980*/
53981struct WalIndexHdr {
53982  u32 iVersion;                   /* Wal-index version */
53983  u32 unused;                     /* Unused (padding) field */
53984  u32 iChange;                    /* Counter incremented each transaction */
53985  u8 isInit;                      /* 1 when initialized */
53986  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
53987  u16 szPage;                     /* Database page size in bytes. 1==64K */
53988  u32 mxFrame;                    /* Index of last valid frame in the WAL */
53989  u32 nPage;                      /* Size of database in pages */
53990  u32 aFrameCksum[2];             /* Checksum of last frame in log */
53991  u32 aSalt[2];                   /* Two salt values copied from WAL header */
53992  u32 aCksum[2];                  /* Checksum over all prior fields */
53993};
53994
53995/*
53996** A copy of the following object occurs in the wal-index immediately
53997** following the second copy of the WalIndexHdr.  This object stores
53998** information used by checkpoint.
53999**
54000** nBackfill is the number of frames in the WAL that have been written
54001** back into the database. (We call the act of moving content from WAL to
54002** database "backfilling".)  The nBackfill number is never greater than
54003** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
54004** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
54005** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
54006** mxFrame back to zero when the WAL is reset.
54007**
54008** nBackfillAttempted is the largest value of nBackfill that a checkpoint
54009** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
54010** the nBackfillAttempted is set before any backfilling is done and the
54011** nBackfill is only set after all backfilling completes.  So if a checkpoint
54012** crashes, nBackfillAttempted might be larger than nBackfill.  The
54013** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
54014**
54015** The aLock[] field is a set of bytes used for locking.  These bytes should
54016** never be read or written.
54017**
54018** There is one entry in aReadMark[] for each reader lock.  If a reader
54019** holds read-lock K, then the value in aReadMark[K] is no greater than
54020** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
54021** for any aReadMark[] means that entry is unused.  aReadMark[0] is
54022** a special case; its value is never used and it exists as a place-holder
54023** to avoid having to offset aReadMark[] indexs by one.  Readers holding
54024** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
54025** directly from the database.
54026**
54027** The value of aReadMark[K] may only be changed by a thread that
54028** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
54029** aReadMark[K] cannot changed while there is a reader is using that mark
54030** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
54031**
54032** The checkpointer may only transfer frames from WAL to database where
54033** the frame numbers are less than or equal to every aReadMark[] that is
54034** in use (that is, every aReadMark[j] for which there is a corresponding
54035** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
54036** largest value and will increase an unused aReadMark[] to mxFrame if there
54037** is not already an aReadMark[] equal to mxFrame.  The exception to the
54038** previous sentence is when nBackfill equals mxFrame (meaning that everything
54039** in the WAL has been backfilled into the database) then new readers
54040** will choose aReadMark[0] which has value 0 and hence such reader will
54041** get all their all content directly from the database file and ignore
54042** the WAL.
54043**
54044** Writers normally append new frames to the end of the WAL.  However,
54045** if nBackfill equals mxFrame (meaning that all WAL content has been
54046** written back into the database) and if no readers are using the WAL
54047** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
54048** the writer will first "reset" the WAL back to the beginning and start
54049** writing new content beginning at frame 1.
54050**
54051** We assume that 32-bit loads are atomic and so no locks are needed in
54052** order to read from any aReadMark[] entries.
54053*/
54054struct WalCkptInfo {
54055  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
54056  u32 aReadMark[WAL_NREADER];     /* Reader marks */
54057  u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
54058  u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
54059  u32 notUsed0;                   /* Available for future enhancements */
54060};
54061#define READMARK_NOT_USED  0xffffffff
54062
54063
54064/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
54065** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
54066** only support mandatory file-locks, we do not read or write data
54067** from the region of the file on which locks are applied.
54068*/
54069#define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
54070#define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
54071
54072/* Size of header before each frame in wal */
54073#define WAL_FRAME_HDRSIZE 24
54074
54075/* Size of write ahead log header, including checksum. */
54076/* #define WAL_HDRSIZE 24 */
54077#define WAL_HDRSIZE 32
54078
54079/* WAL magic value. Either this value, or the same value with the least
54080** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
54081** big-endian format in the first 4 bytes of a WAL file.
54082**
54083** If the LSB is set, then the checksums for each frame within the WAL
54084** file are calculated by treating all data as an array of 32-bit
54085** big-endian words. Otherwise, they are calculated by interpreting
54086** all data as 32-bit little-endian words.
54087*/
54088#define WAL_MAGIC 0x377f0682
54089
54090/*
54091** Return the offset of frame iFrame in the write-ahead log file,
54092** assuming a database page size of szPage bytes. The offset returned
54093** is to the start of the write-ahead log frame-header.
54094*/
54095#define walFrameOffset(iFrame, szPage) (                               \
54096  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
54097)
54098
54099/*
54100** An open write-ahead log file is represented by an instance of the
54101** following object.
54102*/
54103struct Wal {
54104  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
54105  sqlite3_file *pDbFd;       /* File handle for the database file */
54106  sqlite3_file *pWalFd;      /* File handle for WAL file */
54107  u32 iCallback;             /* Value to pass to log callback (or 0) */
54108  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
54109  int nWiData;               /* Size of array apWiData */
54110  int szFirstBlock;          /* Size of first block written to WAL file */
54111  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
54112  u32 szPage;                /* Database page size */
54113  i16 readLock;              /* Which read lock is being held.  -1 for none */
54114  u8 syncFlags;              /* Flags to use to sync header writes */
54115  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
54116  u8 writeLock;              /* True if in a write transaction */
54117  u8 ckptLock;               /* True if holding a checkpoint lock */
54118  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
54119  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
54120  u8 syncHeader;             /* Fsync the WAL header if true */
54121  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
54122  WalIndexHdr hdr;           /* Wal-index header for current transaction */
54123  u32 minFrame;              /* Ignore wal frames before this one */
54124  u32 iReCksum;              /* On commit, recalculate checksums from here */
54125  const char *zWalName;      /* Name of WAL file */
54126  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
54127#ifdef SQLITE_DEBUG
54128  u8 lockError;              /* True if a locking error has occurred */
54129#endif
54130#ifdef SQLITE_ENABLE_SNAPSHOT
54131  WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
54132#endif
54133};
54134
54135/*
54136** Candidate values for Wal.exclusiveMode.
54137*/
54138#define WAL_NORMAL_MODE     0
54139#define WAL_EXCLUSIVE_MODE  1
54140#define WAL_HEAPMEMORY_MODE 2
54141
54142/*
54143** Possible values for WAL.readOnly
54144*/
54145#define WAL_RDWR        0    /* Normal read/write connection */
54146#define WAL_RDONLY      1    /* The WAL file is readonly */
54147#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
54148
54149/*
54150** Each page of the wal-index mapping contains a hash-table made up of
54151** an array of HASHTABLE_NSLOT elements of the following type.
54152*/
54153typedef u16 ht_slot;
54154
54155/*
54156** This structure is used to implement an iterator that loops through
54157** all frames in the WAL in database page order. Where two or more frames
54158** correspond to the same database page, the iterator visits only the
54159** frame most recently written to the WAL (in other words, the frame with
54160** the largest index).
54161**
54162** The internals of this structure are only accessed by:
54163**
54164**   walIteratorInit() - Create a new iterator,
54165**   walIteratorNext() - Step an iterator,
54166**   walIteratorFree() - Free an iterator.
54167**
54168** This functionality is used by the checkpoint code (see walCheckpoint()).
54169*/
54170struct WalIterator {
54171  int iPrior;                     /* Last result returned from the iterator */
54172  int nSegment;                   /* Number of entries in aSegment[] */
54173  struct WalSegment {
54174    int iNext;                    /* Next slot in aIndex[] not yet returned */
54175    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
54176    u32 *aPgno;                   /* Array of page numbers. */
54177    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
54178    int iZero;                    /* Frame number associated with aPgno[0] */
54179  } aSegment[1];                  /* One for every 32KB page in the wal-index */
54180};
54181
54182/*
54183** Define the parameters of the hash tables in the wal-index file. There
54184** is a hash-table following every HASHTABLE_NPAGE page numbers in the
54185** wal-index.
54186**
54187** Changing any of these constants will alter the wal-index format and
54188** create incompatibilities.
54189*/
54190#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
54191#define HASHTABLE_HASH_1     383                  /* Should be prime */
54192#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
54193
54194/*
54195** The block of page numbers associated with the first hash-table in a
54196** wal-index is smaller than usual. This is so that there is a complete
54197** hash-table on each aligned 32KB page of the wal-index.
54198*/
54199#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
54200
54201/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
54202#define WALINDEX_PGSZ   (                                         \
54203    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
54204)
54205
54206/*
54207** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
54208** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
54209** numbered from zero.
54210**
54211** If this call is successful, *ppPage is set to point to the wal-index
54212** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
54213** then an SQLite error code is returned and *ppPage is set to 0.
54214*/
54215static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
54216  int rc = SQLITE_OK;
54217
54218  /* Enlarge the pWal->apWiData[] array if required */
54219  if( pWal->nWiData<=iPage ){
54220    int nByte = sizeof(u32*)*(iPage+1);
54221    volatile u32 **apNew;
54222    apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
54223    if( !apNew ){
54224      *ppPage = 0;
54225      return SQLITE_NOMEM_BKPT;
54226    }
54227    memset((void*)&apNew[pWal->nWiData], 0,
54228           sizeof(u32*)*(iPage+1-pWal->nWiData));
54229    pWal->apWiData = apNew;
54230    pWal->nWiData = iPage+1;
54231  }
54232
54233  /* Request a pointer to the required page from the VFS */
54234  if( pWal->apWiData[iPage]==0 ){
54235    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54236      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
54237      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
54238    }else{
54239      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
54240          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
54241      );
54242      if( rc==SQLITE_READONLY ){
54243        pWal->readOnly |= WAL_SHM_RDONLY;
54244        rc = SQLITE_OK;
54245      }
54246    }
54247  }
54248
54249  *ppPage = pWal->apWiData[iPage];
54250  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
54251  return rc;
54252}
54253
54254/*
54255** Return a pointer to the WalCkptInfo structure in the wal-index.
54256*/
54257static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
54258  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54259  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
54260}
54261
54262/*
54263** Return a pointer to the WalIndexHdr structure in the wal-index.
54264*/
54265static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
54266  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54267  return (volatile WalIndexHdr*)pWal->apWiData[0];
54268}
54269
54270/*
54271** The argument to this macro must be of type u32. On a little-endian
54272** architecture, it returns the u32 value that results from interpreting
54273** the 4 bytes as a big-endian value. On a big-endian architecture, it
54274** returns the value that would be produced by interpreting the 4 bytes
54275** of the input value as a little-endian integer.
54276*/
54277#define BYTESWAP32(x) ( \
54278    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
54279  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
54280)
54281
54282/*
54283** Generate or extend an 8 byte checksum based on the data in
54284** array aByte[] and the initial values of aIn[0] and aIn[1] (or
54285** initial values of 0 and 0 if aIn==NULL).
54286**
54287** The checksum is written back into aOut[] before returning.
54288**
54289** nByte must be a positive multiple of 8.
54290*/
54291static void walChecksumBytes(
54292  int nativeCksum, /* True for native byte-order, false for non-native */
54293  u8 *a,           /* Content to be checksummed */
54294  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
54295  const u32 *aIn,  /* Initial checksum value input */
54296  u32 *aOut        /* OUT: Final checksum value output */
54297){
54298  u32 s1, s2;
54299  u32 *aData = (u32 *)a;
54300  u32 *aEnd = (u32 *)&a[nByte];
54301
54302  if( aIn ){
54303    s1 = aIn[0];
54304    s2 = aIn[1];
54305  }else{
54306    s1 = s2 = 0;
54307  }
54308
54309  assert( nByte>=8 );
54310  assert( (nByte&0x00000007)==0 );
54311
54312  if( nativeCksum ){
54313    do {
54314      s1 += *aData++ + s2;
54315      s2 += *aData++ + s1;
54316    }while( aData<aEnd );
54317  }else{
54318    do {
54319      s1 += BYTESWAP32(aData[0]) + s2;
54320      s2 += BYTESWAP32(aData[1]) + s1;
54321      aData += 2;
54322    }while( aData<aEnd );
54323  }
54324
54325  aOut[0] = s1;
54326  aOut[1] = s2;
54327}
54328
54329static void walShmBarrier(Wal *pWal){
54330  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
54331    sqlite3OsShmBarrier(pWal->pDbFd);
54332  }
54333}
54334
54335/*
54336** Write the header information in pWal->hdr into the wal-index.
54337**
54338** The checksum on pWal->hdr is updated before it is written.
54339*/
54340static void walIndexWriteHdr(Wal *pWal){
54341  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
54342  const int nCksum = offsetof(WalIndexHdr, aCksum);
54343
54344  assert( pWal->writeLock );
54345  pWal->hdr.isInit = 1;
54346  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
54347  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
54348  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54349  walShmBarrier(pWal);
54350  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54351}
54352
54353/*
54354** This function encodes a single frame header and writes it to a buffer
54355** supplied by the caller. A frame-header is made up of a series of
54356** 4-byte big-endian integers, as follows:
54357**
54358**     0: Page number.
54359**     4: For commit records, the size of the database image in pages
54360**        after the commit. For all other records, zero.
54361**     8: Salt-1 (copied from the wal-header)
54362**    12: Salt-2 (copied from the wal-header)
54363**    16: Checksum-1.
54364**    20: Checksum-2.
54365*/
54366static void walEncodeFrame(
54367  Wal *pWal,                      /* The write-ahead log */
54368  u32 iPage,                      /* Database page number for frame */
54369  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
54370  u8 *aData,                      /* Pointer to page data */
54371  u8 *aFrame                      /* OUT: Write encoded frame here */
54372){
54373  int nativeCksum;                /* True for native byte-order checksums */
54374  u32 *aCksum = pWal->hdr.aFrameCksum;
54375  assert( WAL_FRAME_HDRSIZE==24 );
54376  sqlite3Put4byte(&aFrame[0], iPage);
54377  sqlite3Put4byte(&aFrame[4], nTruncate);
54378  if( pWal->iReCksum==0 ){
54379    memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
54380
54381    nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54382    walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54383    walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54384
54385    sqlite3Put4byte(&aFrame[16], aCksum[0]);
54386    sqlite3Put4byte(&aFrame[20], aCksum[1]);
54387  }else{
54388    memset(&aFrame[8], 0, 16);
54389  }
54390}
54391
54392/*
54393** Check to see if the frame with header in aFrame[] and content
54394** in aData[] is valid.  If it is a valid frame, fill *piPage and
54395** *pnTruncate and return true.  Return if the frame is not valid.
54396*/
54397static int walDecodeFrame(
54398  Wal *pWal,                      /* The write-ahead log */
54399  u32 *piPage,                    /* OUT: Database page number for frame */
54400  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
54401  u8 *aData,                      /* Pointer to page data (for checksum) */
54402  u8 *aFrame                      /* Frame data */
54403){
54404  int nativeCksum;                /* True for native byte-order checksums */
54405  u32 *aCksum = pWal->hdr.aFrameCksum;
54406  u32 pgno;                       /* Page number of the frame */
54407  assert( WAL_FRAME_HDRSIZE==24 );
54408
54409  /* A frame is only valid if the salt values in the frame-header
54410  ** match the salt values in the wal-header.
54411  */
54412  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
54413    return 0;
54414  }
54415
54416  /* A frame is only valid if the page number is creater than zero.
54417  */
54418  pgno = sqlite3Get4byte(&aFrame[0]);
54419  if( pgno==0 ){
54420    return 0;
54421  }
54422
54423  /* A frame is only valid if a checksum of the WAL header,
54424  ** all prior frams, the first 16 bytes of this frame-header,
54425  ** and the frame-data matches the checksum in the last 8
54426  ** bytes of this frame-header.
54427  */
54428  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54429  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54430  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54431  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
54432   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
54433  ){
54434    /* Checksum failed. */
54435    return 0;
54436  }
54437
54438  /* If we reach this point, the frame is valid.  Return the page number
54439  ** and the new database size.
54440  */
54441  *piPage = pgno;
54442  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
54443  return 1;
54444}
54445
54446
54447#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54448/*
54449** Names of locks.  This routine is used to provide debugging output and is not
54450** a part of an ordinary build.
54451*/
54452static const char *walLockName(int lockIdx){
54453  if( lockIdx==WAL_WRITE_LOCK ){
54454    return "WRITE-LOCK";
54455  }else if( lockIdx==WAL_CKPT_LOCK ){
54456    return "CKPT-LOCK";
54457  }else if( lockIdx==WAL_RECOVER_LOCK ){
54458    return "RECOVER-LOCK";
54459  }else{
54460    static char zName[15];
54461    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
54462                     lockIdx-WAL_READ_LOCK(0));
54463    return zName;
54464  }
54465}
54466#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
54467
54468
54469/*
54470** Set or release locks on the WAL.  Locks are either shared or exclusive.
54471** A lock cannot be moved directly between shared and exclusive - it must go
54472** through the unlocked state first.
54473**
54474** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
54475*/
54476static int walLockShared(Wal *pWal, int lockIdx){
54477  int rc;
54478  if( pWal->exclusiveMode ) return SQLITE_OK;
54479  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54480                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
54481  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
54482            walLockName(lockIdx), rc ? "failed" : "ok"));
54483  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54484  return rc;
54485}
54486static void walUnlockShared(Wal *pWal, int lockIdx){
54487  if( pWal->exclusiveMode ) return;
54488  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54489                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
54490  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
54491}
54492static int walLockExclusive(Wal *pWal, int lockIdx, int n){
54493  int rc;
54494  if( pWal->exclusiveMode ) return SQLITE_OK;
54495  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54496                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
54497  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
54498            walLockName(lockIdx), n, rc ? "failed" : "ok"));
54499  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54500  return rc;
54501}
54502static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
54503  if( pWal->exclusiveMode ) return;
54504  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54505                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
54506  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
54507             walLockName(lockIdx), n));
54508}
54509
54510/*
54511** Compute a hash on a page number.  The resulting hash value must land
54512** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
54513** the hash to the next value in the event of a collision.
54514*/
54515static int walHash(u32 iPage){
54516  assert( iPage>0 );
54517  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
54518  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
54519}
54520static int walNextHash(int iPriorHash){
54521  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
54522}
54523
54524/*
54525** Return pointers to the hash table and page number array stored on
54526** page iHash of the wal-index. The wal-index is broken into 32KB pages
54527** numbered starting from 0.
54528**
54529** Set output variable *paHash to point to the start of the hash table
54530** in the wal-index file. Set *piZero to one less than the frame
54531** number of the first frame indexed by this hash table. If a
54532** slot in the hash table is set to N, it refers to frame number
54533** (*piZero+N) in the log.
54534**
54535** Finally, set *paPgno so that *paPgno[1] is the page number of the
54536** first frame indexed by the hash table, frame (*piZero+1).
54537*/
54538static int walHashGet(
54539  Wal *pWal,                      /* WAL handle */
54540  int iHash,                      /* Find the iHash'th table */
54541  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
54542  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
54543  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
54544){
54545  int rc;                         /* Return code */
54546  volatile u32 *aPgno;
54547
54548  rc = walIndexPage(pWal, iHash, &aPgno);
54549  assert( rc==SQLITE_OK || iHash>0 );
54550
54551  if( rc==SQLITE_OK ){
54552    u32 iZero;
54553    volatile ht_slot *aHash;
54554
54555    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
54556    if( iHash==0 ){
54557      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
54558      iZero = 0;
54559    }else{
54560      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
54561    }
54562
54563    *paPgno = &aPgno[-1];
54564    *paHash = aHash;
54565    *piZero = iZero;
54566  }
54567  return rc;
54568}
54569
54570/*
54571** Return the number of the wal-index page that contains the hash-table
54572** and page-number array that contain entries corresponding to WAL frame
54573** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
54574** are numbered starting from 0.
54575*/
54576static int walFramePage(u32 iFrame){
54577  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
54578  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
54579       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
54580       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
54581       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
54582       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
54583  );
54584  return iHash;
54585}
54586
54587/*
54588** Return the page number associated with frame iFrame in this WAL.
54589*/
54590static u32 walFramePgno(Wal *pWal, u32 iFrame){
54591  int iHash = walFramePage(iFrame);
54592  if( iHash==0 ){
54593    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
54594  }
54595  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
54596}
54597
54598/*
54599** Remove entries from the hash table that point to WAL slots greater
54600** than pWal->hdr.mxFrame.
54601**
54602** This function is called whenever pWal->hdr.mxFrame is decreased due
54603** to a rollback or savepoint.
54604**
54605** At most only the hash table containing pWal->hdr.mxFrame needs to be
54606** updated.  Any later hash tables will be automatically cleared when
54607** pWal->hdr.mxFrame advances to the point where those hash tables are
54608** actually needed.
54609*/
54610static void walCleanupHash(Wal *pWal){
54611  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
54612  volatile u32 *aPgno = 0;        /* Page number array for hash table */
54613  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
54614  int iLimit = 0;                 /* Zero values greater than this */
54615  int nByte;                      /* Number of bytes to zero in aPgno[] */
54616  int i;                          /* Used to iterate through aHash[] */
54617
54618  assert( pWal->writeLock );
54619  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
54620  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
54621  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
54622
54623  if( pWal->hdr.mxFrame==0 ) return;
54624
54625  /* Obtain pointers to the hash-table and page-number array containing
54626  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
54627  ** that the page said hash-table and array reside on is already mapped.
54628  */
54629  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
54630  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
54631  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
54632
54633  /* Zero all hash-table entries that correspond to frame numbers greater
54634  ** than pWal->hdr.mxFrame.
54635  */
54636  iLimit = pWal->hdr.mxFrame - iZero;
54637  assert( iLimit>0 );
54638  for(i=0; i<HASHTABLE_NSLOT; i++){
54639    if( aHash[i]>iLimit ){
54640      aHash[i] = 0;
54641    }
54642  }
54643
54644  /* Zero the entries in the aPgno array that correspond to frames with
54645  ** frame numbers greater than pWal->hdr.mxFrame.
54646  */
54647  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
54648  memset((void *)&aPgno[iLimit+1], 0, nByte);
54649
54650#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54651  /* Verify that the every entry in the mapping region is still reachable
54652  ** via the hash table even after the cleanup.
54653  */
54654  if( iLimit ){
54655    int j;           /* Loop counter */
54656    int iKey;        /* Hash key */
54657    for(j=1; j<=iLimit; j++){
54658      for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
54659        if( aHash[iKey]==j ) break;
54660      }
54661      assert( aHash[iKey]==j );
54662    }
54663  }
54664#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54665}
54666
54667
54668/*
54669** Set an entry in the wal-index that will map database page number
54670** pPage into WAL frame iFrame.
54671*/
54672static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
54673  int rc;                         /* Return code */
54674  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
54675  volatile u32 *aPgno = 0;        /* Page number array */
54676  volatile ht_slot *aHash = 0;    /* Hash table */
54677
54678  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
54679
54680  /* Assuming the wal-index file was successfully mapped, populate the
54681  ** page number array and hash table entry.
54682  */
54683  if( rc==SQLITE_OK ){
54684    int iKey;                     /* Hash table key */
54685    int idx;                      /* Value to write to hash-table slot */
54686    int nCollide;                 /* Number of hash collisions */
54687
54688    idx = iFrame - iZero;
54689    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
54690
54691    /* If this is the first entry to be added to this hash-table, zero the
54692    ** entire hash table and aPgno[] array before proceeding.
54693    */
54694    if( idx==1 ){
54695      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
54696      memset((void*)&aPgno[1], 0, nByte);
54697    }
54698
54699    /* If the entry in aPgno[] is already set, then the previous writer
54700    ** must have exited unexpectedly in the middle of a transaction (after
54701    ** writing one or more dirty pages to the WAL to free up memory).
54702    ** Remove the remnants of that writers uncommitted transaction from
54703    ** the hash-table before writing any new entries.
54704    */
54705    if( aPgno[idx] ){
54706      walCleanupHash(pWal);
54707      assert( !aPgno[idx] );
54708    }
54709
54710    /* Write the aPgno[] array entry and the hash-table slot. */
54711    nCollide = idx;
54712    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
54713      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
54714    }
54715    aPgno[idx] = iPage;
54716    aHash[iKey] = (ht_slot)idx;
54717
54718#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54719    /* Verify that the number of entries in the hash table exactly equals
54720    ** the number of entries in the mapping region.
54721    */
54722    {
54723      int i;           /* Loop counter */
54724      int nEntry = 0;  /* Number of entries in the hash table */
54725      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
54726      assert( nEntry==idx );
54727    }
54728
54729    /* Verify that the every entry in the mapping region is reachable
54730    ** via the hash table.  This turns out to be a really, really expensive
54731    ** thing to check, so only do this occasionally - not on every
54732    ** iteration.
54733    */
54734    if( (idx&0x3ff)==0 ){
54735      int i;           /* Loop counter */
54736      for(i=1; i<=idx; i++){
54737        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
54738          if( aHash[iKey]==i ) break;
54739        }
54740        assert( aHash[iKey]==i );
54741      }
54742    }
54743#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54744  }
54745
54746
54747  return rc;
54748}
54749
54750
54751/*
54752** Recover the wal-index by reading the write-ahead log file.
54753**
54754** This routine first tries to establish an exclusive lock on the
54755** wal-index to prevent other threads/processes from doing anything
54756** with the WAL or wal-index while recovery is running.  The
54757** WAL_RECOVER_LOCK is also held so that other threads will know
54758** that this thread is running recovery.  If unable to establish
54759** the necessary locks, this routine returns SQLITE_BUSY.
54760*/
54761static int walIndexRecover(Wal *pWal){
54762  int rc;                         /* Return Code */
54763  i64 nSize;                      /* Size of log file */
54764  u32 aFrameCksum[2] = {0, 0};
54765  int iLock;                      /* Lock offset to lock for checkpoint */
54766  int nLock;                      /* Number of locks to hold */
54767
54768  /* Obtain an exclusive lock on all byte in the locking range not already
54769  ** locked by the caller. The caller is guaranteed to have locked the
54770  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
54771  ** If successful, the same bytes that are locked here are unlocked before
54772  ** this function returns.
54773  */
54774  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
54775  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
54776  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
54777  assert( pWal->writeLock );
54778  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
54779  nLock = SQLITE_SHM_NLOCK - iLock;
54780  rc = walLockExclusive(pWal, iLock, nLock);
54781  if( rc ){
54782    return rc;
54783  }
54784  WALTRACE(("WAL%p: recovery begin...\n", pWal));
54785
54786  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
54787
54788  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
54789  if( rc!=SQLITE_OK ){
54790    goto recovery_error;
54791  }
54792
54793  if( nSize>WAL_HDRSIZE ){
54794    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
54795    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
54796    int szFrame;                  /* Number of bytes in buffer aFrame[] */
54797    u8 *aData;                    /* Pointer to data part of aFrame buffer */
54798    int iFrame;                   /* Index of last frame read */
54799    i64 iOffset;                  /* Next offset to read from log file */
54800    int szPage;                   /* Page size according to the log */
54801    u32 magic;                    /* Magic value read from WAL header */
54802    u32 version;                  /* Magic value read from WAL header */
54803    int isValid;                  /* True if this frame is valid */
54804
54805    /* Read in the WAL header. */
54806    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
54807    if( rc!=SQLITE_OK ){
54808      goto recovery_error;
54809    }
54810
54811    /* If the database page size is not a power of two, or is greater than
54812    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
54813    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
54814    ** WAL file.
54815    */
54816    magic = sqlite3Get4byte(&aBuf[0]);
54817    szPage = sqlite3Get4byte(&aBuf[8]);
54818    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
54819     || szPage&(szPage-1)
54820     || szPage>SQLITE_MAX_PAGE_SIZE
54821     || szPage<512
54822    ){
54823      goto finished;
54824    }
54825    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
54826    pWal->szPage = szPage;
54827    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
54828    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
54829
54830    /* Verify that the WAL header checksum is correct */
54831    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
54832        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
54833    );
54834    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
54835     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
54836    ){
54837      goto finished;
54838    }
54839
54840    /* Verify that the version number on the WAL format is one that
54841    ** are able to understand */
54842    version = sqlite3Get4byte(&aBuf[4]);
54843    if( version!=WAL_MAX_VERSION ){
54844      rc = SQLITE_CANTOPEN_BKPT;
54845      goto finished;
54846    }
54847
54848    /* Malloc a buffer to read frames into. */
54849    szFrame = szPage + WAL_FRAME_HDRSIZE;
54850    aFrame = (u8 *)sqlite3_malloc64(szFrame);
54851    if( !aFrame ){
54852      rc = SQLITE_NOMEM_BKPT;
54853      goto recovery_error;
54854    }
54855    aData = &aFrame[WAL_FRAME_HDRSIZE];
54856
54857    /* Read all frames from the log file. */
54858    iFrame = 0;
54859    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
54860      u32 pgno;                   /* Database page number for frame */
54861      u32 nTruncate;              /* dbsize field from frame header */
54862
54863      /* Read and decode the next log frame. */
54864      iFrame++;
54865      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
54866      if( rc!=SQLITE_OK ) break;
54867      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
54868      if( !isValid ) break;
54869      rc = walIndexAppend(pWal, iFrame, pgno);
54870      if( rc!=SQLITE_OK ) break;
54871
54872      /* If nTruncate is non-zero, this is a commit record. */
54873      if( nTruncate ){
54874        pWal->hdr.mxFrame = iFrame;
54875        pWal->hdr.nPage = nTruncate;
54876        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
54877        testcase( szPage<=32768 );
54878        testcase( szPage>=65536 );
54879        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
54880        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
54881      }
54882    }
54883
54884    sqlite3_free(aFrame);
54885  }
54886
54887finished:
54888  if( rc==SQLITE_OK ){
54889    volatile WalCkptInfo *pInfo;
54890    int i;
54891    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
54892    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
54893    walIndexWriteHdr(pWal);
54894
54895    /* Reset the checkpoint-header. This is safe because this thread is
54896    ** currently holding locks that exclude all other readers, writers and
54897    ** checkpointers.
54898    */
54899    pInfo = walCkptInfo(pWal);
54900    pInfo->nBackfill = 0;
54901    pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
54902    pInfo->aReadMark[0] = 0;
54903    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
54904    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
54905
54906    /* If more than one frame was recovered from the log file, report an
54907    ** event via sqlite3_log(). This is to help with identifying performance
54908    ** problems caused by applications routinely shutting down without
54909    ** checkpointing the log file.
54910    */
54911    if( pWal->hdr.nPage ){
54912      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
54913          "recovered %d frames from WAL file %s",
54914          pWal->hdr.mxFrame, pWal->zWalName
54915      );
54916    }
54917  }
54918
54919recovery_error:
54920  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
54921  walUnlockExclusive(pWal, iLock, nLock);
54922  return rc;
54923}
54924
54925/*
54926** Close an open wal-index.
54927*/
54928static void walIndexClose(Wal *pWal, int isDelete){
54929  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54930    int i;
54931    for(i=0; i<pWal->nWiData; i++){
54932      sqlite3_free((void *)pWal->apWiData[i]);
54933      pWal->apWiData[i] = 0;
54934    }
54935  }else{
54936    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
54937  }
54938}
54939
54940/*
54941** Open a connection to the WAL file zWalName. The database file must
54942** already be opened on connection pDbFd. The buffer that zWalName points
54943** to must remain valid for the lifetime of the returned Wal* handle.
54944**
54945** A SHARED lock should be held on the database file when this function
54946** is called. The purpose of this SHARED lock is to prevent any other
54947** client from unlinking the WAL or wal-index file. If another process
54948** were to do this just after this client opened one of these files, the
54949** system would be badly broken.
54950**
54951** If the log file is successfully opened, SQLITE_OK is returned and
54952** *ppWal is set to point to a new WAL handle. If an error occurs,
54953** an SQLite error code is returned and *ppWal is left unmodified.
54954*/
54955SQLITE_PRIVATE int sqlite3WalOpen(
54956  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
54957  sqlite3_file *pDbFd,            /* The open database file */
54958  const char *zWalName,           /* Name of the WAL file */
54959  int bNoShm,                     /* True to run in heap-memory mode */
54960  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
54961  Wal **ppWal                     /* OUT: Allocated Wal handle */
54962){
54963  int rc;                         /* Return Code */
54964  Wal *pRet;                      /* Object to allocate and return */
54965  int flags;                      /* Flags passed to OsOpen() */
54966
54967  assert( zWalName && zWalName[0] );
54968  assert( pDbFd );
54969
54970  /* In the amalgamation, the os_unix.c and os_win.c source files come before
54971  ** this source file.  Verify that the #defines of the locking byte offsets
54972  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
54973  ** For that matter, if the lock offset ever changes from its initial design
54974  ** value of 120, we need to know that so there is an assert() to check it.
54975  */
54976  assert( 120==WALINDEX_LOCK_OFFSET );
54977  assert( 136==WALINDEX_HDR_SIZE );
54978#ifdef WIN_SHM_BASE
54979  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
54980#endif
54981#ifdef UNIX_SHM_BASE
54982  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
54983#endif
54984
54985
54986  /* Allocate an instance of struct Wal to return. */
54987  *ppWal = 0;
54988  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
54989  if( !pRet ){
54990    return SQLITE_NOMEM_BKPT;
54991  }
54992
54993  pRet->pVfs = pVfs;
54994  pRet->pWalFd = (sqlite3_file *)&pRet[1];
54995  pRet->pDbFd = pDbFd;
54996  pRet->readLock = -1;
54997  pRet->mxWalSize = mxWalSize;
54998  pRet->zWalName = zWalName;
54999  pRet->syncHeader = 1;
55000  pRet->padToSectorBoundary = 1;
55001  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
55002
55003  /* Open file handle on the write-ahead log file. */
55004  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
55005  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
55006  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
55007    pRet->readOnly = WAL_RDONLY;
55008  }
55009
55010  if( rc!=SQLITE_OK ){
55011    walIndexClose(pRet, 0);
55012    sqlite3OsClose(pRet->pWalFd);
55013    sqlite3_free(pRet);
55014  }else{
55015    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
55016    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
55017    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
55018      pRet->padToSectorBoundary = 0;
55019    }
55020    *ppWal = pRet;
55021    WALTRACE(("WAL%d: opened\n", pRet));
55022  }
55023  return rc;
55024}
55025
55026/*
55027** Change the size to which the WAL file is trucated on each reset.
55028*/
55029SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
55030  if( pWal ) pWal->mxWalSize = iLimit;
55031}
55032
55033/*
55034** Find the smallest page number out of all pages held in the WAL that
55035** has not been returned by any prior invocation of this method on the
55036** same WalIterator object.   Write into *piFrame the frame index where
55037** that page was last written into the WAL.  Write into *piPage the page
55038** number.
55039**
55040** Return 0 on success.  If there are no pages in the WAL with a page
55041** number larger than *piPage, then return 1.
55042*/
55043static int walIteratorNext(
55044  WalIterator *p,               /* Iterator */
55045  u32 *piPage,                  /* OUT: The page number of the next page */
55046  u32 *piFrame                  /* OUT: Wal frame index of next page */
55047){
55048  u32 iMin;                     /* Result pgno must be greater than iMin */
55049  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
55050  int i;                        /* For looping through segments */
55051
55052  iMin = p->iPrior;
55053  assert( iMin<0xffffffff );
55054  for(i=p->nSegment-1; i>=0; i--){
55055    struct WalSegment *pSegment = &p->aSegment[i];
55056    while( pSegment->iNext<pSegment->nEntry ){
55057      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
55058      if( iPg>iMin ){
55059        if( iPg<iRet ){
55060          iRet = iPg;
55061          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
55062        }
55063        break;
55064      }
55065      pSegment->iNext++;
55066    }
55067  }
55068
55069  *piPage = p->iPrior = iRet;
55070  return (iRet==0xFFFFFFFF);
55071}
55072
55073/*
55074** This function merges two sorted lists into a single sorted list.
55075**
55076** aLeft[] and aRight[] are arrays of indices.  The sort key is
55077** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
55078** is guaranteed for all J<K:
55079**
55080**        aContent[aLeft[J]] < aContent[aLeft[K]]
55081**        aContent[aRight[J]] < aContent[aRight[K]]
55082**
55083** This routine overwrites aRight[] with a new (probably longer) sequence
55084** of indices such that the aRight[] contains every index that appears in
55085** either aLeft[] or the old aRight[] and such that the second condition
55086** above is still met.
55087**
55088** The aContent[aLeft[X]] values will be unique for all X.  And the
55089** aContent[aRight[X]] values will be unique too.  But there might be
55090** one or more combinations of X and Y such that
55091**
55092**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
55093**
55094** When that happens, omit the aLeft[X] and use the aRight[Y] index.
55095*/
55096static void walMerge(
55097  const u32 *aContent,            /* Pages in wal - keys for the sort */
55098  ht_slot *aLeft,                 /* IN: Left hand input list */
55099  int nLeft,                      /* IN: Elements in array *paLeft */
55100  ht_slot **paRight,              /* IN/OUT: Right hand input list */
55101  int *pnRight,                   /* IN/OUT: Elements in *paRight */
55102  ht_slot *aTmp                   /* Temporary buffer */
55103){
55104  int iLeft = 0;                  /* Current index in aLeft */
55105  int iRight = 0;                 /* Current index in aRight */
55106  int iOut = 0;                   /* Current index in output buffer */
55107  int nRight = *pnRight;
55108  ht_slot *aRight = *paRight;
55109
55110  assert( nLeft>0 && nRight>0 );
55111  while( iRight<nRight || iLeft<nLeft ){
55112    ht_slot logpage;
55113    Pgno dbpage;
55114
55115    if( (iLeft<nLeft)
55116     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
55117    ){
55118      logpage = aLeft[iLeft++];
55119    }else{
55120      logpage = aRight[iRight++];
55121    }
55122    dbpage = aContent[logpage];
55123
55124    aTmp[iOut++] = logpage;
55125    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
55126
55127    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
55128    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
55129  }
55130
55131  *paRight = aLeft;
55132  *pnRight = iOut;
55133  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
55134}
55135
55136/*
55137** Sort the elements in list aList using aContent[] as the sort key.
55138** Remove elements with duplicate keys, preferring to keep the
55139** larger aList[] values.
55140**
55141** The aList[] entries are indices into aContent[].  The values in
55142** aList[] are to be sorted so that for all J<K:
55143**
55144**      aContent[aList[J]] < aContent[aList[K]]
55145**
55146** For any X and Y such that
55147**
55148**      aContent[aList[X]] == aContent[aList[Y]]
55149**
55150** Keep the larger of the two values aList[X] and aList[Y] and discard
55151** the smaller.
55152*/
55153static void walMergesort(
55154  const u32 *aContent,            /* Pages in wal */
55155  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
55156  ht_slot *aList,                 /* IN/OUT: List to sort */
55157  int *pnList                     /* IN/OUT: Number of elements in aList[] */
55158){
55159  struct Sublist {
55160    int nList;                    /* Number of elements in aList */
55161    ht_slot *aList;               /* Pointer to sub-list content */
55162  };
55163
55164  const int nList = *pnList;      /* Size of input list */
55165  int nMerge = 0;                 /* Number of elements in list aMerge */
55166  ht_slot *aMerge = 0;            /* List to be merged */
55167  int iList;                      /* Index into input list */
55168  u32 iSub = 0;                   /* Index into aSub array */
55169  struct Sublist aSub[13];        /* Array of sub-lists */
55170
55171  memset(aSub, 0, sizeof(aSub));
55172  assert( nList<=HASHTABLE_NPAGE && nList>0 );
55173  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
55174
55175  for(iList=0; iList<nList; iList++){
55176    nMerge = 1;
55177    aMerge = &aList[iList];
55178    for(iSub=0; iList & (1<<iSub); iSub++){
55179      struct Sublist *p;
55180      assert( iSub<ArraySize(aSub) );
55181      p = &aSub[iSub];
55182      assert( p->aList && p->nList<=(1<<iSub) );
55183      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
55184      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55185    }
55186    aSub[iSub].aList = aMerge;
55187    aSub[iSub].nList = nMerge;
55188  }
55189
55190  for(iSub++; iSub<ArraySize(aSub); iSub++){
55191    if( nList & (1<<iSub) ){
55192      struct Sublist *p;
55193      assert( iSub<ArraySize(aSub) );
55194      p = &aSub[iSub];
55195      assert( p->nList<=(1<<iSub) );
55196      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
55197      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55198    }
55199  }
55200  assert( aMerge==aList );
55201  *pnList = nMerge;
55202
55203#ifdef SQLITE_DEBUG
55204  {
55205    int i;
55206    for(i=1; i<*pnList; i++){
55207      assert( aContent[aList[i]] > aContent[aList[i-1]] );
55208    }
55209  }
55210#endif
55211}
55212
55213/*
55214** Free an iterator allocated by walIteratorInit().
55215*/
55216static void walIteratorFree(WalIterator *p){
55217  sqlite3_free(p);
55218}
55219
55220/*
55221** Construct a WalInterator object that can be used to loop over all
55222** pages in the WAL in ascending order. The caller must hold the checkpoint
55223** lock.
55224**
55225** On success, make *pp point to the newly allocated WalInterator object
55226** return SQLITE_OK. Otherwise, return an error code. If this routine
55227** returns an error, the value of *pp is undefined.
55228**
55229** The calling routine should invoke walIteratorFree() to destroy the
55230** WalIterator object when it has finished with it.
55231*/
55232static int walIteratorInit(Wal *pWal, WalIterator **pp){
55233  WalIterator *p;                 /* Return value */
55234  int nSegment;                   /* Number of segments to merge */
55235  u32 iLast;                      /* Last frame in log */
55236  int nByte;                      /* Number of bytes to allocate */
55237  int i;                          /* Iterator variable */
55238  ht_slot *aTmp;                  /* Temp space used by merge-sort */
55239  int rc = SQLITE_OK;             /* Return Code */
55240
55241  /* This routine only runs while holding the checkpoint lock. And
55242  ** it only runs if there is actually content in the log (mxFrame>0).
55243  */
55244  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
55245  iLast = pWal->hdr.mxFrame;
55246
55247  /* Allocate space for the WalIterator object. */
55248  nSegment = walFramePage(iLast) + 1;
55249  nByte = sizeof(WalIterator)
55250        + (nSegment-1)*sizeof(struct WalSegment)
55251        + iLast*sizeof(ht_slot);
55252  p = (WalIterator *)sqlite3_malloc64(nByte);
55253  if( !p ){
55254    return SQLITE_NOMEM_BKPT;
55255  }
55256  memset(p, 0, nByte);
55257  p->nSegment = nSegment;
55258
55259  /* Allocate temporary space used by the merge-sort routine. This block
55260  ** of memory will be freed before this function returns.
55261  */
55262  aTmp = (ht_slot *)sqlite3_malloc64(
55263      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
55264  );
55265  if( !aTmp ){
55266    rc = SQLITE_NOMEM_BKPT;
55267  }
55268
55269  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
55270    volatile ht_slot *aHash;
55271    u32 iZero;
55272    volatile u32 *aPgno;
55273
55274    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
55275    if( rc==SQLITE_OK ){
55276      int j;                      /* Counter variable */
55277      int nEntry;                 /* Number of entries in this segment */
55278      ht_slot *aIndex;            /* Sorted index for this segment */
55279
55280      aPgno++;
55281      if( (i+1)==nSegment ){
55282        nEntry = (int)(iLast - iZero);
55283      }else{
55284        nEntry = (int)((u32*)aHash - (u32*)aPgno);
55285      }
55286      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
55287      iZero++;
55288
55289      for(j=0; j<nEntry; j++){
55290        aIndex[j] = (ht_slot)j;
55291      }
55292      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
55293      p->aSegment[i].iZero = iZero;
55294      p->aSegment[i].nEntry = nEntry;
55295      p->aSegment[i].aIndex = aIndex;
55296      p->aSegment[i].aPgno = (u32 *)aPgno;
55297    }
55298  }
55299  sqlite3_free(aTmp);
55300
55301  if( rc!=SQLITE_OK ){
55302    walIteratorFree(p);
55303  }
55304  *pp = p;
55305  return rc;
55306}
55307
55308/*
55309** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
55310** n. If the attempt fails and parameter xBusy is not NULL, then it is a
55311** busy-handler function. Invoke it and retry the lock until either the
55312** lock is successfully obtained or the busy-handler returns 0.
55313*/
55314static int walBusyLock(
55315  Wal *pWal,                      /* WAL connection */
55316  int (*xBusy)(void*),            /* Function to call when busy */
55317  void *pBusyArg,                 /* Context argument for xBusyHandler */
55318  int lockIdx,                    /* Offset of first byte to lock */
55319  int n                           /* Number of bytes to lock */
55320){
55321  int rc;
55322  do {
55323    rc = walLockExclusive(pWal, lockIdx, n);
55324  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
55325  return rc;
55326}
55327
55328/*
55329** The cache of the wal-index header must be valid to call this function.
55330** Return the page-size in bytes used by the database.
55331*/
55332static int walPagesize(Wal *pWal){
55333  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55334}
55335
55336/*
55337** The following is guaranteed when this function is called:
55338**
55339**   a) the WRITER lock is held,
55340**   b) the entire log file has been checkpointed, and
55341**   c) any existing readers are reading exclusively from the database
55342**      file - there are no readers that may attempt to read a frame from
55343**      the log file.
55344**
55345** This function updates the shared-memory structures so that the next
55346** client to write to the database (which may be this one) does so by
55347** writing frames into the start of the log file.
55348**
55349** The value of parameter salt1 is used as the aSalt[1] value in the
55350** new wal-index header. It should be passed a pseudo-random value (i.e.
55351** one obtained from sqlite3_randomness()).
55352*/
55353static void walRestartHdr(Wal *pWal, u32 salt1){
55354  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
55355  int i;                          /* Loop counter */
55356  u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
55357  pWal->nCkpt++;
55358  pWal->hdr.mxFrame = 0;
55359  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
55360  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
55361  walIndexWriteHdr(pWal);
55362  pInfo->nBackfill = 0;
55363  pInfo->nBackfillAttempted = 0;
55364  pInfo->aReadMark[1] = 0;
55365  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55366  assert( pInfo->aReadMark[0]==0 );
55367}
55368
55369/*
55370** Copy as much content as we can from the WAL back into the database file
55371** in response to an sqlite3_wal_checkpoint() request or the equivalent.
55372**
55373** The amount of information copies from WAL to database might be limited
55374** by active readers.  This routine will never overwrite a database page
55375** that a concurrent reader might be using.
55376**
55377** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
55378** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
55379** checkpoints are always run by a background thread or background
55380** process, foreground threads will never block on a lengthy fsync call.
55381**
55382** Fsync is called on the WAL before writing content out of the WAL and
55383** into the database.  This ensures that if the new content is persistent
55384** in the WAL and can be recovered following a power-loss or hard reset.
55385**
55386** Fsync is also called on the database file if (and only if) the entire
55387** WAL content is copied into the database file.  This second fsync makes
55388** it safe to delete the WAL since the new content will persist in the
55389** database file.
55390**
55391** This routine uses and updates the nBackfill field of the wal-index header.
55392** This is the only routine that will increase the value of nBackfill.
55393** (A WAL reset or recovery will revert nBackfill to zero, but not increase
55394** its value.)
55395**
55396** The caller must be holding sufficient locks to ensure that no other
55397** checkpoint is running (in any other thread or process) at the same
55398** time.
55399*/
55400static int walCheckpoint(
55401  Wal *pWal,                      /* Wal connection */
55402  int eMode,                      /* One of PASSIVE, FULL or RESTART */
55403  int (*xBusy)(void*),            /* Function to call when busy */
55404  void *pBusyArg,                 /* Context argument for xBusyHandler */
55405  int sync_flags,                 /* Flags for OsSync() (or 0) */
55406  u8 *zBuf                        /* Temporary buffer to use */
55407){
55408  int rc = SQLITE_OK;             /* Return code */
55409  int szPage;                     /* Database page-size */
55410  WalIterator *pIter = 0;         /* Wal iterator context */
55411  u32 iDbpage = 0;                /* Next database page to write */
55412  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
55413  u32 mxSafeFrame;                /* Max frame that can be backfilled */
55414  u32 mxPage;                     /* Max database page to write */
55415  int i;                          /* Loop counter */
55416  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
55417
55418  szPage = walPagesize(pWal);
55419  testcase( szPage<=32768 );
55420  testcase( szPage>=65536 );
55421  pInfo = walCkptInfo(pWal);
55422  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55423
55424    /* Allocate the iterator */
55425    rc = walIteratorInit(pWal, &pIter);
55426    if( rc!=SQLITE_OK ){
55427      return rc;
55428    }
55429    assert( pIter );
55430
55431    /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
55432    ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
55433    assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
55434
55435    /* Compute in mxSafeFrame the index of the last frame of the WAL that is
55436    ** safe to write into the database.  Frames beyond mxSafeFrame might
55437    ** overwrite database pages that are in use by active readers and thus
55438    ** cannot be backfilled from the WAL.
55439    */
55440    mxSafeFrame = pWal->hdr.mxFrame;
55441    mxPage = pWal->hdr.nPage;
55442    for(i=1; i<WAL_NREADER; i++){
55443      /* Thread-sanitizer reports that the following is an unsafe read,
55444      ** as some other thread may be in the process of updating the value
55445      ** of the aReadMark[] slot. The assumption here is that if that is
55446      ** happening, the other client may only be increasing the value,
55447      ** not decreasing it. So assuming either that either the "old" or
55448      ** "new" version of the value is read, and not some arbitrary value
55449      ** that would never be written by a real client, things are still
55450      ** safe.  */
55451      u32 y = pInfo->aReadMark[i];
55452      if( mxSafeFrame>y ){
55453        assert( y<=pWal->hdr.mxFrame );
55454        rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
55455        if( rc==SQLITE_OK ){
55456          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
55457          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55458        }else if( rc==SQLITE_BUSY ){
55459          mxSafeFrame = y;
55460          xBusy = 0;
55461        }else{
55462          goto walcheckpoint_out;
55463        }
55464      }
55465    }
55466
55467    if( pInfo->nBackfill<mxSafeFrame
55468     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
55469    ){
55470      i64 nSize;                    /* Current size of database file */
55471      u32 nBackfill = pInfo->nBackfill;
55472
55473      pInfo->nBackfillAttempted = mxSafeFrame;
55474
55475      /* Sync the WAL to disk */
55476      if( sync_flags ){
55477        rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
55478      }
55479
55480      /* If the database may grow as a result of this checkpoint, hint
55481      ** about the eventual size of the db file to the VFS layer.
55482      */
55483      if( rc==SQLITE_OK ){
55484        i64 nReq = ((i64)mxPage * szPage);
55485        rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
55486        if( rc==SQLITE_OK && nSize<nReq ){
55487          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
55488        }
55489      }
55490
55491
55492      /* Iterate through the contents of the WAL, copying data to the db file */
55493      while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
55494        i64 iOffset;
55495        assert( walFramePgno(pWal, iFrame)==iDbpage );
55496        if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
55497          continue;
55498        }
55499        iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
55500        /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
55501        rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
55502        if( rc!=SQLITE_OK ) break;
55503        iOffset = (iDbpage-1)*(i64)szPage;
55504        testcase( IS_BIG_INT(iOffset) );
55505        rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
55506        if( rc!=SQLITE_OK ) break;
55507      }
55508
55509      /* If work was actually accomplished... */
55510      if( rc==SQLITE_OK ){
55511        if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
55512          i64 szDb = pWal->hdr.nPage*(i64)szPage;
55513          testcase( IS_BIG_INT(szDb) );
55514          rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
55515          if( rc==SQLITE_OK && sync_flags ){
55516            rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
55517          }
55518        }
55519        if( rc==SQLITE_OK ){
55520          pInfo->nBackfill = mxSafeFrame;
55521        }
55522      }
55523
55524      /* Release the reader lock held while backfilling */
55525      walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
55526    }
55527
55528    if( rc==SQLITE_BUSY ){
55529      /* Reset the return code so as not to report a checkpoint failure
55530      ** just because there are active readers.  */
55531      rc = SQLITE_OK;
55532    }
55533  }
55534
55535  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
55536  ** entire wal file has been copied into the database file, then block
55537  ** until all readers have finished using the wal file. This ensures that
55538  ** the next process to write to the database restarts the wal file.
55539  */
55540  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
55541    assert( pWal->writeLock );
55542    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55543      rc = SQLITE_BUSY;
55544    }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
55545      u32 salt1;
55546      sqlite3_randomness(4, &salt1);
55547      assert( pInfo->nBackfill==pWal->hdr.mxFrame );
55548      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
55549      if( rc==SQLITE_OK ){
55550        if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
55551          /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
55552          ** SQLITE_CHECKPOINT_RESTART with the addition that it also
55553          ** truncates the log file to zero bytes just prior to a
55554          ** successful return.
55555          **
55556          ** In theory, it might be safe to do this without updating the
55557          ** wal-index header in shared memory, as all subsequent reader or
55558          ** writer clients should see that the entire log file has been
55559          ** checkpointed and behave accordingly. This seems unsafe though,
55560          ** as it would leave the system in a state where the contents of
55561          ** the wal-index header do not match the contents of the
55562          ** file-system. To avoid this, update the wal-index header to
55563          ** indicate that the log file contains zero valid frames.  */
55564          walRestartHdr(pWal, salt1);
55565          rc = sqlite3OsTruncate(pWal->pWalFd, 0);
55566        }
55567        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
55568      }
55569    }
55570  }
55571
55572 walcheckpoint_out:
55573  walIteratorFree(pIter);
55574  return rc;
55575}
55576
55577/*
55578** If the WAL file is currently larger than nMax bytes in size, truncate
55579** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
55580*/
55581static void walLimitSize(Wal *pWal, i64 nMax){
55582  i64 sz;
55583  int rx;
55584  sqlite3BeginBenignMalloc();
55585  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
55586  if( rx==SQLITE_OK && (sz > nMax ) ){
55587    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
55588  }
55589  sqlite3EndBenignMalloc();
55590  if( rx ){
55591    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
55592  }
55593}
55594
55595/*
55596** Close a connection to a log file.
55597*/
55598SQLITE_PRIVATE int sqlite3WalClose(
55599  Wal *pWal,                      /* Wal to close */
55600  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
55601  int nBuf,
55602  u8 *zBuf                        /* Buffer of at least nBuf bytes */
55603){
55604  int rc = SQLITE_OK;
55605  if( pWal ){
55606    int isDelete = 0;             /* True to unlink wal and wal-index files */
55607
55608    /* If an EXCLUSIVE lock can be obtained on the database file (using the
55609    ** ordinary, rollback-mode locking methods, this guarantees that the
55610    ** connection associated with this log file is the only connection to
55611    ** the database. In this case checkpoint the database and unlink both
55612    ** the wal and wal-index files.
55613    **
55614    ** The EXCLUSIVE lock is not released before returning.
55615    */
55616    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
55617    if( rc==SQLITE_OK ){
55618      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
55619        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
55620      }
55621      rc = sqlite3WalCheckpoint(
55622          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
55623      );
55624      if( rc==SQLITE_OK ){
55625        int bPersist = -1;
55626        sqlite3OsFileControlHint(
55627            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
55628        );
55629        if( bPersist!=1 ){
55630          /* Try to delete the WAL file if the checkpoint completed and
55631          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
55632          ** mode (!bPersist) */
55633          isDelete = 1;
55634        }else if( pWal->mxWalSize>=0 ){
55635          /* Try to truncate the WAL file to zero bytes if the checkpoint
55636          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
55637          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
55638          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
55639          ** to zero bytes as truncating to the journal_size_limit might
55640          ** leave a corrupt WAL file on disk. */
55641          walLimitSize(pWal, 0);
55642        }
55643      }
55644    }
55645
55646    walIndexClose(pWal, isDelete);
55647    sqlite3OsClose(pWal->pWalFd);
55648    if( isDelete ){
55649      sqlite3BeginBenignMalloc();
55650      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
55651      sqlite3EndBenignMalloc();
55652    }
55653    WALTRACE(("WAL%p: closed\n", pWal));
55654    sqlite3_free((void *)pWal->apWiData);
55655    sqlite3_free(pWal);
55656  }
55657  return rc;
55658}
55659
55660/*
55661** Try to read the wal-index header.  Return 0 on success and 1 if
55662** there is a problem.
55663**
55664** The wal-index is in shared memory.  Another thread or process might
55665** be writing the header at the same time this procedure is trying to
55666** read it, which might result in inconsistency.  A dirty read is detected
55667** by verifying that both copies of the header are the same and also by
55668** a checksum on the header.
55669**
55670** If and only if the read is consistent and the header is different from
55671** pWal->hdr, then pWal->hdr is updated to the content of the new header
55672** and *pChanged is set to 1.
55673**
55674** If the checksum cannot be verified return non-zero. If the header
55675** is read successfully and the checksum verified, return zero.
55676*/
55677static int walIndexTryHdr(Wal *pWal, int *pChanged){
55678  u32 aCksum[2];                  /* Checksum on the header content */
55679  WalIndexHdr h1, h2;             /* Two copies of the header content */
55680  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
55681
55682  /* The first page of the wal-index must be mapped at this point. */
55683  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55684
55685  /* Read the header. This might happen concurrently with a write to the
55686  ** same area of shared memory on a different CPU in a SMP,
55687  ** meaning it is possible that an inconsistent snapshot is read
55688  ** from the file. If this happens, return non-zero.
55689  **
55690  ** There are two copies of the header at the beginning of the wal-index.
55691  ** When reading, read [0] first then [1].  Writes are in the reverse order.
55692  ** Memory barriers are used to prevent the compiler or the hardware from
55693  ** reordering the reads and writes.
55694  */
55695  aHdr = walIndexHdr(pWal);
55696  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
55697  walShmBarrier(pWal);
55698  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
55699
55700  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
55701    return 1;   /* Dirty read */
55702  }
55703  if( h1.isInit==0 ){
55704    return 1;   /* Malformed header - probably all zeros */
55705  }
55706  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
55707  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
55708    return 1;   /* Checksum does not match */
55709  }
55710
55711  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
55712    *pChanged = 1;
55713    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
55714    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55715    testcase( pWal->szPage<=32768 );
55716    testcase( pWal->szPage>=65536 );
55717  }
55718
55719  /* The header was successfully read. Return zero. */
55720  return 0;
55721}
55722
55723/*
55724** Read the wal-index header from the wal-index and into pWal->hdr.
55725** If the wal-header appears to be corrupt, try to reconstruct the
55726** wal-index from the WAL before returning.
55727**
55728** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
55729** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
55730** to 0.
55731**
55732** If the wal-index header is successfully read, return SQLITE_OK.
55733** Otherwise an SQLite error code.
55734*/
55735static int walIndexReadHdr(Wal *pWal, int *pChanged){
55736  int rc;                         /* Return code */
55737  int badHdr;                     /* True if a header read failed */
55738  volatile u32 *page0;            /* Chunk of wal-index containing header */
55739
55740  /* Ensure that page 0 of the wal-index (the page that contains the
55741  ** wal-index header) is mapped. Return early if an error occurs here.
55742  */
55743  assert( pChanged );
55744  rc = walIndexPage(pWal, 0, &page0);
55745  if( rc!=SQLITE_OK ){
55746    return rc;
55747  };
55748  assert( page0 || pWal->writeLock==0 );
55749
55750  /* If the first page of the wal-index has been mapped, try to read the
55751  ** wal-index header immediately, without holding any lock. This usually
55752  ** works, but may fail if the wal-index header is corrupt or currently
55753  ** being modified by another thread or process.
55754  */
55755  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
55756
55757  /* If the first attempt failed, it might have been due to a race
55758  ** with a writer.  So get a WRITE lock and try again.
55759  */
55760  assert( badHdr==0 || pWal->writeLock==0 );
55761  if( badHdr ){
55762    if( pWal->readOnly & WAL_SHM_RDONLY ){
55763      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
55764        walUnlockShared(pWal, WAL_WRITE_LOCK);
55765        rc = SQLITE_READONLY_RECOVERY;
55766      }
55767    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
55768      pWal->writeLock = 1;
55769      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
55770        badHdr = walIndexTryHdr(pWal, pChanged);
55771        if( badHdr ){
55772          /* If the wal-index header is still malformed even while holding
55773          ** a WRITE lock, it can only mean that the header is corrupted and
55774          ** needs to be reconstructed.  So run recovery to do exactly that.
55775          */
55776          rc = walIndexRecover(pWal);
55777          *pChanged = 1;
55778        }
55779      }
55780      pWal->writeLock = 0;
55781      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
55782    }
55783  }
55784
55785  /* If the header is read successfully, check the version number to make
55786  ** sure the wal-index was not constructed with some future format that
55787  ** this version of SQLite cannot understand.
55788  */
55789  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
55790    rc = SQLITE_CANTOPEN_BKPT;
55791  }
55792
55793  return rc;
55794}
55795
55796/*
55797** This is the value that walTryBeginRead returns when it needs to
55798** be retried.
55799*/
55800#define WAL_RETRY  (-1)
55801
55802/*
55803** Attempt to start a read transaction.  This might fail due to a race or
55804** other transient condition.  When that happens, it returns WAL_RETRY to
55805** indicate to the caller that it is safe to retry immediately.
55806**
55807** On success return SQLITE_OK.  On a permanent failure (such an
55808** I/O error or an SQLITE_BUSY because another process is running
55809** recovery) return a positive error code.
55810**
55811** The useWal parameter is true to force the use of the WAL and disable
55812** the case where the WAL is bypassed because it has been completely
55813** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
55814** to make a copy of the wal-index header into pWal->hdr.  If the
55815** wal-index header has changed, *pChanged is set to 1 (as an indication
55816** to the caller that the local paget cache is obsolete and needs to be
55817** flushed.)  When useWal==1, the wal-index header is assumed to already
55818** be loaded and the pChanged parameter is unused.
55819**
55820** The caller must set the cnt parameter to the number of prior calls to
55821** this routine during the current read attempt that returned WAL_RETRY.
55822** This routine will start taking more aggressive measures to clear the
55823** race conditions after multiple WAL_RETRY returns, and after an excessive
55824** number of errors will ultimately return SQLITE_PROTOCOL.  The
55825** SQLITE_PROTOCOL return indicates that some other process has gone rogue
55826** and is not honoring the locking protocol.  There is a vanishingly small
55827** chance that SQLITE_PROTOCOL could be returned because of a run of really
55828** bad luck when there is lots of contention for the wal-index, but that
55829** possibility is so small that it can be safely neglected, we believe.
55830**
55831** On success, this routine obtains a read lock on
55832** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
55833** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
55834** that means the Wal does not hold any read lock.  The reader must not
55835** access any database page that is modified by a WAL frame up to and
55836** including frame number aReadMark[pWal->readLock].  The reader will
55837** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
55838** Or if pWal->readLock==0, then the reader will ignore the WAL
55839** completely and get all content directly from the database file.
55840** If the useWal parameter is 1 then the WAL will never be ignored and
55841** this routine will always set pWal->readLock>0 on success.
55842** When the read transaction is completed, the caller must release the
55843** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
55844**
55845** This routine uses the nBackfill and aReadMark[] fields of the header
55846** to select a particular WAL_READ_LOCK() that strives to let the
55847** checkpoint process do as much work as possible.  This routine might
55848** update values of the aReadMark[] array in the header, but if it does
55849** so it takes care to hold an exclusive lock on the corresponding
55850** WAL_READ_LOCK() while changing values.
55851*/
55852static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
55853  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
55854  u32 mxReadMark;                 /* Largest aReadMark[] value */
55855  int mxI;                        /* Index of largest aReadMark[] value */
55856  int i;                          /* Loop counter */
55857  int rc = SQLITE_OK;             /* Return code  */
55858  u32 mxFrame;                    /* Wal frame to lock to */
55859
55860  assert( pWal->readLock<0 );     /* Not currently locked */
55861
55862  /* Take steps to avoid spinning forever if there is a protocol error.
55863  **
55864  ** Circumstances that cause a RETRY should only last for the briefest
55865  ** instances of time.  No I/O or other system calls are done while the
55866  ** locks are held, so the locks should not be held for very long. But
55867  ** if we are unlucky, another process that is holding a lock might get
55868  ** paged out or take a page-fault that is time-consuming to resolve,
55869  ** during the few nanoseconds that it is holding the lock.  In that case,
55870  ** it might take longer than normal for the lock to free.
55871  **
55872  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
55873  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
55874  ** is more of a scheduler yield than an actual delay.  But on the 10th
55875  ** an subsequent retries, the delays start becoming longer and longer,
55876  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
55877  ** The total delay time before giving up is less than 10 seconds.
55878  */
55879  if( cnt>5 ){
55880    int nDelay = 1;                      /* Pause time in microseconds */
55881    if( cnt>100 ){
55882      VVA_ONLY( pWal->lockError = 1; )
55883      return SQLITE_PROTOCOL;
55884    }
55885    if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
55886    sqlite3OsSleep(pWal->pVfs, nDelay);
55887  }
55888
55889  if( !useWal ){
55890    rc = walIndexReadHdr(pWal, pChanged);
55891    if( rc==SQLITE_BUSY ){
55892      /* If there is not a recovery running in another thread or process
55893      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
55894      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
55895      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
55896      ** would be technically correct.  But the race is benign since with
55897      ** WAL_RETRY this routine will be called again and will probably be
55898      ** right on the second iteration.
55899      */
55900      if( pWal->apWiData[0]==0 ){
55901        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
55902        ** We assume this is a transient condition, so return WAL_RETRY. The
55903        ** xShmMap() implementation used by the default unix and win32 VFS
55904        ** modules may return SQLITE_BUSY due to a race condition in the
55905        ** code that determines whether or not the shared-memory region
55906        ** must be zeroed before the requested page is returned.
55907        */
55908        rc = WAL_RETRY;
55909      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
55910        walUnlockShared(pWal, WAL_RECOVER_LOCK);
55911        rc = WAL_RETRY;
55912      }else if( rc==SQLITE_BUSY ){
55913        rc = SQLITE_BUSY_RECOVERY;
55914      }
55915    }
55916    if( rc!=SQLITE_OK ){
55917      return rc;
55918    }
55919  }
55920
55921  pInfo = walCkptInfo(pWal);
55922  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
55923#ifdef SQLITE_ENABLE_SNAPSHOT
55924   && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
55925     || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
55926#endif
55927  ){
55928    /* The WAL has been completely backfilled (or it is empty).
55929    ** and can be safely ignored.
55930    */
55931    rc = walLockShared(pWal, WAL_READ_LOCK(0));
55932    walShmBarrier(pWal);
55933    if( rc==SQLITE_OK ){
55934      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
55935        /* It is not safe to allow the reader to continue here if frames
55936        ** may have been appended to the log before READ_LOCK(0) was obtained.
55937        ** When holding READ_LOCK(0), the reader ignores the entire log file,
55938        ** which implies that the database file contains a trustworthy
55939        ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
55940        ** happening, this is usually correct.
55941        **
55942        ** However, if frames have been appended to the log (or if the log
55943        ** is wrapped and written for that matter) before the READ_LOCK(0)
55944        ** is obtained, that is not necessarily true. A checkpointer may
55945        ** have started to backfill the appended frames but crashed before
55946        ** it finished. Leaving a corrupt image in the database file.
55947        */
55948        walUnlockShared(pWal, WAL_READ_LOCK(0));
55949        return WAL_RETRY;
55950      }
55951      pWal->readLock = 0;
55952      return SQLITE_OK;
55953    }else if( rc!=SQLITE_BUSY ){
55954      return rc;
55955    }
55956  }
55957
55958  /* If we get this far, it means that the reader will want to use
55959  ** the WAL to get at content from recent commits.  The job now is
55960  ** to select one of the aReadMark[] entries that is closest to
55961  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
55962  */
55963  mxReadMark = 0;
55964  mxI = 0;
55965  mxFrame = pWal->hdr.mxFrame;
55966#ifdef SQLITE_ENABLE_SNAPSHOT
55967  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
55968    mxFrame = pWal->pSnapshot->mxFrame;
55969  }
55970#endif
55971  for(i=1; i<WAL_NREADER; i++){
55972    u32 thisMark = pInfo->aReadMark[i];
55973    if( mxReadMark<=thisMark && thisMark<=mxFrame ){
55974      assert( thisMark!=READMARK_NOT_USED );
55975      mxReadMark = thisMark;
55976      mxI = i;
55977    }
55978  }
55979  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
55980   && (mxReadMark<mxFrame || mxI==0)
55981  ){
55982    for(i=1; i<WAL_NREADER; i++){
55983      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
55984      if( rc==SQLITE_OK ){
55985        mxReadMark = pInfo->aReadMark[i] = mxFrame;
55986        mxI = i;
55987        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55988        break;
55989      }else if( rc!=SQLITE_BUSY ){
55990        return rc;
55991      }
55992    }
55993  }
55994  if( mxI==0 ){
55995    assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
55996    return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
55997  }
55998
55999  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
56000  if( rc ){
56001    return rc==SQLITE_BUSY ? WAL_RETRY : rc;
56002  }
56003  /* Now that the read-lock has been obtained, check that neither the
56004  ** value in the aReadMark[] array or the contents of the wal-index
56005  ** header have changed.
56006  **
56007  ** It is necessary to check that the wal-index header did not change
56008  ** between the time it was read and when the shared-lock was obtained
56009  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
56010  ** that the log file may have been wrapped by a writer, or that frames
56011  ** that occur later in the log than pWal->hdr.mxFrame may have been
56012  ** copied into the database by a checkpointer. If either of these things
56013  ** happened, then reading the database with the current value of
56014  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
56015  ** instead.
56016  **
56017  ** Before checking that the live wal-index header has not changed
56018  ** since it was read, set Wal.minFrame to the first frame in the wal
56019  ** file that has not yet been checkpointed. This client will not need
56020  ** to read any frames earlier than minFrame from the wal file - they
56021  ** can be safely read directly from the database file.
56022  **
56023  ** Because a ShmBarrier() call is made between taking the copy of
56024  ** nBackfill and checking that the wal-header in shared-memory still
56025  ** matches the one cached in pWal->hdr, it is guaranteed that the
56026  ** checkpointer that set nBackfill was not working with a wal-index
56027  ** header newer than that cached in pWal->hdr. If it were, that could
56028  ** cause a problem. The checkpointer could omit to checkpoint
56029  ** a version of page X that lies before pWal->minFrame (call that version
56030  ** A) on the basis that there is a newer version (version B) of the same
56031  ** page later in the wal file. But if version B happens to like past
56032  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
56033  ** that it can read version A from the database file. However, since
56034  ** we can guarantee that the checkpointer that set nBackfill could not
56035  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
56036  */
56037  pWal->minFrame = pInfo->nBackfill+1;
56038  walShmBarrier(pWal);
56039  if( pInfo->aReadMark[mxI]!=mxReadMark
56040   || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
56041  ){
56042    walUnlockShared(pWal, WAL_READ_LOCK(mxI));
56043    return WAL_RETRY;
56044  }else{
56045    assert( mxReadMark<=pWal->hdr.mxFrame );
56046    pWal->readLock = (i16)mxI;
56047  }
56048  return rc;
56049}
56050
56051/*
56052** Begin a read transaction on the database.
56053**
56054** This routine used to be called sqlite3OpenSnapshot() and with good reason:
56055** it takes a snapshot of the state of the WAL and wal-index for the current
56056** instant in time.  The current thread will continue to use this snapshot.
56057** Other threads might append new content to the WAL and wal-index but
56058** that extra content is ignored by the current thread.
56059**
56060** If the database contents have changes since the previous read
56061** transaction, then *pChanged is set to 1 before returning.  The
56062** Pager layer will use this to know that is cache is stale and
56063** needs to be flushed.
56064*/
56065SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
56066  int rc;                         /* Return code */
56067  int cnt = 0;                    /* Number of TryBeginRead attempts */
56068
56069#ifdef SQLITE_ENABLE_SNAPSHOT
56070  int bChanged = 0;
56071  WalIndexHdr *pSnapshot = pWal->pSnapshot;
56072  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56073    bChanged = 1;
56074  }
56075#endif
56076
56077  do{
56078    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
56079  }while( rc==WAL_RETRY );
56080  testcase( (rc&0xff)==SQLITE_BUSY );
56081  testcase( (rc&0xff)==SQLITE_IOERR );
56082  testcase( rc==SQLITE_PROTOCOL );
56083  testcase( rc==SQLITE_OK );
56084
56085#ifdef SQLITE_ENABLE_SNAPSHOT
56086  if( rc==SQLITE_OK ){
56087    if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56088      /* At this point the client has a lock on an aReadMark[] slot holding
56089      ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
56090      ** is populated with the wal-index header corresponding to the head
56091      ** of the wal file. Verify that pSnapshot is still valid before
56092      ** continuing.  Reasons why pSnapshot might no longer be valid:
56093      **
56094      **    (1)  The WAL file has been reset since the snapshot was taken.
56095      **         In this case, the salt will have changed.
56096      **
56097      **    (2)  A checkpoint as been attempted that wrote frames past
56098      **         pSnapshot->mxFrame into the database file.  Note that the
56099      **         checkpoint need not have completed for this to cause problems.
56100      */
56101      volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56102
56103      assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
56104      assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
56105
56106      /* It is possible that there is a checkpointer thread running
56107      ** concurrent with this code. If this is the case, it may be that the
56108      ** checkpointer has already determined that it will checkpoint
56109      ** snapshot X, where X is later in the wal file than pSnapshot, but
56110      ** has not yet set the pInfo->nBackfillAttempted variable to indicate
56111      ** its intent. To avoid the race condition this leads to, ensure that
56112      ** there is no checkpointer process by taking a shared CKPT lock
56113      ** before checking pInfo->nBackfillAttempted.  */
56114      rc = walLockShared(pWal, WAL_CKPT_LOCK);
56115
56116      if( rc==SQLITE_OK ){
56117        /* Check that the wal file has not been wrapped. Assuming that it has
56118        ** not, also check that no checkpointer has attempted to checkpoint any
56119        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
56120        ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
56121        ** with *pSnapshot and set *pChanged as appropriate for opening the
56122        ** snapshot.  */
56123        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
56124         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
56125        ){
56126          assert( pWal->readLock>0 );
56127          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
56128          *pChanged = bChanged;
56129        }else{
56130          rc = SQLITE_BUSY_SNAPSHOT;
56131        }
56132
56133        /* Release the shared CKPT lock obtained above. */
56134        walUnlockShared(pWal, WAL_CKPT_LOCK);
56135      }
56136
56137
56138      if( rc!=SQLITE_OK ){
56139        sqlite3WalEndReadTransaction(pWal);
56140      }
56141    }
56142  }
56143#endif
56144  return rc;
56145}
56146
56147/*
56148** Finish with a read transaction.  All this does is release the
56149** read-lock.
56150*/
56151SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
56152  sqlite3WalEndWriteTransaction(pWal);
56153  if( pWal->readLock>=0 ){
56154    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56155    pWal->readLock = -1;
56156  }
56157}
56158
56159/*
56160** Search the wal file for page pgno. If found, set *piRead to the frame that
56161** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
56162** to zero.
56163**
56164** Return SQLITE_OK if successful, or an error code if an error occurs. If an
56165** error does occur, the final value of *piRead is undefined.
56166*/
56167SQLITE_PRIVATE int sqlite3WalFindFrame(
56168  Wal *pWal,                      /* WAL handle */
56169  Pgno pgno,                      /* Database page number to read data for */
56170  u32 *piRead                     /* OUT: Frame number (or zero) */
56171){
56172  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
56173  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
56174  int iHash;                      /* Used to loop through N hash tables */
56175  int iMinHash;
56176
56177  /* This routine is only be called from within a read transaction. */
56178  assert( pWal->readLock>=0 || pWal->lockError );
56179
56180  /* If the "last page" field of the wal-index header snapshot is 0, then
56181  ** no data will be read from the wal under any circumstances. Return early
56182  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
56183  ** then the WAL is ignored by the reader so return early, as if the
56184  ** WAL were empty.
56185  */
56186  if( iLast==0 || pWal->readLock==0 ){
56187    *piRead = 0;
56188    return SQLITE_OK;
56189  }
56190
56191  /* Search the hash table or tables for an entry matching page number
56192  ** pgno. Each iteration of the following for() loop searches one
56193  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
56194  **
56195  ** This code might run concurrently to the code in walIndexAppend()
56196  ** that adds entries to the wal-index (and possibly to this hash
56197  ** table). This means the value just read from the hash
56198  ** slot (aHash[iKey]) may have been added before or after the
56199  ** current read transaction was opened. Values added after the
56200  ** read transaction was opened may have been written incorrectly -
56201  ** i.e. these slots may contain garbage data. However, we assume
56202  ** that any slots written before the current read transaction was
56203  ** opened remain unmodified.
56204  **
56205  ** For the reasons above, the if(...) condition featured in the inner
56206  ** loop of the following block is more stringent that would be required
56207  ** if we had exclusive access to the hash-table:
56208  **
56209  **   (aPgno[iFrame]==pgno):
56210  **     This condition filters out normal hash-table collisions.
56211  **
56212  **   (iFrame<=iLast):
56213  **     This condition filters out entries that were added to the hash
56214  **     table after the current read-transaction had started.
56215  */
56216  iMinHash = walFramePage(pWal->minFrame);
56217  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
56218    volatile ht_slot *aHash;      /* Pointer to hash table */
56219    volatile u32 *aPgno;          /* Pointer to array of page numbers */
56220    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
56221    int iKey;                     /* Hash slot index */
56222    int nCollide;                 /* Number of hash collisions remaining */
56223    int rc;                       /* Error code */
56224
56225    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
56226    if( rc!=SQLITE_OK ){
56227      return rc;
56228    }
56229    nCollide = HASHTABLE_NSLOT;
56230    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
56231      u32 iFrame = aHash[iKey] + iZero;
56232      if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
56233        assert( iFrame>iRead || CORRUPT_DB );
56234        iRead = iFrame;
56235      }
56236      if( (nCollide--)==0 ){
56237        return SQLITE_CORRUPT_BKPT;
56238      }
56239    }
56240  }
56241
56242#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56243  /* If expensive assert() statements are available, do a linear search
56244  ** of the wal-index file content. Make sure the results agree with the
56245  ** result obtained using the hash indexes above.  */
56246  {
56247    u32 iRead2 = 0;
56248    u32 iTest;
56249    assert( pWal->minFrame>0 );
56250    for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
56251      if( walFramePgno(pWal, iTest)==pgno ){
56252        iRead2 = iTest;
56253        break;
56254      }
56255    }
56256    assert( iRead==iRead2 );
56257  }
56258#endif
56259
56260  *piRead = iRead;
56261  return SQLITE_OK;
56262}
56263
56264/*
56265** Read the contents of frame iRead from the wal file into buffer pOut
56266** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
56267** error code otherwise.
56268*/
56269SQLITE_PRIVATE int sqlite3WalReadFrame(
56270  Wal *pWal,                      /* WAL handle */
56271  u32 iRead,                      /* Frame to read */
56272  int nOut,                       /* Size of buffer pOut in bytes */
56273  u8 *pOut                        /* Buffer to write page data to */
56274){
56275  int sz;
56276  i64 iOffset;
56277  sz = pWal->hdr.szPage;
56278  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
56279  testcase( sz<=32768 );
56280  testcase( sz>=65536 );
56281  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
56282  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
56283  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
56284}
56285
56286/*
56287** Return the size of the database in pages (or zero, if unknown).
56288*/
56289SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
56290  if( pWal && ALWAYS(pWal->readLock>=0) ){
56291    return pWal->hdr.nPage;
56292  }
56293  return 0;
56294}
56295
56296
56297/*
56298** This function starts a write transaction on the WAL.
56299**
56300** A read transaction must have already been started by a prior call
56301** to sqlite3WalBeginReadTransaction().
56302**
56303** If another thread or process has written into the database since
56304** the read transaction was started, then it is not possible for this
56305** thread to write as doing so would cause a fork.  So this routine
56306** returns SQLITE_BUSY in that case and no write transaction is started.
56307**
56308** There can only be a single writer active at a time.
56309*/
56310SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
56311  int rc;
56312
56313  /* Cannot start a write transaction without first holding a read
56314  ** transaction. */
56315  assert( pWal->readLock>=0 );
56316  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
56317
56318  if( pWal->readOnly ){
56319    return SQLITE_READONLY;
56320  }
56321
56322  /* Only one writer allowed at a time.  Get the write lock.  Return
56323  ** SQLITE_BUSY if unable.
56324  */
56325  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
56326  if( rc ){
56327    return rc;
56328  }
56329  pWal->writeLock = 1;
56330
56331  /* If another connection has written to the database file since the
56332  ** time the read transaction on this connection was started, then
56333  ** the write is disallowed.
56334  */
56335  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
56336    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56337    pWal->writeLock = 0;
56338    rc = SQLITE_BUSY_SNAPSHOT;
56339  }
56340
56341  return rc;
56342}
56343
56344/*
56345** End a write transaction.  The commit has already been done.  This
56346** routine merely releases the lock.
56347*/
56348SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
56349  if( pWal->writeLock ){
56350    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56351    pWal->writeLock = 0;
56352    pWal->iReCksum = 0;
56353    pWal->truncateOnCommit = 0;
56354  }
56355  return SQLITE_OK;
56356}
56357
56358/*
56359** If any data has been written (but not committed) to the log file, this
56360** function moves the write-pointer back to the start of the transaction.
56361**
56362** Additionally, the callback function is invoked for each frame written
56363** to the WAL since the start of the transaction. If the callback returns
56364** other than SQLITE_OK, it is not invoked again and the error code is
56365** returned to the caller.
56366**
56367** Otherwise, if the callback function does not return an error, this
56368** function returns SQLITE_OK.
56369*/
56370SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
56371  int rc = SQLITE_OK;
56372  if( ALWAYS(pWal->writeLock) ){
56373    Pgno iMax = pWal->hdr.mxFrame;
56374    Pgno iFrame;
56375
56376    /* Restore the clients cache of the wal-index header to the state it
56377    ** was in before the client began writing to the database.
56378    */
56379    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
56380
56381    for(iFrame=pWal->hdr.mxFrame+1;
56382        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
56383        iFrame++
56384    ){
56385      /* This call cannot fail. Unless the page for which the page number
56386      ** is passed as the second argument is (a) in the cache and
56387      ** (b) has an outstanding reference, then xUndo is either a no-op
56388      ** (if (a) is false) or simply expels the page from the cache (if (b)
56389      ** is false).
56390      **
56391      ** If the upper layer is doing a rollback, it is guaranteed that there
56392      ** are no outstanding references to any page other than page 1. And
56393      ** page 1 is never written to the log until the transaction is
56394      ** committed. As a result, the call to xUndo may not fail.
56395      */
56396      assert( walFramePgno(pWal, iFrame)!=1 );
56397      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
56398    }
56399    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
56400  }
56401  return rc;
56402}
56403
56404/*
56405** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
56406** values. This function populates the array with values required to
56407** "rollback" the write position of the WAL handle back to the current
56408** point in the event of a savepoint rollback (via WalSavepointUndo()).
56409*/
56410SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
56411  assert( pWal->writeLock );
56412  aWalData[0] = pWal->hdr.mxFrame;
56413  aWalData[1] = pWal->hdr.aFrameCksum[0];
56414  aWalData[2] = pWal->hdr.aFrameCksum[1];
56415  aWalData[3] = pWal->nCkpt;
56416}
56417
56418/*
56419** Move the write position of the WAL back to the point identified by
56420** the values in the aWalData[] array. aWalData must point to an array
56421** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
56422** by a call to WalSavepoint().
56423*/
56424SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
56425  int rc = SQLITE_OK;
56426
56427  assert( pWal->writeLock );
56428  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
56429
56430  if( aWalData[3]!=pWal->nCkpt ){
56431    /* This savepoint was opened immediately after the write-transaction
56432    ** was started. Right after that, the writer decided to wrap around
56433    ** to the start of the log. Update the savepoint values to match.
56434    */
56435    aWalData[0] = 0;
56436    aWalData[3] = pWal->nCkpt;
56437  }
56438
56439  if( aWalData[0]<pWal->hdr.mxFrame ){
56440    pWal->hdr.mxFrame = aWalData[0];
56441    pWal->hdr.aFrameCksum[0] = aWalData[1];
56442    pWal->hdr.aFrameCksum[1] = aWalData[2];
56443    walCleanupHash(pWal);
56444  }
56445
56446  return rc;
56447}
56448
56449/*
56450** This function is called just before writing a set of frames to the log
56451** file (see sqlite3WalFrames()). It checks to see if, instead of appending
56452** to the current log file, it is possible to overwrite the start of the
56453** existing log file with the new frames (i.e. "reset" the log). If so,
56454** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
56455** unchanged.
56456**
56457** SQLITE_OK is returned if no error is encountered (regardless of whether
56458** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
56459** if an error occurs.
56460*/
56461static int walRestartLog(Wal *pWal){
56462  int rc = SQLITE_OK;
56463  int cnt;
56464
56465  if( pWal->readLock==0 ){
56466    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56467    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56468    if( pInfo->nBackfill>0 ){
56469      u32 salt1;
56470      sqlite3_randomness(4, &salt1);
56471      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56472      if( rc==SQLITE_OK ){
56473        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
56474        ** readers are currently using the WAL), then the transactions
56475        ** frames will overwrite the start of the existing log. Update the
56476        ** wal-index header to reflect this.
56477        **
56478        ** In theory it would be Ok to update the cache of the header only
56479        ** at this point. But updating the actual wal-index header is also
56480        ** safe and means there is no special case for sqlite3WalUndo()
56481        ** to handle if this transaction is rolled back.  */
56482        walRestartHdr(pWal, salt1);
56483        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56484      }else if( rc!=SQLITE_BUSY ){
56485        return rc;
56486      }
56487    }
56488    walUnlockShared(pWal, WAL_READ_LOCK(0));
56489    pWal->readLock = -1;
56490    cnt = 0;
56491    do{
56492      int notUsed;
56493      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
56494    }while( rc==WAL_RETRY );
56495    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
56496    testcase( (rc&0xff)==SQLITE_IOERR );
56497    testcase( rc==SQLITE_PROTOCOL );
56498    testcase( rc==SQLITE_OK );
56499  }
56500  return rc;
56501}
56502
56503/*
56504** Information about the current state of the WAL file and where
56505** the next fsync should occur - passed from sqlite3WalFrames() into
56506** walWriteToLog().
56507*/
56508typedef struct WalWriter {
56509  Wal *pWal;                   /* The complete WAL information */
56510  sqlite3_file *pFd;           /* The WAL file to which we write */
56511  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
56512  int syncFlags;               /* Flags for the fsync */
56513  int szPage;                  /* Size of one page */
56514} WalWriter;
56515
56516/*
56517** Write iAmt bytes of content into the WAL file beginning at iOffset.
56518** Do a sync when crossing the p->iSyncPoint boundary.
56519**
56520** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
56521** first write the part before iSyncPoint, then sync, then write the
56522** rest.
56523*/
56524static int walWriteToLog(
56525  WalWriter *p,              /* WAL to write to */
56526  void *pContent,            /* Content to be written */
56527  int iAmt,                  /* Number of bytes to write */
56528  sqlite3_int64 iOffset      /* Start writing at this offset */
56529){
56530  int rc;
56531  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
56532    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
56533    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
56534    if( rc ) return rc;
56535    iOffset += iFirstAmt;
56536    iAmt -= iFirstAmt;
56537    pContent = (void*)(iFirstAmt + (char*)pContent);
56538    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
56539    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
56540    if( iAmt==0 || rc ) return rc;
56541  }
56542  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
56543  return rc;
56544}
56545
56546/*
56547** Write out a single frame of the WAL
56548*/
56549static int walWriteOneFrame(
56550  WalWriter *p,               /* Where to write the frame */
56551  PgHdr *pPage,               /* The page of the frame to be written */
56552  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
56553  sqlite3_int64 iOffset       /* Byte offset at which to write */
56554){
56555  int rc;                         /* Result code from subfunctions */
56556  void *pData;                    /* Data actually written */
56557  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
56558#if defined(SQLITE_HAS_CODEC)
56559  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
56560#else
56561  pData = pPage->pData;
56562#endif
56563  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
56564  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
56565  if( rc ) return rc;
56566  /* Write the page data */
56567  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
56568  return rc;
56569}
56570
56571/*
56572** This function is called as part of committing a transaction within which
56573** one or more frames have been overwritten. It updates the checksums for
56574** all frames written to the wal file by the current transaction starting
56575** with the earliest to have been overwritten.
56576**
56577** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
56578*/
56579static int walRewriteChecksums(Wal *pWal, u32 iLast){
56580  const int szPage = pWal->szPage;/* Database page size */
56581  int rc = SQLITE_OK;             /* Return code */
56582  u8 *aBuf;                       /* Buffer to load data from wal file into */
56583  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
56584  u32 iRead;                      /* Next frame to read from wal file */
56585  i64 iCksumOff;
56586
56587  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
56588  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
56589
56590  /* Find the checksum values to use as input for the recalculating the
56591  ** first checksum. If the first frame is frame 1 (implying that the current
56592  ** transaction restarted the wal file), these values must be read from the
56593  ** wal-file header. Otherwise, read them from the frame header of the
56594  ** previous frame.  */
56595  assert( pWal->iReCksum>0 );
56596  if( pWal->iReCksum==1 ){
56597    iCksumOff = 24;
56598  }else{
56599    iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
56600  }
56601  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
56602  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
56603  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
56604
56605  iRead = pWal->iReCksum;
56606  pWal->iReCksum = 0;
56607  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
56608    i64 iOff = walFrameOffset(iRead, szPage);
56609    rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
56610    if( rc==SQLITE_OK ){
56611      u32 iPgno, nDbSize;
56612      iPgno = sqlite3Get4byte(aBuf);
56613      nDbSize = sqlite3Get4byte(&aBuf[4]);
56614
56615      walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
56616      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
56617    }
56618  }
56619
56620  sqlite3_free(aBuf);
56621  return rc;
56622}
56623
56624/*
56625** Write a set of frames to the log. The caller must hold the write-lock
56626** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
56627*/
56628SQLITE_PRIVATE int sqlite3WalFrames(
56629  Wal *pWal,                      /* Wal handle to write to */
56630  int szPage,                     /* Database page-size in bytes */
56631  PgHdr *pList,                   /* List of dirty pages to write */
56632  Pgno nTruncate,                 /* Database size after this commit */
56633  int isCommit,                   /* True if this is a commit */
56634  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
56635){
56636  int rc;                         /* Used to catch return codes */
56637  u32 iFrame;                     /* Next frame address */
56638  PgHdr *p;                       /* Iterator to run through pList with. */
56639  PgHdr *pLast = 0;               /* Last frame in list */
56640  int nExtra = 0;                 /* Number of extra copies of last page */
56641  int szFrame;                    /* The size of a single frame */
56642  i64 iOffset;                    /* Next byte to write in WAL file */
56643  WalWriter w;                    /* The writer */
56644  u32 iFirst = 0;                 /* First frame that may be overwritten */
56645  WalIndexHdr *pLive;             /* Pointer to shared header */
56646
56647  assert( pList );
56648  assert( pWal->writeLock );
56649
56650  /* If this frame set completes a transaction, then nTruncate>0.  If
56651  ** nTruncate==0 then this frame set does not complete the transaction. */
56652  assert( (isCommit!=0)==(nTruncate!=0) );
56653
56654#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
56655  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
56656    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
56657              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
56658  }
56659#endif
56660
56661  pLive = (WalIndexHdr*)walIndexHdr(pWal);
56662  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
56663    iFirst = pLive->mxFrame+1;
56664  }
56665
56666  /* See if it is possible to write these frames into the start of the
56667  ** log file, instead of appending to it at pWal->hdr.mxFrame.
56668  */
56669  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
56670    return rc;
56671  }
56672
56673  /* If this is the first frame written into the log, write the WAL
56674  ** header to the start of the WAL file. See comments at the top of
56675  ** this source file for a description of the WAL header format.
56676  */
56677  iFrame = pWal->hdr.mxFrame;
56678  if( iFrame==0 ){
56679    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
56680    u32 aCksum[2];                /* Checksum for wal-header */
56681
56682    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
56683    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
56684    sqlite3Put4byte(&aWalHdr[8], szPage);
56685    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
56686    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
56687    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
56688    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
56689    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
56690    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
56691
56692    pWal->szPage = szPage;
56693    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
56694    pWal->hdr.aFrameCksum[0] = aCksum[0];
56695    pWal->hdr.aFrameCksum[1] = aCksum[1];
56696    pWal->truncateOnCommit = 1;
56697
56698    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
56699    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
56700    if( rc!=SQLITE_OK ){
56701      return rc;
56702    }
56703
56704    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
56705    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
56706    ** an out-of-order write following a WAL restart could result in
56707    ** database corruption.  See the ticket:
56708    **
56709    **     http://localhost:591/sqlite/info/ff5be73dee
56710    */
56711    if( pWal->syncHeader && sync_flags ){
56712      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
56713      if( rc ) return rc;
56714    }
56715  }
56716  assert( (int)pWal->szPage==szPage );
56717
56718  /* Setup information needed to write frames into the WAL */
56719  w.pWal = pWal;
56720  w.pFd = pWal->pWalFd;
56721  w.iSyncPoint = 0;
56722  w.syncFlags = sync_flags;
56723  w.szPage = szPage;
56724  iOffset = walFrameOffset(iFrame+1, szPage);
56725  szFrame = szPage + WAL_FRAME_HDRSIZE;
56726
56727  /* Write all frames into the log file exactly once */
56728  for(p=pList; p; p=p->pDirty){
56729    int nDbSize;   /* 0 normally.  Positive == commit flag */
56730
56731    /* Check if this page has already been written into the wal file by
56732    ** the current transaction. If so, overwrite the existing frame and
56733    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
56734    ** checksums must be recomputed when the transaction is committed.  */
56735    if( iFirst && (p->pDirty || isCommit==0) ){
56736      u32 iWrite = 0;
56737      VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
56738      assert( rc==SQLITE_OK || iWrite==0 );
56739      if( iWrite>=iFirst ){
56740        i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
56741        void *pData;
56742        if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
56743          pWal->iReCksum = iWrite;
56744        }
56745#if defined(SQLITE_HAS_CODEC)
56746        if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
56747#else
56748        pData = p->pData;
56749#endif
56750        rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
56751        if( rc ) return rc;
56752        p->flags &= ~PGHDR_WAL_APPEND;
56753        continue;
56754      }
56755    }
56756
56757    iFrame++;
56758    assert( iOffset==walFrameOffset(iFrame, szPage) );
56759    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
56760    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
56761    if( rc ) return rc;
56762    pLast = p;
56763    iOffset += szFrame;
56764    p->flags |= PGHDR_WAL_APPEND;
56765  }
56766
56767  /* Recalculate checksums within the wal file if required. */
56768  if( isCommit && pWal->iReCksum ){
56769    rc = walRewriteChecksums(pWal, iFrame);
56770    if( rc ) return rc;
56771  }
56772
56773  /* If this is the end of a transaction, then we might need to pad
56774  ** the transaction and/or sync the WAL file.
56775  **
56776  ** Padding and syncing only occur if this set of frames complete a
56777  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
56778  ** or synchronous==OFF, then no padding or syncing are needed.
56779  **
56780  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
56781  ** needed and only the sync is done.  If padding is needed, then the
56782  ** final frame is repeated (with its commit mark) until the next sector
56783  ** boundary is crossed.  Only the part of the WAL prior to the last
56784  ** sector boundary is synced; the part of the last frame that extends
56785  ** past the sector boundary is written after the sync.
56786  */
56787  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
56788    int bSync = 1;
56789    if( pWal->padToSectorBoundary ){
56790      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
56791      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
56792      bSync = (w.iSyncPoint==iOffset);
56793      testcase( bSync );
56794      while( iOffset<w.iSyncPoint ){
56795        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
56796        if( rc ) return rc;
56797        iOffset += szFrame;
56798        nExtra++;
56799      }
56800    }
56801    if( bSync ){
56802      assert( rc==SQLITE_OK );
56803      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
56804    }
56805  }
56806
56807  /* If this frame set completes the first transaction in the WAL and
56808  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
56809  ** journal size limit, if possible.
56810  */
56811  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
56812    i64 sz = pWal->mxWalSize;
56813    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
56814      sz = walFrameOffset(iFrame+nExtra+1, szPage);
56815    }
56816    walLimitSize(pWal, sz);
56817    pWal->truncateOnCommit = 0;
56818  }
56819
56820  /* Append data to the wal-index. It is not necessary to lock the
56821  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
56822  ** guarantees that there are no other writers, and no data that may
56823  ** be in use by existing readers is being overwritten.
56824  */
56825  iFrame = pWal->hdr.mxFrame;
56826  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
56827    if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
56828    iFrame++;
56829    rc = walIndexAppend(pWal, iFrame, p->pgno);
56830  }
56831  while( rc==SQLITE_OK && nExtra>0 ){
56832    iFrame++;
56833    nExtra--;
56834    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
56835  }
56836
56837  if( rc==SQLITE_OK ){
56838    /* Update the private copy of the header. */
56839    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56840    testcase( szPage<=32768 );
56841    testcase( szPage>=65536 );
56842    pWal->hdr.mxFrame = iFrame;
56843    if( isCommit ){
56844      pWal->hdr.iChange++;
56845      pWal->hdr.nPage = nTruncate;
56846    }
56847    /* If this is a commit, update the wal-index header too. */
56848    if( isCommit ){
56849      walIndexWriteHdr(pWal);
56850      pWal->iCallback = iFrame;
56851    }
56852  }
56853
56854  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
56855  return rc;
56856}
56857
56858/*
56859** This routine is called to implement sqlite3_wal_checkpoint() and
56860** related interfaces.
56861**
56862** Obtain a CHECKPOINT lock and then backfill as much information as
56863** we can from WAL into the database.
56864**
56865** If parameter xBusy is not NULL, it is a pointer to a busy-handler
56866** callback. In this case this function runs a blocking checkpoint.
56867*/
56868SQLITE_PRIVATE int sqlite3WalCheckpoint(
56869  Wal *pWal,                      /* Wal connection */
56870  int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
56871  int (*xBusy)(void*),            /* Function to call when busy */
56872  void *pBusyArg,                 /* Context argument for xBusyHandler */
56873  int sync_flags,                 /* Flags to sync db file with (or 0) */
56874  int nBuf,                       /* Size of temporary buffer */
56875  u8 *zBuf,                       /* Temporary buffer to use */
56876  int *pnLog,                     /* OUT: Number of frames in WAL */
56877  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
56878){
56879  int rc;                         /* Return code */
56880  int isChanged = 0;              /* True if a new wal-index header is loaded */
56881  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
56882  int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
56883
56884  assert( pWal->ckptLock==0 );
56885  assert( pWal->writeLock==0 );
56886
56887  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56888  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56889  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56890
56891  if( pWal->readOnly ) return SQLITE_READONLY;
56892  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
56893
56894  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
56895  ** "checkpoint" lock on the database file. */
56896  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
56897  if( rc ){
56898    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
56899    ** checkpoint operation at the same time, the lock cannot be obtained and
56900    ** SQLITE_BUSY is returned.
56901    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
56902    ** it will not be invoked in this case.
56903    */
56904    testcase( rc==SQLITE_BUSY );
56905    testcase( xBusy!=0 );
56906    return rc;
56907  }
56908  pWal->ckptLock = 1;
56909
56910  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
56911  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
56912  ** file.
56913  **
56914  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
56915  ** immediately, and a busy-handler is configured, it is invoked and the
56916  ** writer lock retried until either the busy-handler returns 0 or the
56917  ** lock is successfully obtained.
56918  */
56919  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56920    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
56921    if( rc==SQLITE_OK ){
56922      pWal->writeLock = 1;
56923    }else if( rc==SQLITE_BUSY ){
56924      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
56925      xBusy2 = 0;
56926      rc = SQLITE_OK;
56927    }
56928  }
56929
56930  /* Read the wal-index header. */
56931  if( rc==SQLITE_OK ){
56932    rc = walIndexReadHdr(pWal, &isChanged);
56933    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
56934      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
56935    }
56936  }
56937
56938  /* Copy data from the log to the database file. */
56939  if( rc==SQLITE_OK ){
56940
56941    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
56942      rc = SQLITE_CORRUPT_BKPT;
56943    }else{
56944      rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
56945    }
56946
56947    /* If no error occurred, set the output variables. */
56948    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
56949      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
56950      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
56951    }
56952  }
56953
56954  if( isChanged ){
56955    /* If a new wal-index header was loaded before the checkpoint was
56956    ** performed, then the pager-cache associated with pWal is now
56957    ** out of date. So zero the cached wal-index header to ensure that
56958    ** next time the pager opens a snapshot on this database it knows that
56959    ** the cache needs to be reset.
56960    */
56961    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
56962  }
56963
56964  /* Release the locks. */
56965  sqlite3WalEndWriteTransaction(pWal);
56966  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
56967  pWal->ckptLock = 0;
56968  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
56969  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
56970}
56971
56972/* Return the value to pass to a sqlite3_wal_hook callback, the
56973** number of frames in the WAL at the point of the last commit since
56974** sqlite3WalCallback() was called.  If no commits have occurred since
56975** the last call, then return 0.
56976*/
56977SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
56978  u32 ret = 0;
56979  if( pWal ){
56980    ret = pWal->iCallback;
56981    pWal->iCallback = 0;
56982  }
56983  return (int)ret;
56984}
56985
56986/*
56987** This function is called to change the WAL subsystem into or out
56988** of locking_mode=EXCLUSIVE.
56989**
56990** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
56991** into locking_mode=NORMAL.  This means that we must acquire a lock
56992** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
56993** or if the acquisition of the lock fails, then return 0.  If the
56994** transition out of exclusive-mode is successful, return 1.  This
56995** operation must occur while the pager is still holding the exclusive
56996** lock on the main database file.
56997**
56998** If op is one, then change from locking_mode=NORMAL into
56999** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
57000** be released.  Return 1 if the transition is made and 0 if the
57001** WAL is already in exclusive-locking mode - meaning that this
57002** routine is a no-op.  The pager must already hold the exclusive lock
57003** on the main database file before invoking this operation.
57004**
57005** If op is negative, then do a dry-run of the op==1 case but do
57006** not actually change anything. The pager uses this to see if it
57007** should acquire the database exclusive lock prior to invoking
57008** the op==1 case.
57009*/
57010SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
57011  int rc;
57012  assert( pWal->writeLock==0 );
57013  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
57014
57015  /* pWal->readLock is usually set, but might be -1 if there was a
57016  ** prior error while attempting to acquire are read-lock. This cannot
57017  ** happen if the connection is actually in exclusive mode (as no xShmLock
57018  ** locks are taken in this case). Nor should the pager attempt to
57019  ** upgrade to exclusive-mode following such an error.
57020  */
57021  assert( pWal->readLock>=0 || pWal->lockError );
57022  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
57023
57024  if( op==0 ){
57025    if( pWal->exclusiveMode ){
57026      pWal->exclusiveMode = 0;
57027      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
57028        pWal->exclusiveMode = 1;
57029      }
57030      rc = pWal->exclusiveMode==0;
57031    }else{
57032      /* Already in locking_mode=NORMAL */
57033      rc = 0;
57034    }
57035  }else if( op>0 ){
57036    assert( pWal->exclusiveMode==0 );
57037    assert( pWal->readLock>=0 );
57038    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57039    pWal->exclusiveMode = 1;
57040    rc = 1;
57041  }else{
57042    rc = pWal->exclusiveMode==0;
57043  }
57044  return rc;
57045}
57046
57047/*
57048** Return true if the argument is non-NULL and the WAL module is using
57049** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57050** WAL module is using shared-memory, return false.
57051*/
57052SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
57053  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
57054}
57055
57056#ifdef SQLITE_ENABLE_SNAPSHOT
57057/* Create a snapshot object.  The content of a snapshot is opaque to
57058** every other subsystem, so the WAL module can put whatever it needs
57059** in the object.
57060*/
57061SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
57062  int rc = SQLITE_OK;
57063  WalIndexHdr *pRet;
57064
57065  assert( pWal->readLock>=0 && pWal->writeLock==0 );
57066
57067  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
57068  if( pRet==0 ){
57069    rc = SQLITE_NOMEM_BKPT;
57070  }else{
57071    memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
57072    *ppSnapshot = (sqlite3_snapshot*)pRet;
57073  }
57074
57075  return rc;
57076}
57077
57078/* Try to open on pSnapshot when the next read-transaction starts
57079*/
57080SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
57081  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
57082}
57083
57084/*
57085** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
57086** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
57087*/
57088SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
57089  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
57090  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
57091
57092  /* aSalt[0] is a copy of the value stored in the wal file header. It
57093  ** is incremented each time the wal file is restarted.  */
57094  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
57095  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
57096  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
57097  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
57098  return 0;
57099}
57100#endif /* SQLITE_ENABLE_SNAPSHOT */
57101
57102#ifdef SQLITE_ENABLE_ZIPVFS
57103/*
57104** If the argument is not NULL, it points to a Wal object that holds a
57105** read-lock. This function returns the database page-size if it is known,
57106** or zero if it is not (or if pWal is NULL).
57107*/
57108SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
57109  assert( pWal==0 || pWal->readLock>=0 );
57110  return (pWal ? pWal->szPage : 0);
57111}
57112#endif
57113
57114/* Return the sqlite3_file object for the WAL file
57115*/
57116SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
57117  return pWal->pWalFd;
57118}
57119
57120#endif /* #ifndef SQLITE_OMIT_WAL */
57121
57122/************** End of wal.c *************************************************/
57123/************** Begin file btmutex.c *****************************************/
57124/*
57125** 2007 August 27
57126**
57127** The author disclaims copyright to this source code.  In place of
57128** a legal notice, here is a blessing:
57129**
57130**    May you do good and not evil.
57131**    May you find forgiveness for yourself and forgive others.
57132**    May you share freely, never taking more than you give.
57133**
57134*************************************************************************
57135**
57136** This file contains code used to implement mutexes on Btree objects.
57137** This code really belongs in btree.c.  But btree.c is getting too
57138** big and we want to break it down some.  This packaged seemed like
57139** a good breakout.
57140*/
57141/************** Include btreeInt.h in the middle of btmutex.c ****************/
57142/************** Begin file btreeInt.h ****************************************/
57143/*
57144** 2004 April 6
57145**
57146** The author disclaims copyright to this source code.  In place of
57147** a legal notice, here is a blessing:
57148**
57149**    May you do good and not evil.
57150**    May you find forgiveness for yourself and forgive others.
57151**    May you share freely, never taking more than you give.
57152**
57153*************************************************************************
57154** This file implements an external (disk-based) database using BTrees.
57155** For a detailed discussion of BTrees, refer to
57156**
57157**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
57158**     "Sorting And Searching", pages 473-480. Addison-Wesley
57159**     Publishing Company, Reading, Massachusetts.
57160**
57161** The basic idea is that each page of the file contains N database
57162** entries and N+1 pointers to subpages.
57163**
57164**   ----------------------------------------------------------------
57165**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
57166**   ----------------------------------------------------------------
57167**
57168** All of the keys on the page that Ptr(0) points to have values less
57169** than Key(0).  All of the keys on page Ptr(1) and its subpages have
57170** values greater than Key(0) and less than Key(1).  All of the keys
57171** on Ptr(N) and its subpages have values greater than Key(N-1).  And
57172** so forth.
57173**
57174** Finding a particular key requires reading O(log(M)) pages from the
57175** disk where M is the number of entries in the tree.
57176**
57177** In this implementation, a single file can hold one or more separate
57178** BTrees.  Each BTree is identified by the index of its root page.  The
57179** key and data for any entry are combined to form the "payload".  A
57180** fixed amount of payload can be carried directly on the database
57181** page.  If the payload is larger than the preset amount then surplus
57182** bytes are stored on overflow pages.  The payload for an entry
57183** and the preceding pointer are combined to form a "Cell".  Each
57184** page has a small header which contains the Ptr(N) pointer and other
57185** information such as the size of key and data.
57186**
57187** FORMAT DETAILS
57188**
57189** The file is divided into pages.  The first page is called page 1,
57190** the second is page 2, and so forth.  A page number of zero indicates
57191** "no such page".  The page size can be any power of 2 between 512 and 65536.
57192** Each page can be either a btree page, a freelist page, an overflow
57193** page, or a pointer-map page.
57194**
57195** The first page is always a btree page.  The first 100 bytes of the first
57196** page contain a special header (the "file header") that describes the file.
57197** The format of the file header is as follows:
57198**
57199**   OFFSET   SIZE    DESCRIPTION
57200**      0      16     Header string: "SQLite format 3\000"
57201**     16       2     Page size in bytes.  (1 means 65536)
57202**     18       1     File format write version
57203**     19       1     File format read version
57204**     20       1     Bytes of unused space at the end of each page
57205**     21       1     Max embedded payload fraction (must be 64)
57206**     22       1     Min embedded payload fraction (must be 32)
57207**     23       1     Min leaf payload fraction (must be 32)
57208**     24       4     File change counter
57209**     28       4     Reserved for future use
57210**     32       4     First freelist page
57211**     36       4     Number of freelist pages in the file
57212**     40      60     15 4-byte meta values passed to higher layers
57213**
57214**     40       4     Schema cookie
57215**     44       4     File format of schema layer
57216**     48       4     Size of page cache
57217**     52       4     Largest root-page (auto/incr_vacuum)
57218**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
57219**     60       4     User version
57220**     64       4     Incremental vacuum mode
57221**     68       4     Application-ID
57222**     72      20     unused
57223**     92       4     The version-valid-for number
57224**     96       4     SQLITE_VERSION_NUMBER
57225**
57226** All of the integer values are big-endian (most significant byte first).
57227**
57228** The file change counter is incremented when the database is changed
57229** This counter allows other processes to know when the file has changed
57230** and thus when they need to flush their cache.
57231**
57232** The max embedded payload fraction is the amount of the total usable
57233** space in a page that can be consumed by a single cell for standard
57234** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
57235** is to limit the maximum cell size so that at least 4 cells will fit
57236** on one page.  Thus the default max embedded payload fraction is 64.
57237**
57238** If the payload for a cell is larger than the max payload, then extra
57239** payload is spilled to overflow pages.  Once an overflow page is allocated,
57240** as many bytes as possible are moved into the overflow pages without letting
57241** the cell size drop below the min embedded payload fraction.
57242**
57243** The min leaf payload fraction is like the min embedded payload fraction
57244** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
57245** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
57246** not specified in the header.
57247**
57248** Each btree pages is divided into three sections:  The header, the
57249** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
57250** file header that occurs before the page header.
57251**
57252**      |----------------|
57253**      | file header    |   100 bytes.  Page 1 only.
57254**      |----------------|
57255**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
57256**      |----------------|
57257**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
57258**      | array          |   |  Grows downward
57259**      |                |   v
57260**      |----------------|
57261**      | unallocated    |
57262**      | space          |
57263**      |----------------|   ^  Grows upwards
57264**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
57265**      | area           |   |  and free space fragments.
57266**      |----------------|
57267**
57268** The page headers looks like this:
57269**
57270**   OFFSET   SIZE     DESCRIPTION
57271**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
57272**      1       2      byte offset to the first freeblock
57273**      3       2      number of cells on this page
57274**      5       2      first byte of the cell content area
57275**      7       1      number of fragmented free bytes
57276**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
57277**
57278** The flags define the format of this btree page.  The leaf flag means that
57279** this page has no children.  The zerodata flag means that this page carries
57280** only keys and no data.  The intkey flag means that the key is an integer
57281** which is stored in the key size entry of the cell header rather than in
57282** the payload area.
57283**
57284** The cell pointer array begins on the first byte after the page header.
57285** The cell pointer array contains zero or more 2-byte numbers which are
57286** offsets from the beginning of the page to the cell content in the cell
57287** content area.  The cell pointers occur in sorted order.  The system strives
57288** to keep free space after the last cell pointer so that new cells can
57289** be easily added without having to defragment the page.
57290**
57291** Cell content is stored at the very end of the page and grows toward the
57292** beginning of the page.
57293**
57294** Unused space within the cell content area is collected into a linked list of
57295** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
57296** to the first freeblock is given in the header.  Freeblocks occur in
57297** increasing order.  Because a freeblock must be at least 4 bytes in size,
57298** any group of 3 or fewer unused bytes in the cell content area cannot
57299** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
57300** a fragment.  The total number of bytes in all fragments is recorded.
57301** in the page header at offset 7.
57302**
57303**    SIZE    DESCRIPTION
57304**      2     Byte offset of the next freeblock
57305**      2     Bytes in this freeblock
57306**
57307** Cells are of variable length.  Cells are stored in the cell content area at
57308** the end of the page.  Pointers to the cells are in the cell pointer array
57309** that immediately follows the page header.  Cells is not necessarily
57310** contiguous or in order, but cell pointers are contiguous and in order.
57311**
57312** Cell content makes use of variable length integers.  A variable
57313** length integer is 1 to 9 bytes where the lower 7 bits of each
57314** byte are used.  The integer consists of all bytes that have bit 8 set and
57315** the first byte with bit 8 clear.  The most significant byte of the integer
57316** appears first.  A variable-length integer may not be more than 9 bytes long.
57317** As a special case, all 8 bytes of the 9th byte are used as data.  This
57318** allows a 64-bit integer to be encoded in 9 bytes.
57319**
57320**    0x00                      becomes  0x00000000
57321**    0x7f                      becomes  0x0000007f
57322**    0x81 0x00                 becomes  0x00000080
57323**    0x82 0x00                 becomes  0x00000100
57324**    0x80 0x7f                 becomes  0x0000007f
57325**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
57326**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
57327**
57328** Variable length integers are used for rowids and to hold the number of
57329** bytes of key and data in a btree cell.
57330**
57331** The content of a cell looks like this:
57332**
57333**    SIZE    DESCRIPTION
57334**      4     Page number of the left child. Omitted if leaf flag is set.
57335**     var    Number of bytes of data. Omitted if the zerodata flag is set.
57336**     var    Number of bytes of key. Or the key itself if intkey flag is set.
57337**      *     Payload
57338**      4     First page of the overflow chain.  Omitted if no overflow
57339**
57340** Overflow pages form a linked list.  Each page except the last is completely
57341** filled with data (pagesize - 4 bytes).  The last page can have as little
57342** as 1 byte of data.
57343**
57344**    SIZE    DESCRIPTION
57345**      4     Page number of next overflow page
57346**      *     Data
57347**
57348** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
57349** file header points to the first in a linked list of trunk page.  Each trunk
57350** page points to multiple leaf pages.  The content of a leaf page is
57351** unspecified.  A trunk page looks like this:
57352**
57353**    SIZE    DESCRIPTION
57354**      4     Page number of next trunk page
57355**      4     Number of leaf pointers on this page
57356**      *     zero or more pages numbers of leaves
57357*/
57358/* #include "sqliteInt.h" */
57359
57360
57361/* The following value is the maximum cell size assuming a maximum page
57362** size give above.
57363*/
57364#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
57365
57366/* The maximum number of cells on a single page of the database.  This
57367** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
57368** plus 2 bytes for the index to the cell in the page header).  Such
57369** small cells will be rare, but they are possible.
57370*/
57371#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
57372
57373/* Forward declarations */
57374typedef struct MemPage MemPage;
57375typedef struct BtLock BtLock;
57376typedef struct CellInfo CellInfo;
57377
57378/*
57379** This is a magic string that appears at the beginning of every
57380** SQLite database in order to identify the file as a real database.
57381**
57382** You can change this value at compile-time by specifying a
57383** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
57384** header must be exactly 16 bytes including the zero-terminator so
57385** the string itself should be 15 characters long.  If you change
57386** the header, then your custom library will not be able to read
57387** databases generated by the standard tools and the standard tools
57388** will not be able to read databases created by your custom library.
57389*/
57390#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
57391#  define SQLITE_FILE_HEADER "SQLite format 3"
57392#endif
57393
57394/*
57395** Page type flags.  An ORed combination of these flags appear as the
57396** first byte of on-disk image of every BTree page.
57397*/
57398#define PTF_INTKEY    0x01
57399#define PTF_ZERODATA  0x02
57400#define PTF_LEAFDATA  0x04
57401#define PTF_LEAF      0x08
57402
57403/*
57404** As each page of the file is loaded into memory, an instance of the following
57405** structure is appended and initialized to zero.  This structure stores
57406** information about the page that is decoded from the raw file page.
57407**
57408** The pParent field points back to the parent page.  This allows us to
57409** walk up the BTree from any leaf to the root.  Care must be taken to
57410** unref() the parent page pointer when this page is no longer referenced.
57411** The pageDestructor() routine handles that chore.
57412**
57413** Access to all fields of this structure is controlled by the mutex
57414** stored in MemPage.pBt->mutex.
57415*/
57416struct MemPage {
57417  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
57418  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
57419  u8 intKey;           /* True if table b-trees.  False for index b-trees */
57420  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
57421  u8 leaf;             /* True if a leaf page */
57422  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
57423  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
57424  u8 max1bytePayload;  /* min(maxLocal,127) */
57425  u8 bBusy;            /* Prevent endless loops on corrupt database files */
57426  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
57427  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
57428  u16 cellOffset;      /* Index in aData of first cell pointer */
57429  u16 nFree;           /* Number of free bytes on the page */
57430  u16 nCell;           /* Number of cells on this page, local and ovfl */
57431  u16 maskPage;        /* Mask for page offset */
57432  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
57433                       ** non-overflow cell */
57434  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
57435  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
57436  u8 *aData;           /* Pointer to disk image of the page data */
57437  u8 *aDataEnd;        /* One byte past the end of usable data */
57438  u8 *aCellIdx;        /* The cell index area */
57439  u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
57440  DbPage *pDbPage;     /* Pager page handle */
57441  u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
57442  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
57443  Pgno pgno;           /* Page number for this page */
57444};
57445
57446/*
57447** The in-memory image of a disk page has the auxiliary information appended
57448** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
57449** that extra information.
57450*/
57451#define EXTRA_SIZE sizeof(MemPage)
57452
57453/*
57454** A linked list of the following structures is stored at BtShared.pLock.
57455** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
57456** is opened on the table with root page BtShared.iTable. Locks are removed
57457** from this list when a transaction is committed or rolled back, or when
57458** a btree handle is closed.
57459*/
57460struct BtLock {
57461  Btree *pBtree;        /* Btree handle holding this lock */
57462  Pgno iTable;          /* Root page of table */
57463  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
57464  BtLock *pNext;        /* Next in BtShared.pLock list */
57465};
57466
57467/* Candidate values for BtLock.eLock */
57468#define READ_LOCK     1
57469#define WRITE_LOCK    2
57470
57471/* A Btree handle
57472**
57473** A database connection contains a pointer to an instance of
57474** this object for every database file that it has open.  This structure
57475** is opaque to the database connection.  The database connection cannot
57476** see the internals of this structure and only deals with pointers to
57477** this structure.
57478**
57479** For some database files, the same underlying database cache might be
57480** shared between multiple connections.  In that case, each connection
57481** has it own instance of this object.  But each instance of this object
57482** points to the same BtShared object.  The database cache and the
57483** schema associated with the database file are all contained within
57484** the BtShared object.
57485**
57486** All fields in this structure are accessed under sqlite3.mutex.
57487** The pBt pointer itself may not be changed while there exists cursors
57488** in the referenced BtShared that point back to this Btree since those
57489** cursors have to go through this Btree to find their BtShared and
57490** they often do so without holding sqlite3.mutex.
57491*/
57492struct Btree {
57493  sqlite3 *db;       /* The database connection holding this btree */
57494  BtShared *pBt;     /* Sharable content of this btree */
57495  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
57496  u8 sharable;       /* True if we can share pBt with another db */
57497  u8 locked;         /* True if db currently has pBt locked */
57498  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
57499  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
57500  int nBackup;       /* Number of backup operations reading this btree */
57501  u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
57502  Btree *pNext;      /* List of other sharable Btrees from the same db */
57503  Btree *pPrev;      /* Back pointer of the same list */
57504#ifndef SQLITE_OMIT_SHARED_CACHE
57505  BtLock lock;       /* Object used to lock page 1 */
57506#endif
57507};
57508
57509/*
57510** Btree.inTrans may take one of the following values.
57511**
57512** If the shared-data extension is enabled, there may be multiple users
57513** of the Btree structure. At most one of these may open a write transaction,
57514** but any number may have active read transactions.
57515*/
57516#define TRANS_NONE  0
57517#define TRANS_READ  1
57518#define TRANS_WRITE 2
57519
57520/*
57521** An instance of this object represents a single database file.
57522**
57523** A single database file can be in use at the same time by two
57524** or more database connections.  When two or more connections are
57525** sharing the same database file, each connection has it own
57526** private Btree object for the file and each of those Btrees points
57527** to this one BtShared object.  BtShared.nRef is the number of
57528** connections currently sharing this database file.
57529**
57530** Fields in this structure are accessed under the BtShared.mutex
57531** mutex, except for nRef and pNext which are accessed under the
57532** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
57533** may not be modified once it is initially set as long as nRef>0.
57534** The pSchema field may be set once under BtShared.mutex and
57535** thereafter is unchanged as long as nRef>0.
57536**
57537** isPending:
57538**
57539**   If a BtShared client fails to obtain a write-lock on a database
57540**   table (because there exists one or more read-locks on the table),
57541**   the shared-cache enters 'pending-lock' state and isPending is
57542**   set to true.
57543**
57544**   The shared-cache leaves the 'pending lock' state when either of
57545**   the following occur:
57546**
57547**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
57548**     2) The number of locks held by other connections drops to zero.
57549**
57550**   while in the 'pending-lock' state, no connection may start a new
57551**   transaction.
57552**
57553**   This feature is included to help prevent writer-starvation.
57554*/
57555struct BtShared {
57556  Pager *pPager;        /* The page cache */
57557  sqlite3 *db;          /* Database connection currently using this Btree */
57558  BtCursor *pCursor;    /* A list of all open cursors */
57559  MemPage *pPage1;      /* First page of the database */
57560  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
57561#ifndef SQLITE_OMIT_AUTOVACUUM
57562  u8 autoVacuum;        /* True if auto-vacuum is enabled */
57563  u8 incrVacuum;        /* True if incr-vacuum is enabled */
57564  u8 bDoTruncate;       /* True to truncate db on commit */
57565#endif
57566  u8 inTransaction;     /* Transaction state */
57567  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
57568#ifdef SQLITE_HAS_CODEC
57569  u8 optimalReserve;    /* Desired amount of reserved space per page */
57570#endif
57571  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
57572  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
57573  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
57574  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
57575  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
57576  u32 pageSize;         /* Total number of bytes on a page */
57577  u32 usableSize;       /* Number of usable bytes on each page */
57578  int nTransaction;     /* Number of open transactions (read + write) */
57579  u32 nPage;            /* Number of pages in the database */
57580  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
57581  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
57582  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
57583  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
57584#ifndef SQLITE_OMIT_SHARED_CACHE
57585  int nRef;             /* Number of references to this structure */
57586  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
57587  BtLock *pLock;        /* List of locks held on this shared-btree struct */
57588  Btree *pWriter;       /* Btree with currently open write transaction */
57589#endif
57590  u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
57591};
57592
57593/*
57594** Allowed values for BtShared.btsFlags
57595*/
57596#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
57597#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
57598#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
57599#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
57600#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
57601#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
57602#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
57603
57604/*
57605** An instance of the following structure is used to hold information
57606** about a cell.  The parseCellPtr() function fills in this structure
57607** based on information extract from the raw disk page.
57608*/
57609struct CellInfo {
57610  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
57611  u8 *pPayload;  /* Pointer to the start of payload */
57612  u32 nPayload;  /* Bytes of payload */
57613  u16 nLocal;    /* Amount of payload held locally, not on overflow */
57614  u16 nSize;     /* Size of the cell content on the main b-tree page */
57615};
57616
57617/*
57618** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
57619** this will be declared corrupt. This value is calculated based on a
57620** maximum database size of 2^31 pages a minimum fanout of 2 for a
57621** root-node and 3 for all other internal nodes.
57622**
57623** If a tree that appears to be taller than this is encountered, it is
57624** assumed that the database is corrupt.
57625*/
57626#define BTCURSOR_MAX_DEPTH 20
57627
57628/*
57629** A cursor is a pointer to a particular entry within a particular
57630** b-tree within a database file.
57631**
57632** The entry is identified by its MemPage and the index in
57633** MemPage.aCell[] of the entry.
57634**
57635** A single database file can be shared by two more database connections,
57636** but cursors cannot be shared.  Each cursor is associated with a
57637** particular database connection identified BtCursor.pBtree.db.
57638**
57639** Fields in this structure are accessed under the BtShared.mutex
57640** found at self->pBt->mutex.
57641**
57642** skipNext meaning:
57643**    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
57644**    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
57645**    eState==FAULT:                   Cursor fault with skipNext as error code.
57646*/
57647struct BtCursor {
57648  Btree *pBtree;            /* The Btree to which this cursor belongs */
57649  BtShared *pBt;            /* The BtShared this cursor points to */
57650  BtCursor *pNext;          /* Forms a linked list of all cursors */
57651  Pgno *aOverflow;          /* Cache of overflow page locations */
57652  CellInfo info;            /* A parse of the cell we are pointing at */
57653  i64 nKey;                 /* Size of pKey, or last integer key */
57654  void *pKey;               /* Saved key that was cursor last known position */
57655  Pgno pgnoRoot;            /* The root page of this tree */
57656  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
57657  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
57658                   ** Error code if eState==CURSOR_FAULT */
57659  u8 curFlags;              /* zero or more BTCF_* flags defined below */
57660  u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
57661  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
57662  u8 hints;                 /* As configured by CursorSetHints() */
57663  /* All fields above are zeroed when the cursor is allocated.  See
57664  ** sqlite3BtreeCursorZero().  Fields that follow must be manually
57665  ** initialized. */
57666  i8 iPage;                 /* Index of current page in apPage */
57667  u8 curIntKey;             /* Value of apPage[0]->intKey */
57668  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
57669  void *padding1;           /* Make object size a multiple of 16 */
57670  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
57671  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
57672};
57673
57674/*
57675** Legal values for BtCursor.curFlags
57676*/
57677#define BTCF_WriteFlag    0x01   /* True if a write cursor */
57678#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
57679#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
57680#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
57681#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
57682#define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
57683
57684/*
57685** Potential values for BtCursor.eState.
57686**
57687** CURSOR_INVALID:
57688**   Cursor does not point to a valid entry. This can happen (for example)
57689**   because the table is empty or because BtreeCursorFirst() has not been
57690**   called.
57691**
57692** CURSOR_VALID:
57693**   Cursor points to a valid entry. getPayload() etc. may be called.
57694**
57695** CURSOR_SKIPNEXT:
57696**   Cursor is valid except that the Cursor.skipNext field is non-zero
57697**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
57698**   operation should be a no-op.
57699**
57700** CURSOR_REQUIRESEEK:
57701**   The table that this cursor was opened on still exists, but has been
57702**   modified since the cursor was last used. The cursor position is saved
57703**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
57704**   this state, restoreCursorPosition() can be called to attempt to
57705**   seek the cursor to the saved position.
57706**
57707** CURSOR_FAULT:
57708**   An unrecoverable error (an I/O error or a malloc failure) has occurred
57709**   on a different connection that shares the BtShared cache with this
57710**   cursor.  The error has left the cache in an inconsistent state.
57711**   Do nothing else with this cursor.  Any attempt to use the cursor
57712**   should return the error code stored in BtCursor.skipNext
57713*/
57714#define CURSOR_INVALID           0
57715#define CURSOR_VALID             1
57716#define CURSOR_SKIPNEXT          2
57717#define CURSOR_REQUIRESEEK       3
57718#define CURSOR_FAULT             4
57719
57720/*
57721** The database page the PENDING_BYTE occupies. This page is never used.
57722*/
57723# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
57724
57725/*
57726** These macros define the location of the pointer-map entry for a
57727** database page. The first argument to each is the number of usable
57728** bytes on each page of the database (often 1024). The second is the
57729** page number to look up in the pointer map.
57730**
57731** PTRMAP_PAGENO returns the database page number of the pointer-map
57732** page that stores the required pointer. PTRMAP_PTROFFSET returns
57733** the offset of the requested map entry.
57734**
57735** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
57736** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
57737** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
57738** this test.
57739*/
57740#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
57741#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
57742#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
57743
57744/*
57745** The pointer map is a lookup table that identifies the parent page for
57746** each child page in the database file.  The parent page is the page that
57747** contains a pointer to the child.  Every page in the database contains
57748** 0 or 1 parent pages.  (In this context 'database page' refers
57749** to any page that is not part of the pointer map itself.)  Each pointer map
57750** entry consists of a single byte 'type' and a 4 byte parent page number.
57751** The PTRMAP_XXX identifiers below are the valid types.
57752**
57753** The purpose of the pointer map is to facility moving pages from one
57754** position in the file to another as part of autovacuum.  When a page
57755** is moved, the pointer in its parent must be updated to point to the
57756** new location.  The pointer map is used to locate the parent page quickly.
57757**
57758** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
57759**                  used in this case.
57760**
57761** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
57762**                  is not used in this case.
57763**
57764** PTRMAP_OVERFLOW1: The database page is the first page in a list of
57765**                   overflow pages. The page number identifies the page that
57766**                   contains the cell with a pointer to this overflow page.
57767**
57768** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
57769**                   overflow pages. The page-number identifies the previous
57770**                   page in the overflow page list.
57771**
57772** PTRMAP_BTREE: The database page is a non-root btree page. The page number
57773**               identifies the parent page in the btree.
57774*/
57775#define PTRMAP_ROOTPAGE 1
57776#define PTRMAP_FREEPAGE 2
57777#define PTRMAP_OVERFLOW1 3
57778#define PTRMAP_OVERFLOW2 4
57779#define PTRMAP_BTREE 5
57780
57781/* A bunch of assert() statements to check the transaction state variables
57782** of handle p (type Btree*) are internally consistent.
57783*/
57784#define btreeIntegrity(p) \
57785  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
57786  assert( p->pBt->inTransaction>=p->inTrans );
57787
57788
57789/*
57790** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
57791** if the database supports auto-vacuum or not. Because it is used
57792** within an expression that is an argument to another macro
57793** (sqliteMallocRaw), it is not possible to use conditional compilation.
57794** So, this macro is defined instead.
57795*/
57796#ifndef SQLITE_OMIT_AUTOVACUUM
57797#define ISAUTOVACUUM (pBt->autoVacuum)
57798#else
57799#define ISAUTOVACUUM 0
57800#endif
57801
57802
57803/*
57804** This structure is passed around through all the sanity checking routines
57805** in order to keep track of some global state information.
57806**
57807** The aRef[] array is allocated so that there is 1 bit for each page in
57808** the database. As the integrity-check proceeds, for each page used in
57809** the database the corresponding bit is set. This allows integrity-check to
57810** detect pages that are used twice and orphaned pages (both of which
57811** indicate corruption).
57812*/
57813typedef struct IntegrityCk IntegrityCk;
57814struct IntegrityCk {
57815  BtShared *pBt;    /* The tree being checked out */
57816  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
57817  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
57818  Pgno nPage;       /* Number of pages in the database */
57819  int mxErr;        /* Stop accumulating errors when this reaches zero */
57820  int nErr;         /* Number of messages written to zErrMsg so far */
57821  int mallocFailed; /* A memory allocation error has occurred */
57822  const char *zPfx; /* Error message prefix */
57823  int v1, v2;       /* Values for up to two %d fields in zPfx */
57824  StrAccum errMsg;  /* Accumulate the error message text here */
57825  u32 *heap;        /* Min-heap used for analyzing cell coverage */
57826};
57827
57828/*
57829** Routines to read or write a two- and four-byte big-endian integer values.
57830*/
57831#define get2byte(x)   ((x)[0]<<8 | (x)[1])
57832#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
57833#define get4byte sqlite3Get4byte
57834#define put4byte sqlite3Put4byte
57835
57836/*
57837** get2byteAligned(), unlike get2byte(), requires that its argument point to a
57838** two-byte aligned address.  get2bytea() is only used for accessing the
57839** cell addresses in a btree header.
57840*/
57841#if SQLITE_BYTEORDER==4321
57842# define get2byteAligned(x)  (*(u16*)(x))
57843#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57844    && GCC_VERSION>=4008000
57845# define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
57846#elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57847    && defined(_MSC_VER) && _MSC_VER>=1300
57848# define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
57849#else
57850# define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
57851#endif
57852
57853/************** End of btreeInt.h ********************************************/
57854/************** Continuing where we left off in btmutex.c ********************/
57855#ifndef SQLITE_OMIT_SHARED_CACHE
57856#if SQLITE_THREADSAFE
57857
57858/*
57859** Obtain the BtShared mutex associated with B-Tree handle p. Also,
57860** set BtShared.db to the database handle associated with p and the
57861** p->locked boolean to true.
57862*/
57863static void lockBtreeMutex(Btree *p){
57864  assert( p->locked==0 );
57865  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
57866  assert( sqlite3_mutex_held(p->db->mutex) );
57867
57868  sqlite3_mutex_enter(p->pBt->mutex);
57869  p->pBt->db = p->db;
57870  p->locked = 1;
57871}
57872
57873/*
57874** Release the BtShared mutex associated with B-Tree handle p and
57875** clear the p->locked boolean.
57876*/
57877static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
57878  BtShared *pBt = p->pBt;
57879  assert( p->locked==1 );
57880  assert( sqlite3_mutex_held(pBt->mutex) );
57881  assert( sqlite3_mutex_held(p->db->mutex) );
57882  assert( p->db==pBt->db );
57883
57884  sqlite3_mutex_leave(pBt->mutex);
57885  p->locked = 0;
57886}
57887
57888/* Forward reference */
57889static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
57890
57891/*
57892** Enter a mutex on the given BTree object.
57893**
57894** If the object is not sharable, then no mutex is ever required
57895** and this routine is a no-op.  The underlying mutex is non-recursive.
57896** But we keep a reference count in Btree.wantToLock so the behavior
57897** of this interface is recursive.
57898**
57899** To avoid deadlocks, multiple Btrees are locked in the same order
57900** by all database connections.  The p->pNext is a list of other
57901** Btrees belonging to the same database connection as the p Btree
57902** which need to be locked after p.  If we cannot get a lock on
57903** p, then first unlock all of the others on p->pNext, then wait
57904** for the lock to become available on p, then relock all of the
57905** subsequent Btrees that desire a lock.
57906*/
57907SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
57908  /* Some basic sanity checking on the Btree.  The list of Btrees
57909  ** connected by pNext and pPrev should be in sorted order by
57910  ** Btree.pBt value. All elements of the list should belong to
57911  ** the same connection. Only shared Btrees are on the list. */
57912  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
57913  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
57914  assert( p->pNext==0 || p->pNext->db==p->db );
57915  assert( p->pPrev==0 || p->pPrev->db==p->db );
57916  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
57917
57918  /* Check for locking consistency */
57919  assert( !p->locked || p->wantToLock>0 );
57920  assert( p->sharable || p->wantToLock==0 );
57921
57922  /* We should already hold a lock on the database connection */
57923  assert( sqlite3_mutex_held(p->db->mutex) );
57924
57925  /* Unless the database is sharable and unlocked, then BtShared.db
57926  ** should already be set correctly. */
57927  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
57928
57929  if( !p->sharable ) return;
57930  p->wantToLock++;
57931  if( p->locked ) return;
57932  btreeLockCarefully(p);
57933}
57934
57935/* This is a helper function for sqlite3BtreeLock(). By moving
57936** complex, but seldom used logic, out of sqlite3BtreeLock() and
57937** into this routine, we avoid unnecessary stack pointer changes
57938** and thus help the sqlite3BtreeLock() routine to run much faster
57939** in the common case.
57940*/
57941static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
57942  Btree *pLater;
57943
57944  /* In most cases, we should be able to acquire the lock we
57945  ** want without having to go through the ascending lock
57946  ** procedure that follows.  Just be sure not to block.
57947  */
57948  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
57949    p->pBt->db = p->db;
57950    p->locked = 1;
57951    return;
57952  }
57953
57954  /* To avoid deadlock, first release all locks with a larger
57955  ** BtShared address.  Then acquire our lock.  Then reacquire
57956  ** the other BtShared locks that we used to hold in ascending
57957  ** order.
57958  */
57959  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57960    assert( pLater->sharable );
57961    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
57962    assert( !pLater->locked || pLater->wantToLock>0 );
57963    if( pLater->locked ){
57964      unlockBtreeMutex(pLater);
57965    }
57966  }
57967  lockBtreeMutex(p);
57968  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57969    if( pLater->wantToLock ){
57970      lockBtreeMutex(pLater);
57971    }
57972  }
57973}
57974
57975
57976/*
57977** Exit the recursive mutex on a Btree.
57978*/
57979SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
57980  assert( sqlite3_mutex_held(p->db->mutex) );
57981  if( p->sharable ){
57982    assert( p->wantToLock>0 );
57983    p->wantToLock--;
57984    if( p->wantToLock==0 ){
57985      unlockBtreeMutex(p);
57986    }
57987  }
57988}
57989
57990#ifndef NDEBUG
57991/*
57992** Return true if the BtShared mutex is held on the btree, or if the
57993** B-Tree is not marked as sharable.
57994**
57995** This routine is used only from within assert() statements.
57996*/
57997SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
57998  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
57999  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
58000  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
58001  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
58002
58003  return (p->sharable==0 || p->locked);
58004}
58005#endif
58006
58007
58008/*
58009** Enter the mutex on every Btree associated with a database
58010** connection.  This is needed (for example) prior to parsing
58011** a statement since we will be comparing table and column names
58012** against all schemas and we do not want those schemas being
58013** reset out from under us.
58014**
58015** There is a corresponding leave-all procedures.
58016**
58017** Enter the mutexes in accending order by BtShared pointer address
58018** to avoid the possibility of deadlock when two threads with
58019** two or more btrees in common both try to lock all their btrees
58020** at the same instant.
58021*/
58022SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58023  int i;
58024  Btree *p;
58025  assert( sqlite3_mutex_held(db->mutex) );
58026  for(i=0; i<db->nDb; i++){
58027    p = db->aDb[i].pBt;
58028    if( p ) sqlite3BtreeEnter(p);
58029  }
58030}
58031SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
58032  int i;
58033  Btree *p;
58034  assert( sqlite3_mutex_held(db->mutex) );
58035  for(i=0; i<db->nDb; i++){
58036    p = db->aDb[i].pBt;
58037    if( p ) sqlite3BtreeLeave(p);
58038  }
58039}
58040
58041#ifndef NDEBUG
58042/*
58043** Return true if the current thread holds the database connection
58044** mutex and all required BtShared mutexes.
58045**
58046** This routine is used inside assert() statements only.
58047*/
58048SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
58049  int i;
58050  if( !sqlite3_mutex_held(db->mutex) ){
58051    return 0;
58052  }
58053  for(i=0; i<db->nDb; i++){
58054    Btree *p;
58055    p = db->aDb[i].pBt;
58056    if( p && p->sharable &&
58057         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
58058      return 0;
58059    }
58060  }
58061  return 1;
58062}
58063#endif /* NDEBUG */
58064
58065#ifndef NDEBUG
58066/*
58067** Return true if the correct mutexes are held for accessing the
58068** db->aDb[iDb].pSchema structure.  The mutexes required for schema
58069** access are:
58070**
58071**   (1) The mutex on db
58072**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
58073**
58074** If pSchema is not NULL, then iDb is computed from pSchema and
58075** db using sqlite3SchemaToIndex().
58076*/
58077SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
58078  Btree *p;
58079  assert( db!=0 );
58080  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
58081  assert( iDb>=0 && iDb<db->nDb );
58082  if( !sqlite3_mutex_held(db->mutex) ) return 0;
58083  if( iDb==1 ) return 1;
58084  p = db->aDb[iDb].pBt;
58085  assert( p!=0 );
58086  return p->sharable==0 || p->locked==1;
58087}
58088#endif /* NDEBUG */
58089
58090#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
58091/*
58092** The following are special cases for mutex enter routines for use
58093** in single threaded applications that use shared cache.  Except for
58094** these two routines, all mutex operations are no-ops in that case and
58095** are null #defines in btree.h.
58096**
58097** If shared cache is disabled, then all btree mutex routines, including
58098** the ones below, are no-ops and are null #defines in btree.h.
58099*/
58100
58101SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58102  p->pBt->db = p->db;
58103}
58104SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58105  int i;
58106  for(i=0; i<db->nDb; i++){
58107    Btree *p = db->aDb[i].pBt;
58108    if( p ){
58109      p->pBt->db = p->db;
58110    }
58111  }
58112}
58113#endif /* if SQLITE_THREADSAFE */
58114
58115#ifndef SQLITE_OMIT_INCRBLOB
58116/*
58117** Enter a mutex on a Btree given a cursor owned by that Btree.
58118**
58119** These entry points are used by incremental I/O only. Enter() is required
58120** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
58121** the build is threadsafe. Leave() is only required by threadsafe builds.
58122*/
58123SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
58124  sqlite3BtreeEnter(pCur->pBtree);
58125}
58126# if SQLITE_THREADSAFE
58127SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
58128  sqlite3BtreeLeave(pCur->pBtree);
58129}
58130# endif
58131#endif /* ifndef SQLITE_OMIT_INCRBLOB */
58132
58133#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
58134
58135/************** End of btmutex.c *********************************************/
58136/************** Begin file btree.c *******************************************/
58137/*
58138** 2004 April 6
58139**
58140** The author disclaims copyright to this source code.  In place of
58141** a legal notice, here is a blessing:
58142**
58143**    May you do good and not evil.
58144**    May you find forgiveness for yourself and forgive others.
58145**    May you share freely, never taking more than you give.
58146**
58147*************************************************************************
58148** This file implements an external (disk-based) database using BTrees.
58149** See the header comment on "btreeInt.h" for additional information.
58150** Including a description of file format and an overview of operation.
58151*/
58152/* #include "btreeInt.h" */
58153
58154/*
58155** The header string that appears at the beginning of every
58156** SQLite database.
58157*/
58158static const char zMagicHeader[] = SQLITE_FILE_HEADER;
58159
58160/*
58161** Set this global variable to 1 to enable tracing using the TRACE
58162** macro.
58163*/
58164#if 0
58165int sqlite3BtreeTrace=1;  /* True to enable tracing */
58166# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
58167#else
58168# define TRACE(X)
58169#endif
58170
58171/*
58172** Extract a 2-byte big-endian integer from an array of unsigned bytes.
58173** But if the value is zero, make it 65536.
58174**
58175** This routine is used to extract the "offset to cell content area" value
58176** from the header of a btree page.  If the page size is 65536 and the page
58177** is empty, the offset should be 65536, but the 2-byte value stores zero.
58178** This routine makes the necessary adjustment to 65536.
58179*/
58180#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
58181
58182/*
58183** Values passed as the 5th argument to allocateBtreePage()
58184*/
58185#define BTALLOC_ANY   0           /* Allocate any page */
58186#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
58187#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
58188
58189/*
58190** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
58191** defined, or 0 if it is. For example:
58192**
58193**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58194*/
58195#ifndef SQLITE_OMIT_AUTOVACUUM
58196#define IfNotOmitAV(expr) (expr)
58197#else
58198#define IfNotOmitAV(expr) 0
58199#endif
58200
58201#ifndef SQLITE_OMIT_SHARED_CACHE
58202/*
58203** A list of BtShared objects that are eligible for participation
58204** in shared cache.  This variable has file scope during normal builds,
58205** but the test harness needs to access it so we make it global for
58206** test builds.
58207**
58208** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
58209*/
58210#ifdef SQLITE_TEST
58211SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58212#else
58213static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58214#endif
58215#endif /* SQLITE_OMIT_SHARED_CACHE */
58216
58217#ifndef SQLITE_OMIT_SHARED_CACHE
58218/*
58219** Enable or disable the shared pager and schema features.
58220**
58221** This routine has no effect on existing database connections.
58222** The shared cache setting effects only future calls to
58223** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
58224*/
58225SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
58226  sqlite3GlobalConfig.sharedCacheEnabled = enable;
58227  return SQLITE_OK;
58228}
58229#endif
58230
58231
58232
58233#ifdef SQLITE_OMIT_SHARED_CACHE
58234  /*
58235  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
58236  ** and clearAllSharedCacheTableLocks()
58237  ** manipulate entries in the BtShared.pLock linked list used to store
58238  ** shared-cache table level locks. If the library is compiled with the
58239  ** shared-cache feature disabled, then there is only ever one user
58240  ** of each BtShared structure and so this locking is not necessary.
58241  ** So define the lock related functions as no-ops.
58242  */
58243  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
58244  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
58245  #define clearAllSharedCacheTableLocks(a)
58246  #define downgradeAllSharedCacheTableLocks(a)
58247  #define hasSharedCacheTableLock(a,b,c,d) 1
58248  #define hasReadConflicts(a, b) 0
58249#endif
58250
58251#ifndef SQLITE_OMIT_SHARED_CACHE
58252
58253#ifdef SQLITE_DEBUG
58254/*
58255**** This function is only used as part of an assert() statement. ***
58256**
58257** Check to see if pBtree holds the required locks to read or write to the
58258** table with root page iRoot.   Return 1 if it does and 0 if not.
58259**
58260** For example, when writing to a table with root-page iRoot via
58261** Btree connection pBtree:
58262**
58263**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
58264**
58265** When writing to an index that resides in a sharable database, the
58266** caller should have first obtained a lock specifying the root page of
58267** the corresponding table. This makes things a bit more complicated,
58268** as this module treats each table as a separate structure. To determine
58269** the table corresponding to the index being written, this
58270** function has to search through the database schema.
58271**
58272** Instead of a lock on the table/index rooted at page iRoot, the caller may
58273** hold a write-lock on the schema table (root page 1). This is also
58274** acceptable.
58275*/
58276static int hasSharedCacheTableLock(
58277  Btree *pBtree,         /* Handle that must hold lock */
58278  Pgno iRoot,            /* Root page of b-tree */
58279  int isIndex,           /* True if iRoot is the root of an index b-tree */
58280  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
58281){
58282  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
58283  Pgno iTab = 0;
58284  BtLock *pLock;
58285
58286  /* If this database is not shareable, or if the client is reading
58287  ** and has the read-uncommitted flag set, then no lock is required.
58288  ** Return true immediately.
58289  */
58290  if( (pBtree->sharable==0)
58291   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
58292  ){
58293    return 1;
58294  }
58295
58296  /* If the client is reading  or writing an index and the schema is
58297  ** not loaded, then it is too difficult to actually check to see if
58298  ** the correct locks are held.  So do not bother - just return true.
58299  ** This case does not come up very often anyhow.
58300  */
58301  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
58302    return 1;
58303  }
58304
58305  /* Figure out the root-page that the lock should be held on. For table
58306  ** b-trees, this is just the root page of the b-tree being read or
58307  ** written. For index b-trees, it is the root page of the associated
58308  ** table.  */
58309  if( isIndex ){
58310    HashElem *p;
58311    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
58312      Index *pIdx = (Index *)sqliteHashData(p);
58313      if( pIdx->tnum==(int)iRoot ){
58314        if( iTab ){
58315          /* Two or more indexes share the same root page.  There must
58316          ** be imposter tables.  So just return true.  The assert is not
58317          ** useful in that case. */
58318          return 1;
58319        }
58320        iTab = pIdx->pTable->tnum;
58321      }
58322    }
58323  }else{
58324    iTab = iRoot;
58325  }
58326
58327  /* Search for the required lock. Either a write-lock on root-page iTab, a
58328  ** write-lock on the schema table, or (if the client is reading) a
58329  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
58330  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
58331    if( pLock->pBtree==pBtree
58332     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
58333     && pLock->eLock>=eLockType
58334    ){
58335      return 1;
58336    }
58337  }
58338
58339  /* Failed to find the required lock. */
58340  return 0;
58341}
58342#endif /* SQLITE_DEBUG */
58343
58344#ifdef SQLITE_DEBUG
58345/*
58346**** This function may be used as part of assert() statements only. ****
58347**
58348** Return true if it would be illegal for pBtree to write into the
58349** table or index rooted at iRoot because other shared connections are
58350** simultaneously reading that same table or index.
58351**
58352** It is illegal for pBtree to write if some other Btree object that
58353** shares the same BtShared object is currently reading or writing
58354** the iRoot table.  Except, if the other Btree object has the
58355** read-uncommitted flag set, then it is OK for the other object to
58356** have a read cursor.
58357**
58358** For example, before writing to any part of the table or index
58359** rooted at page iRoot, one should call:
58360**
58361**    assert( !hasReadConflicts(pBtree, iRoot) );
58362*/
58363static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
58364  BtCursor *p;
58365  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58366    if( p->pgnoRoot==iRoot
58367     && p->pBtree!=pBtree
58368     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
58369    ){
58370      return 1;
58371    }
58372  }
58373  return 0;
58374}
58375#endif    /* #ifdef SQLITE_DEBUG */
58376
58377/*
58378** Query to see if Btree handle p may obtain a lock of type eLock
58379** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
58380** SQLITE_OK if the lock may be obtained (by calling
58381** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
58382*/
58383static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
58384  BtShared *pBt = p->pBt;
58385  BtLock *pIter;
58386
58387  assert( sqlite3BtreeHoldsMutex(p) );
58388  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58389  assert( p->db!=0 );
58390  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
58391
58392  /* If requesting a write-lock, then the Btree must have an open write
58393  ** transaction on this file. And, obviously, for this to be so there
58394  ** must be an open write transaction on the file itself.
58395  */
58396  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
58397  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
58398
58399  /* This routine is a no-op if the shared-cache is not enabled */
58400  if( !p->sharable ){
58401    return SQLITE_OK;
58402  }
58403
58404  /* If some other connection is holding an exclusive lock, the
58405  ** requested lock may not be obtained.
58406  */
58407  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
58408    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
58409    return SQLITE_LOCKED_SHAREDCACHE;
58410  }
58411
58412  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58413    /* The condition (pIter->eLock!=eLock) in the following if(...)
58414    ** statement is a simplification of:
58415    **
58416    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
58417    **
58418    ** since we know that if eLock==WRITE_LOCK, then no other connection
58419    ** may hold a WRITE_LOCK on any table in this file (since there can
58420    ** only be a single writer).
58421    */
58422    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
58423    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
58424    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
58425      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
58426      if( eLock==WRITE_LOCK ){
58427        assert( p==pBt->pWriter );
58428        pBt->btsFlags |= BTS_PENDING;
58429      }
58430      return SQLITE_LOCKED_SHAREDCACHE;
58431    }
58432  }
58433  return SQLITE_OK;
58434}
58435#endif /* !SQLITE_OMIT_SHARED_CACHE */
58436
58437#ifndef SQLITE_OMIT_SHARED_CACHE
58438/*
58439** Add a lock on the table with root-page iTable to the shared-btree used
58440** by Btree handle p. Parameter eLock must be either READ_LOCK or
58441** WRITE_LOCK.
58442**
58443** This function assumes the following:
58444**
58445**   (a) The specified Btree object p is connected to a sharable
58446**       database (one with the BtShared.sharable flag set), and
58447**
58448**   (b) No other Btree objects hold a lock that conflicts
58449**       with the requested lock (i.e. querySharedCacheTableLock() has
58450**       already been called and returned SQLITE_OK).
58451**
58452** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
58453** is returned if a malloc attempt fails.
58454*/
58455static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
58456  BtShared *pBt = p->pBt;
58457  BtLock *pLock = 0;
58458  BtLock *pIter;
58459
58460  assert( sqlite3BtreeHoldsMutex(p) );
58461  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58462  assert( p->db!=0 );
58463
58464  /* A connection with the read-uncommitted flag set will never try to
58465  ** obtain a read-lock using this function. The only read-lock obtained
58466  ** by a connection in read-uncommitted mode is on the sqlite_master
58467  ** table, and that lock is obtained in BtreeBeginTrans().  */
58468  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
58469
58470  /* This function should only be called on a sharable b-tree after it
58471  ** has been determined that no other b-tree holds a conflicting lock.  */
58472  assert( p->sharable );
58473  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
58474
58475  /* First search the list for an existing lock on this table. */
58476  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58477    if( pIter->iTable==iTable && pIter->pBtree==p ){
58478      pLock = pIter;
58479      break;
58480    }
58481  }
58482
58483  /* If the above search did not find a BtLock struct associating Btree p
58484  ** with table iTable, allocate one and link it into the list.
58485  */
58486  if( !pLock ){
58487    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
58488    if( !pLock ){
58489      return SQLITE_NOMEM_BKPT;
58490    }
58491    pLock->iTable = iTable;
58492    pLock->pBtree = p;
58493    pLock->pNext = pBt->pLock;
58494    pBt->pLock = pLock;
58495  }
58496
58497  /* Set the BtLock.eLock variable to the maximum of the current lock
58498  ** and the requested lock. This means if a write-lock was already held
58499  ** and a read-lock requested, we don't incorrectly downgrade the lock.
58500  */
58501  assert( WRITE_LOCK>READ_LOCK );
58502  if( eLock>pLock->eLock ){
58503    pLock->eLock = eLock;
58504  }
58505
58506  return SQLITE_OK;
58507}
58508#endif /* !SQLITE_OMIT_SHARED_CACHE */
58509
58510#ifndef SQLITE_OMIT_SHARED_CACHE
58511/*
58512** Release all the table locks (locks obtained via calls to
58513** the setSharedCacheTableLock() procedure) held by Btree object p.
58514**
58515** This function assumes that Btree p has an open read or write
58516** transaction. If it does not, then the BTS_PENDING flag
58517** may be incorrectly cleared.
58518*/
58519static void clearAllSharedCacheTableLocks(Btree *p){
58520  BtShared *pBt = p->pBt;
58521  BtLock **ppIter = &pBt->pLock;
58522
58523  assert( sqlite3BtreeHoldsMutex(p) );
58524  assert( p->sharable || 0==*ppIter );
58525  assert( p->inTrans>0 );
58526
58527  while( *ppIter ){
58528    BtLock *pLock = *ppIter;
58529    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
58530    assert( pLock->pBtree->inTrans>=pLock->eLock );
58531    if( pLock->pBtree==p ){
58532      *ppIter = pLock->pNext;
58533      assert( pLock->iTable!=1 || pLock==&p->lock );
58534      if( pLock->iTable!=1 ){
58535        sqlite3_free(pLock);
58536      }
58537    }else{
58538      ppIter = &pLock->pNext;
58539    }
58540  }
58541
58542  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
58543  if( pBt->pWriter==p ){
58544    pBt->pWriter = 0;
58545    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58546  }else if( pBt->nTransaction==2 ){
58547    /* This function is called when Btree p is concluding its
58548    ** transaction. If there currently exists a writer, and p is not
58549    ** that writer, then the number of locks held by connections other
58550    ** than the writer must be about to drop to zero. In this case
58551    ** set the BTS_PENDING flag to 0.
58552    **
58553    ** If there is not currently a writer, then BTS_PENDING must
58554    ** be zero already. So this next line is harmless in that case.
58555    */
58556    pBt->btsFlags &= ~BTS_PENDING;
58557  }
58558}
58559
58560/*
58561** This function changes all write-locks held by Btree p into read-locks.
58562*/
58563static void downgradeAllSharedCacheTableLocks(Btree *p){
58564  BtShared *pBt = p->pBt;
58565  if( pBt->pWriter==p ){
58566    BtLock *pLock;
58567    pBt->pWriter = 0;
58568    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58569    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
58570      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
58571      pLock->eLock = READ_LOCK;
58572    }
58573  }
58574}
58575
58576#endif /* SQLITE_OMIT_SHARED_CACHE */
58577
58578static void releasePage(MemPage *pPage);  /* Forward reference */
58579
58580/*
58581***** This routine is used inside of assert() only ****
58582**
58583** Verify that the cursor holds the mutex on its BtShared
58584*/
58585#ifdef SQLITE_DEBUG
58586static int cursorHoldsMutex(BtCursor *p){
58587  return sqlite3_mutex_held(p->pBt->mutex);
58588}
58589
58590/* Verify that the cursor and the BtShared agree about what is the current
58591** database connetion. This is important in shared-cache mode. If the database
58592** connection pointers get out-of-sync, it is possible for routines like
58593** btreeInitPage() to reference an stale connection pointer that references a
58594** a connection that has already closed.  This routine is used inside assert()
58595** statements only and for the purpose of double-checking that the btree code
58596** does keep the database connection pointers up-to-date.
58597*/
58598static int cursorOwnsBtShared(BtCursor *p){
58599  assert( cursorHoldsMutex(p) );
58600  return (p->pBtree->db==p->pBt->db);
58601}
58602#endif
58603
58604/*
58605** Invalidate the overflow cache of the cursor passed as the first argument.
58606** on the shared btree structure pBt.
58607*/
58608#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
58609
58610/*
58611** Invalidate the overflow page-list cache for all cursors opened
58612** on the shared btree structure pBt.
58613*/
58614static void invalidateAllOverflowCache(BtShared *pBt){
58615  BtCursor *p;
58616  assert( sqlite3_mutex_held(pBt->mutex) );
58617  for(p=pBt->pCursor; p; p=p->pNext){
58618    invalidateOverflowCache(p);
58619  }
58620}
58621
58622#ifndef SQLITE_OMIT_INCRBLOB
58623/*
58624** This function is called before modifying the contents of a table
58625** to invalidate any incrblob cursors that are open on the
58626** row or one of the rows being modified.
58627**
58628** If argument isClearTable is true, then the entire contents of the
58629** table is about to be deleted. In this case invalidate all incrblob
58630** cursors open on any row within the table with root-page pgnoRoot.
58631**
58632** Otherwise, if argument isClearTable is false, then the row with
58633** rowid iRow is being replaced or deleted. In this case invalidate
58634** only those incrblob cursors open on that specific row.
58635*/
58636static void invalidateIncrblobCursors(
58637  Btree *pBtree,          /* The database file to check */
58638  i64 iRow,               /* The rowid that might be changing */
58639  int isClearTable        /* True if all rows are being deleted */
58640){
58641  BtCursor *p;
58642  if( pBtree->hasIncrblobCur==0 ) return;
58643  assert( sqlite3BtreeHoldsMutex(pBtree) );
58644  pBtree->hasIncrblobCur = 0;
58645  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58646    if( (p->curFlags & BTCF_Incrblob)!=0 ){
58647      pBtree->hasIncrblobCur = 1;
58648      if( isClearTable || p->info.nKey==iRow ){
58649        p->eState = CURSOR_INVALID;
58650      }
58651    }
58652  }
58653}
58654
58655#else
58656  /* Stub function when INCRBLOB is omitted */
58657  #define invalidateIncrblobCursors(x,y,z)
58658#endif /* SQLITE_OMIT_INCRBLOB */
58659
58660/*
58661** Set bit pgno of the BtShared.pHasContent bitvec. This is called
58662** when a page that previously contained data becomes a free-list leaf
58663** page.
58664**
58665** The BtShared.pHasContent bitvec exists to work around an obscure
58666** bug caused by the interaction of two useful IO optimizations surrounding
58667** free-list leaf pages:
58668**
58669**   1) When all data is deleted from a page and the page becomes
58670**      a free-list leaf page, the page is not written to the database
58671**      (as free-list leaf pages contain no meaningful data). Sometimes
58672**      such a page is not even journalled (as it will not be modified,
58673**      why bother journalling it?).
58674**
58675**   2) When a free-list leaf page is reused, its content is not read
58676**      from the database or written to the journal file (why should it
58677**      be, if it is not at all meaningful?).
58678**
58679** By themselves, these optimizations work fine and provide a handy
58680** performance boost to bulk delete or insert operations. However, if
58681** a page is moved to the free-list and then reused within the same
58682** transaction, a problem comes up. If the page is not journalled when
58683** it is moved to the free-list and it is also not journalled when it
58684** is extracted from the free-list and reused, then the original data
58685** may be lost. In the event of a rollback, it may not be possible
58686** to restore the database to its original configuration.
58687**
58688** The solution is the BtShared.pHasContent bitvec. Whenever a page is
58689** moved to become a free-list leaf page, the corresponding bit is
58690** set in the bitvec. Whenever a leaf page is extracted from the free-list,
58691** optimization 2 above is omitted if the corresponding bit is already
58692** set in BtShared.pHasContent. The contents of the bitvec are cleared
58693** at the end of every transaction.
58694*/
58695static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
58696  int rc = SQLITE_OK;
58697  if( !pBt->pHasContent ){
58698    assert( pgno<=pBt->nPage );
58699    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
58700    if( !pBt->pHasContent ){
58701      rc = SQLITE_NOMEM_BKPT;
58702    }
58703  }
58704  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
58705    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
58706  }
58707  return rc;
58708}
58709
58710/*
58711** Query the BtShared.pHasContent vector.
58712**
58713** This function is called when a free-list leaf page is removed from the
58714** free-list for reuse. It returns false if it is safe to retrieve the
58715** page from the pager layer with the 'no-content' flag set. True otherwise.
58716*/
58717static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
58718  Bitvec *p = pBt->pHasContent;
58719  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
58720}
58721
58722/*
58723** Clear (destroy) the BtShared.pHasContent bitvec. This should be
58724** invoked at the conclusion of each write-transaction.
58725*/
58726static void btreeClearHasContent(BtShared *pBt){
58727  sqlite3BitvecDestroy(pBt->pHasContent);
58728  pBt->pHasContent = 0;
58729}
58730
58731/*
58732** Release all of the apPage[] pages for a cursor.
58733*/
58734static void btreeReleaseAllCursorPages(BtCursor *pCur){
58735  int i;
58736  for(i=0; i<=pCur->iPage; i++){
58737    releasePage(pCur->apPage[i]);
58738    pCur->apPage[i] = 0;
58739  }
58740  pCur->iPage = -1;
58741}
58742
58743/*
58744** The cursor passed as the only argument must point to a valid entry
58745** when this function is called (i.e. have eState==CURSOR_VALID). This
58746** function saves the current cursor key in variables pCur->nKey and
58747** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
58748** code otherwise.
58749**
58750** If the cursor is open on an intkey table, then the integer key
58751** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
58752** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
58753** set to point to a malloced buffer pCur->nKey bytes in size containing
58754** the key.
58755*/
58756static int saveCursorKey(BtCursor *pCur){
58757  int rc = SQLITE_OK;
58758  assert( CURSOR_VALID==pCur->eState );
58759  assert( 0==pCur->pKey );
58760  assert( cursorHoldsMutex(pCur) );
58761
58762  if( pCur->curIntKey ){
58763    /* Only the rowid is required for a table btree */
58764    pCur->nKey = sqlite3BtreeIntegerKey(pCur);
58765  }else{
58766    /* For an index btree, save the complete key content */
58767    void *pKey;
58768    pCur->nKey = sqlite3BtreePayloadSize(pCur);
58769    pKey = sqlite3Malloc( pCur->nKey );
58770    if( pKey ){
58771      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
58772      if( rc==SQLITE_OK ){
58773        pCur->pKey = pKey;
58774      }else{
58775        sqlite3_free(pKey);
58776      }
58777    }else{
58778      rc = SQLITE_NOMEM_BKPT;
58779    }
58780  }
58781  assert( !pCur->curIntKey || !pCur->pKey );
58782  return rc;
58783}
58784
58785/*
58786** Save the current cursor position in the variables BtCursor.nKey
58787** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
58788**
58789** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
58790** prior to calling this routine.
58791*/
58792static int saveCursorPosition(BtCursor *pCur){
58793  int rc;
58794
58795  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
58796  assert( 0==pCur->pKey );
58797  assert( cursorHoldsMutex(pCur) );
58798
58799  if( pCur->eState==CURSOR_SKIPNEXT ){
58800    pCur->eState = CURSOR_VALID;
58801  }else{
58802    pCur->skipNext = 0;
58803  }
58804
58805  rc = saveCursorKey(pCur);
58806  if( rc==SQLITE_OK ){
58807    btreeReleaseAllCursorPages(pCur);
58808    pCur->eState = CURSOR_REQUIRESEEK;
58809  }
58810
58811  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
58812  return rc;
58813}
58814
58815/* Forward reference */
58816static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
58817
58818/*
58819** Save the positions of all cursors (except pExcept) that are open on
58820** the table with root-page iRoot.  "Saving the cursor position" means that
58821** the location in the btree is remembered in such a way that it can be
58822** moved back to the same spot after the btree has been modified.  This
58823** routine is called just before cursor pExcept is used to modify the
58824** table, for example in BtreeDelete() or BtreeInsert().
58825**
58826** If there are two or more cursors on the same btree, then all such
58827** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
58828** routine enforces that rule.  This routine only needs to be called in
58829** the uncommon case when pExpect has the BTCF_Multiple flag set.
58830**
58831** If pExpect!=NULL and if no other cursors are found on the same root-page,
58832** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
58833** pointless call to this routine.
58834**
58835** Implementation note:  This routine merely checks to see if any cursors
58836** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
58837** event that cursors are in need to being saved.
58838*/
58839static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
58840  BtCursor *p;
58841  assert( sqlite3_mutex_held(pBt->mutex) );
58842  assert( pExcept==0 || pExcept->pBt==pBt );
58843  for(p=pBt->pCursor; p; p=p->pNext){
58844    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
58845  }
58846  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
58847  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
58848  return SQLITE_OK;
58849}
58850
58851/* This helper routine to saveAllCursors does the actual work of saving
58852** the cursors if and when a cursor is found that actually requires saving.
58853** The common case is that no cursors need to be saved, so this routine is
58854** broken out from its caller to avoid unnecessary stack pointer movement.
58855*/
58856static int SQLITE_NOINLINE saveCursorsOnList(
58857  BtCursor *p,         /* The first cursor that needs saving */
58858  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
58859  BtCursor *pExcept    /* Do not save this cursor */
58860){
58861  do{
58862    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
58863      if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58864        int rc = saveCursorPosition(p);
58865        if( SQLITE_OK!=rc ){
58866          return rc;
58867        }
58868      }else{
58869        testcase( p->iPage>0 );
58870        btreeReleaseAllCursorPages(p);
58871      }
58872    }
58873    p = p->pNext;
58874  }while( p );
58875  return SQLITE_OK;
58876}
58877
58878/*
58879** Clear the current cursor position.
58880*/
58881SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
58882  assert( cursorHoldsMutex(pCur) );
58883  sqlite3_free(pCur->pKey);
58884  pCur->pKey = 0;
58885  pCur->eState = CURSOR_INVALID;
58886}
58887
58888/*
58889** In this version of BtreeMoveto, pKey is a packed index record
58890** such as is generated by the OP_MakeRecord opcode.  Unpack the
58891** record and then call BtreeMovetoUnpacked() to do the work.
58892*/
58893static int btreeMoveto(
58894  BtCursor *pCur,     /* Cursor open on the btree to be searched */
58895  const void *pKey,   /* Packed key if the btree is an index */
58896  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
58897  int bias,           /* Bias search to the high end */
58898  int *pRes           /* Write search results here */
58899){
58900  int rc;                    /* Status code */
58901  UnpackedRecord *pIdxKey;   /* Unpacked index key */
58902  char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
58903  char *pFree = 0;
58904
58905  if( pKey ){
58906    assert( nKey==(i64)(int)nKey );
58907    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
58908        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
58909    );
58910    if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
58911    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
58912    if( pIdxKey->nField==0 ){
58913      sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58914      return SQLITE_CORRUPT_BKPT;
58915    }
58916  }else{
58917    pIdxKey = 0;
58918  }
58919  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
58920  if( pFree ){
58921    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58922  }
58923  return rc;
58924}
58925
58926/*
58927** Restore the cursor to the position it was in (or as close to as possible)
58928** when saveCursorPosition() was called. Note that this call deletes the
58929** saved position info stored by saveCursorPosition(), so there can be
58930** at most one effective restoreCursorPosition() call after each
58931** saveCursorPosition().
58932*/
58933static int btreeRestoreCursorPosition(BtCursor *pCur){
58934  int rc;
58935  int skipNext;
58936  assert( cursorOwnsBtShared(pCur) );
58937  assert( pCur->eState>=CURSOR_REQUIRESEEK );
58938  if( pCur->eState==CURSOR_FAULT ){
58939    return pCur->skipNext;
58940  }
58941  pCur->eState = CURSOR_INVALID;
58942  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
58943  if( rc==SQLITE_OK ){
58944    sqlite3_free(pCur->pKey);
58945    pCur->pKey = 0;
58946    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
58947    pCur->skipNext |= skipNext;
58948    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
58949      pCur->eState = CURSOR_SKIPNEXT;
58950    }
58951  }
58952  return rc;
58953}
58954
58955#define restoreCursorPosition(p) \
58956  (p->eState>=CURSOR_REQUIRESEEK ? \
58957         btreeRestoreCursorPosition(p) : \
58958         SQLITE_OK)
58959
58960/*
58961** Determine whether or not a cursor has moved from the position where
58962** it was last placed, or has been invalidated for any other reason.
58963** Cursors can move when the row they are pointing at is deleted out
58964** from under them, for example.  Cursor might also move if a btree
58965** is rebalanced.
58966**
58967** Calling this routine with a NULL cursor pointer returns false.
58968**
58969** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
58970** back to where it ought to be if this routine returns true.
58971*/
58972SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
58973  return pCur->eState!=CURSOR_VALID;
58974}
58975
58976/*
58977** This routine restores a cursor back to its original position after it
58978** has been moved by some outside activity (such as a btree rebalance or
58979** a row having been deleted out from under the cursor).
58980**
58981** On success, the *pDifferentRow parameter is false if the cursor is left
58982** pointing at exactly the same row.  *pDifferntRow is the row the cursor
58983** was pointing to has been deleted, forcing the cursor to point to some
58984** nearby row.
58985**
58986** This routine should only be called for a cursor that just returned
58987** TRUE from sqlite3BtreeCursorHasMoved().
58988*/
58989SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
58990  int rc;
58991
58992  assert( pCur!=0 );
58993  assert( pCur->eState!=CURSOR_VALID );
58994  rc = restoreCursorPosition(pCur);
58995  if( rc ){
58996    *pDifferentRow = 1;
58997    return rc;
58998  }
58999  if( pCur->eState!=CURSOR_VALID ){
59000    *pDifferentRow = 1;
59001  }else{
59002    assert( pCur->skipNext==0 );
59003    *pDifferentRow = 0;
59004  }
59005  return SQLITE_OK;
59006}
59007
59008#ifdef SQLITE_ENABLE_CURSOR_HINTS
59009/*
59010** Provide hints to the cursor.  The particular hint given (and the type
59011** and number of the varargs parameters) is determined by the eHintType
59012** parameter.  See the definitions of the BTREE_HINT_* macros for details.
59013*/
59014SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
59015  /* Used only by system that substitute their own storage engine */
59016}
59017#endif
59018
59019/*
59020** Provide flag hints to the cursor.
59021*/
59022SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
59023  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
59024  pCur->hints = x;
59025}
59026
59027
59028#ifndef SQLITE_OMIT_AUTOVACUUM
59029/*
59030** Given a page number of a regular database page, return the page
59031** number for the pointer-map page that contains the entry for the
59032** input page number.
59033**
59034** Return 0 (not a valid page) for pgno==1 since there is
59035** no pointer map associated with page 1.  The integrity_check logic
59036** requires that ptrmapPageno(*,1)!=1.
59037*/
59038static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
59039  int nPagesPerMapPage;
59040  Pgno iPtrMap, ret;
59041  assert( sqlite3_mutex_held(pBt->mutex) );
59042  if( pgno<2 ) return 0;
59043  nPagesPerMapPage = (pBt->usableSize/5)+1;
59044  iPtrMap = (pgno-2)/nPagesPerMapPage;
59045  ret = (iPtrMap*nPagesPerMapPage) + 2;
59046  if( ret==PENDING_BYTE_PAGE(pBt) ){
59047    ret++;
59048  }
59049  return ret;
59050}
59051
59052/*
59053** Write an entry into the pointer map.
59054**
59055** This routine updates the pointer map entry for page number 'key'
59056** so that it maps to type 'eType' and parent page number 'pgno'.
59057**
59058** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
59059** a no-op.  If an error occurs, the appropriate error code is written
59060** into *pRC.
59061*/
59062static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
59063  DbPage *pDbPage;  /* The pointer map page */
59064  u8 *pPtrmap;      /* The pointer map data */
59065  Pgno iPtrmap;     /* The pointer map page number */
59066  int offset;       /* Offset in pointer map page */
59067  int rc;           /* Return code from subfunctions */
59068
59069  if( *pRC ) return;
59070
59071  assert( sqlite3_mutex_held(pBt->mutex) );
59072  /* The master-journal page number must never be used as a pointer map page */
59073  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
59074
59075  assert( pBt->autoVacuum );
59076  if( key==0 ){
59077    *pRC = SQLITE_CORRUPT_BKPT;
59078    return;
59079  }
59080  iPtrmap = PTRMAP_PAGENO(pBt, key);
59081  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59082  if( rc!=SQLITE_OK ){
59083    *pRC = rc;
59084    return;
59085  }
59086  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59087  if( offset<0 ){
59088    *pRC = SQLITE_CORRUPT_BKPT;
59089    goto ptrmap_exit;
59090  }
59091  assert( offset <= (int)pBt->usableSize-5 );
59092  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59093
59094  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
59095    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
59096    *pRC= rc = sqlite3PagerWrite(pDbPage);
59097    if( rc==SQLITE_OK ){
59098      pPtrmap[offset] = eType;
59099      put4byte(&pPtrmap[offset+1], parent);
59100    }
59101  }
59102
59103ptrmap_exit:
59104  sqlite3PagerUnref(pDbPage);
59105}
59106
59107/*
59108** Read an entry from the pointer map.
59109**
59110** This routine retrieves the pointer map entry for page 'key', writing
59111** the type and parent page number to *pEType and *pPgno respectively.
59112** An error code is returned if something goes wrong, otherwise SQLITE_OK.
59113*/
59114static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
59115  DbPage *pDbPage;   /* The pointer map page */
59116  int iPtrmap;       /* Pointer map page index */
59117  u8 *pPtrmap;       /* Pointer map page data */
59118  int offset;        /* Offset of entry in pointer map */
59119  int rc;
59120
59121  assert( sqlite3_mutex_held(pBt->mutex) );
59122
59123  iPtrmap = PTRMAP_PAGENO(pBt, key);
59124  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59125  if( rc!=0 ){
59126    return rc;
59127  }
59128  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59129
59130  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59131  if( offset<0 ){
59132    sqlite3PagerUnref(pDbPage);
59133    return SQLITE_CORRUPT_BKPT;
59134  }
59135  assert( offset <= (int)pBt->usableSize-5 );
59136  assert( pEType!=0 );
59137  *pEType = pPtrmap[offset];
59138  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
59139
59140  sqlite3PagerUnref(pDbPage);
59141  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
59142  return SQLITE_OK;
59143}
59144
59145#else /* if defined SQLITE_OMIT_AUTOVACUUM */
59146  #define ptrmapPut(w,x,y,z,rc)
59147  #define ptrmapGet(w,x,y,z) SQLITE_OK
59148  #define ptrmapPutOvflPtr(x, y, rc)
59149#endif
59150
59151/*
59152** Given a btree page and a cell index (0 means the first cell on
59153** the page, 1 means the second cell, and so forth) return a pointer
59154** to the cell content.
59155**
59156** findCellPastPtr() does the same except it skips past the initial
59157** 4-byte child pointer found on interior pages, if there is one.
59158**
59159** This routine works only for pages that do not contain overflow cells.
59160*/
59161#define findCell(P,I) \
59162  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59163#define findCellPastPtr(P,I) \
59164  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59165
59166
59167/*
59168** This is common tail processing for btreeParseCellPtr() and
59169** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
59170** on a single B-tree page.  Make necessary adjustments to the CellInfo
59171** structure.
59172*/
59173static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
59174  MemPage *pPage,         /* Page containing the cell */
59175  u8 *pCell,              /* Pointer to the cell text. */
59176  CellInfo *pInfo         /* Fill in this structure */
59177){
59178  /* If the payload will not fit completely on the local page, we have
59179  ** to decide how much to store locally and how much to spill onto
59180  ** overflow pages.  The strategy is to minimize the amount of unused
59181  ** space on overflow pages while keeping the amount of local storage
59182  ** in between minLocal and maxLocal.
59183  **
59184  ** Warning:  changing the way overflow payload is distributed in any
59185  ** way will result in an incompatible file format.
59186  */
59187  int minLocal;  /* Minimum amount of payload held locally */
59188  int maxLocal;  /* Maximum amount of payload held locally */
59189  int surplus;   /* Overflow payload available for local storage */
59190
59191  minLocal = pPage->minLocal;
59192  maxLocal = pPage->maxLocal;
59193  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
59194  testcase( surplus==maxLocal );
59195  testcase( surplus==maxLocal+1 );
59196  if( surplus <= maxLocal ){
59197    pInfo->nLocal = (u16)surplus;
59198  }else{
59199    pInfo->nLocal = (u16)minLocal;
59200  }
59201  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
59202}
59203
59204/*
59205** The following routines are implementations of the MemPage.xParseCell()
59206** method.
59207**
59208** Parse a cell content block and fill in the CellInfo structure.
59209**
59210** btreeParseCellPtr()        =>   table btree leaf nodes
59211** btreeParseCellNoPayload()  =>   table btree internal nodes
59212** btreeParseCellPtrIndex()   =>   index btree nodes
59213**
59214** There is also a wrapper function btreeParseCell() that works for
59215** all MemPage types and that references the cell by index rather than
59216** by pointer.
59217*/
59218static void btreeParseCellPtrNoPayload(
59219  MemPage *pPage,         /* Page containing the cell */
59220  u8 *pCell,              /* Pointer to the cell text. */
59221  CellInfo *pInfo         /* Fill in this structure */
59222){
59223  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59224  assert( pPage->leaf==0 );
59225  assert( pPage->childPtrSize==4 );
59226#ifndef SQLITE_DEBUG
59227  UNUSED_PARAMETER(pPage);
59228#endif
59229  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
59230  pInfo->nPayload = 0;
59231  pInfo->nLocal = 0;
59232  pInfo->pPayload = 0;
59233  return;
59234}
59235static void btreeParseCellPtr(
59236  MemPage *pPage,         /* Page containing the cell */
59237  u8 *pCell,              /* Pointer to the cell text. */
59238  CellInfo *pInfo         /* Fill in this structure */
59239){
59240  u8 *pIter;              /* For scanning through pCell */
59241  u32 nPayload;           /* Number of bytes of cell payload */
59242  u64 iKey;               /* Extracted Key value */
59243
59244  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59245  assert( pPage->leaf==0 || pPage->leaf==1 );
59246  assert( pPage->intKeyLeaf );
59247  assert( pPage->childPtrSize==0 );
59248  pIter = pCell;
59249
59250  /* The next block of code is equivalent to:
59251  **
59252  **     pIter += getVarint32(pIter, nPayload);
59253  **
59254  ** The code is inlined to avoid a function call.
59255  */
59256  nPayload = *pIter;
59257  if( nPayload>=0x80 ){
59258    u8 *pEnd = &pIter[8];
59259    nPayload &= 0x7f;
59260    do{
59261      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59262    }while( (*pIter)>=0x80 && pIter<pEnd );
59263  }
59264  pIter++;
59265
59266  /* The next block of code is equivalent to:
59267  **
59268  **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
59269  **
59270  ** The code is inlined to avoid a function call.
59271  */
59272  iKey = *pIter;
59273  if( iKey>=0x80 ){
59274    u8 *pEnd = &pIter[7];
59275    iKey &= 0x7f;
59276    while(1){
59277      iKey = (iKey<<7) | (*++pIter & 0x7f);
59278      if( (*pIter)<0x80 ) break;
59279      if( pIter>=pEnd ){
59280        iKey = (iKey<<8) | *++pIter;
59281        break;
59282      }
59283    }
59284  }
59285  pIter++;
59286
59287  pInfo->nKey = *(i64*)&iKey;
59288  pInfo->nPayload = nPayload;
59289  pInfo->pPayload = pIter;
59290  testcase( nPayload==pPage->maxLocal );
59291  testcase( nPayload==pPage->maxLocal+1 );
59292  if( nPayload<=pPage->maxLocal ){
59293    /* This is the (easy) common case where the entire payload fits
59294    ** on the local page.  No overflow is required.
59295    */
59296    pInfo->nSize = nPayload + (u16)(pIter - pCell);
59297    if( pInfo->nSize<4 ) pInfo->nSize = 4;
59298    pInfo->nLocal = (u16)nPayload;
59299  }else{
59300    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59301  }
59302}
59303static void btreeParseCellPtrIndex(
59304  MemPage *pPage,         /* Page containing the cell */
59305  u8 *pCell,              /* Pointer to the cell text. */
59306  CellInfo *pInfo         /* Fill in this structure */
59307){
59308  u8 *pIter;              /* For scanning through pCell */
59309  u32 nPayload;           /* Number of bytes of cell payload */
59310
59311  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59312  assert( pPage->leaf==0 || pPage->leaf==1 );
59313  assert( pPage->intKeyLeaf==0 );
59314  pIter = pCell + pPage->childPtrSize;
59315  nPayload = *pIter;
59316  if( nPayload>=0x80 ){
59317    u8 *pEnd = &pIter[8];
59318    nPayload &= 0x7f;
59319    do{
59320      nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59321    }while( *(pIter)>=0x80 && pIter<pEnd );
59322  }
59323  pIter++;
59324  pInfo->nKey = nPayload;
59325  pInfo->nPayload = nPayload;
59326  pInfo->pPayload = pIter;
59327  testcase( nPayload==pPage->maxLocal );
59328  testcase( nPayload==pPage->maxLocal+1 );
59329  if( nPayload<=pPage->maxLocal ){
59330    /* This is the (easy) common case where the entire payload fits
59331    ** on the local page.  No overflow is required.
59332    */
59333    pInfo->nSize = nPayload + (u16)(pIter - pCell);
59334    if( pInfo->nSize<4 ) pInfo->nSize = 4;
59335    pInfo->nLocal = (u16)nPayload;
59336  }else{
59337    btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59338  }
59339}
59340static void btreeParseCell(
59341  MemPage *pPage,         /* Page containing the cell */
59342  int iCell,              /* The cell index.  First cell is 0 */
59343  CellInfo *pInfo         /* Fill in this structure */
59344){
59345  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
59346}
59347
59348/*
59349** The following routines are implementations of the MemPage.xCellSize
59350** method.
59351**
59352** Compute the total number of bytes that a Cell needs in the cell
59353** data area of the btree-page.  The return number includes the cell
59354** data header and the local payload, but not any overflow page or
59355** the space used by the cell pointer.
59356**
59357** cellSizePtrNoPayload()    =>   table internal nodes
59358** cellSizePtr()             =>   all index nodes & table leaf nodes
59359*/
59360static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
59361  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
59362  u8 *pEnd;                                /* End mark for a varint */
59363  u32 nSize;                               /* Size value to return */
59364
59365#ifdef SQLITE_DEBUG
59366  /* The value returned by this function should always be the same as
59367  ** the (CellInfo.nSize) value found by doing a full parse of the
59368  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59369  ** this function verifies that this invariant is not violated. */
59370  CellInfo debuginfo;
59371  pPage->xParseCell(pPage, pCell, &debuginfo);
59372#endif
59373
59374  nSize = *pIter;
59375  if( nSize>=0x80 ){
59376    pEnd = &pIter[8];
59377    nSize &= 0x7f;
59378    do{
59379      nSize = (nSize<<7) | (*++pIter & 0x7f);
59380    }while( *(pIter)>=0x80 && pIter<pEnd );
59381  }
59382  pIter++;
59383  if( pPage->intKey ){
59384    /* pIter now points at the 64-bit integer key value, a variable length
59385    ** integer. The following block moves pIter to point at the first byte
59386    ** past the end of the key value. */
59387    pEnd = &pIter[9];
59388    while( (*pIter++)&0x80 && pIter<pEnd );
59389  }
59390  testcase( nSize==pPage->maxLocal );
59391  testcase( nSize==pPage->maxLocal+1 );
59392  if( nSize<=pPage->maxLocal ){
59393    nSize += (u32)(pIter - pCell);
59394    if( nSize<4 ) nSize = 4;
59395  }else{
59396    int minLocal = pPage->minLocal;
59397    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
59398    testcase( nSize==pPage->maxLocal );
59399    testcase( nSize==pPage->maxLocal+1 );
59400    if( nSize>pPage->maxLocal ){
59401      nSize = minLocal;
59402    }
59403    nSize += 4 + (u16)(pIter - pCell);
59404  }
59405  assert( nSize==debuginfo.nSize || CORRUPT_DB );
59406  return (u16)nSize;
59407}
59408static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
59409  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
59410  u8 *pEnd;              /* End mark for a varint */
59411
59412#ifdef SQLITE_DEBUG
59413  /* The value returned by this function should always be the same as
59414  ** the (CellInfo.nSize) value found by doing a full parse of the
59415  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59416  ** this function verifies that this invariant is not violated. */
59417  CellInfo debuginfo;
59418  pPage->xParseCell(pPage, pCell, &debuginfo);
59419#else
59420  UNUSED_PARAMETER(pPage);
59421#endif
59422
59423  assert( pPage->childPtrSize==4 );
59424  pEnd = pIter + 9;
59425  while( (*pIter++)&0x80 && pIter<pEnd );
59426  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
59427  return (u16)(pIter - pCell);
59428}
59429
59430
59431#ifdef SQLITE_DEBUG
59432/* This variation on cellSizePtr() is used inside of assert() statements
59433** only. */
59434static u16 cellSize(MemPage *pPage, int iCell){
59435  return pPage->xCellSize(pPage, findCell(pPage, iCell));
59436}
59437#endif
59438
59439#ifndef SQLITE_OMIT_AUTOVACUUM
59440/*
59441** If the cell pCell, part of page pPage contains a pointer
59442** to an overflow page, insert an entry into the pointer-map
59443** for the overflow page.
59444*/
59445static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
59446  CellInfo info;
59447  if( *pRC ) return;
59448  assert( pCell!=0 );
59449  pPage->xParseCell(pPage, pCell, &info);
59450  if( info.nLocal<info.nPayload ){
59451    Pgno ovfl = get4byte(&pCell[info.nSize-4]);
59452    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
59453  }
59454}
59455#endif
59456
59457
59458/*
59459** Defragment the page given.  All Cells are moved to the
59460** end of the page and all free space is collected into one
59461** big FreeBlk that occurs in between the header and cell
59462** pointer array and the cell content area.
59463**
59464** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
59465** b-tree page so that there are no freeblocks or fragment bytes, all
59466** unused bytes are contained in the unallocated space region, and all
59467** cells are packed tightly at the end of the page.
59468*/
59469static int defragmentPage(MemPage *pPage){
59470  int i;                     /* Loop counter */
59471  int pc;                    /* Address of the i-th cell */
59472  int hdr;                   /* Offset to the page header */
59473  int size;                  /* Size of a cell */
59474  int usableSize;            /* Number of usable bytes on a page */
59475  int cellOffset;            /* Offset to the cell pointer array */
59476  int cbrk;                  /* Offset to the cell content area */
59477  int nCell;                 /* Number of cells on the page */
59478  unsigned char *data;       /* The page data */
59479  unsigned char *temp;       /* Temp area for cell content */
59480  unsigned char *src;        /* Source of content */
59481  int iCellFirst;            /* First allowable cell index */
59482  int iCellLast;             /* Last possible cell index */
59483
59484
59485  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59486  assert( pPage->pBt!=0 );
59487  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
59488  assert( pPage->nOverflow==0 );
59489  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59490  temp = 0;
59491  src = data = pPage->aData;
59492  hdr = pPage->hdrOffset;
59493  cellOffset = pPage->cellOffset;
59494  nCell = pPage->nCell;
59495  assert( nCell==get2byte(&data[hdr+3]) );
59496  usableSize = pPage->pBt->usableSize;
59497  cbrk = usableSize;
59498  iCellFirst = cellOffset + 2*nCell;
59499  iCellLast = usableSize - 4;
59500  for(i=0; i<nCell; i++){
59501    u8 *pAddr;     /* The i-th cell pointer */
59502    pAddr = &data[cellOffset + i*2];
59503    pc = get2byte(pAddr);
59504    testcase( pc==iCellFirst );
59505    testcase( pc==iCellLast );
59506    /* These conditions have already been verified in btreeInitPage()
59507    ** if PRAGMA cell_size_check=ON.
59508    */
59509    if( pc<iCellFirst || pc>iCellLast ){
59510      return SQLITE_CORRUPT_BKPT;
59511    }
59512    assert( pc>=iCellFirst && pc<=iCellLast );
59513    size = pPage->xCellSize(pPage, &src[pc]);
59514    cbrk -= size;
59515    if( cbrk<iCellFirst || pc+size>usableSize ){
59516      return SQLITE_CORRUPT_BKPT;
59517    }
59518    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
59519    testcase( cbrk+size==usableSize );
59520    testcase( pc+size==usableSize );
59521    put2byte(pAddr, cbrk);
59522    if( temp==0 ){
59523      int x;
59524      if( cbrk==pc ) continue;
59525      temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
59526      x = get2byte(&data[hdr+5]);
59527      memcpy(&temp[x], &data[x], (cbrk+size) - x);
59528      src = temp;
59529    }
59530    memcpy(&data[cbrk], &src[pc], size);
59531  }
59532  assert( cbrk>=iCellFirst );
59533  put2byte(&data[hdr+5], cbrk);
59534  data[hdr+1] = 0;
59535  data[hdr+2] = 0;
59536  data[hdr+7] = 0;
59537  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
59538  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59539  if( cbrk-iCellFirst!=pPage->nFree ){
59540    return SQLITE_CORRUPT_BKPT;
59541  }
59542  return SQLITE_OK;
59543}
59544
59545/*
59546** Search the free-list on page pPg for space to store a cell nByte bytes in
59547** size. If one can be found, return a pointer to the space and remove it
59548** from the free-list.
59549**
59550** If no suitable space can be found on the free-list, return NULL.
59551**
59552** This function may detect corruption within pPg.  If corruption is
59553** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
59554**
59555** Slots on the free list that are between 1 and 3 bytes larger than nByte
59556** will be ignored if adding the extra space to the fragmentation count
59557** causes the fragmentation count to exceed 60.
59558*/
59559static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
59560  const int hdr = pPg->hdrOffset;
59561  u8 * const aData = pPg->aData;
59562  int iAddr = hdr + 1;
59563  int pc = get2byte(&aData[iAddr]);
59564  int x;
59565  int usableSize = pPg->pBt->usableSize;
59566
59567  assert( pc>0 );
59568  do{
59569    int size;            /* Size of the free slot */
59570    /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
59571    ** increasing offset. */
59572    if( pc>usableSize-4 || pc<iAddr+4 ){
59573      *pRc = SQLITE_CORRUPT_BKPT;
59574      return 0;
59575    }
59576    /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
59577    ** freeblock form a big-endian integer which is the size of the freeblock
59578    ** in bytes, including the 4-byte header. */
59579    size = get2byte(&aData[pc+2]);
59580    if( (x = size - nByte)>=0 ){
59581      testcase( x==4 );
59582      testcase( x==3 );
59583      if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
59584        *pRc = SQLITE_CORRUPT_BKPT;
59585        return 0;
59586      }else if( x<4 ){
59587        /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
59588        ** number of bytes in fragments may not exceed 60. */
59589        if( aData[hdr+7]>57 ) return 0;
59590
59591        /* Remove the slot from the free-list. Update the number of
59592        ** fragmented bytes within the page. */
59593        memcpy(&aData[iAddr], &aData[pc], 2);
59594        aData[hdr+7] += (u8)x;
59595      }else{
59596        /* The slot remains on the free-list. Reduce its size to account
59597         ** for the portion used by the new allocation. */
59598        put2byte(&aData[pc+2], x);
59599      }
59600      return &aData[pc + x];
59601    }
59602    iAddr = pc;
59603    pc = get2byte(&aData[pc]);
59604  }while( pc );
59605
59606  return 0;
59607}
59608
59609/*
59610** Allocate nByte bytes of space from within the B-Tree page passed
59611** as the first argument. Write into *pIdx the index into pPage->aData[]
59612** of the first byte of allocated space. Return either SQLITE_OK or
59613** an error code (usually SQLITE_CORRUPT).
59614**
59615** The caller guarantees that there is sufficient space to make the
59616** allocation.  This routine might need to defragment in order to bring
59617** all the space together, however.  This routine will avoid using
59618** the first two bytes past the cell pointer area since presumably this
59619** allocation is being made in order to insert a new cell, so we will
59620** also end up needing a new cell pointer.
59621*/
59622static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
59623  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
59624  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
59625  int top;                             /* First byte of cell content area */
59626  int rc = SQLITE_OK;                  /* Integer return code */
59627  int gap;        /* First byte of gap between cell pointers and cell content */
59628
59629  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59630  assert( pPage->pBt );
59631  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59632  assert( nByte>=0 );  /* Minimum cell size is 4 */
59633  assert( pPage->nFree>=nByte );
59634  assert( pPage->nOverflow==0 );
59635  assert( nByte < (int)(pPage->pBt->usableSize-8) );
59636
59637  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
59638  gap = pPage->cellOffset + 2*pPage->nCell;
59639  assert( gap<=65536 );
59640  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
59641  ** and the reserved space is zero (the usual value for reserved space)
59642  ** then the cell content offset of an empty page wants to be 65536.
59643  ** However, that integer is too large to be stored in a 2-byte unsigned
59644  ** integer, so a value of 0 is used in its place. */
59645  top = get2byte(&data[hdr+5]);
59646  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
59647  if( gap>top ){
59648    if( top==0 && pPage->pBt->usableSize==65536 ){
59649      top = 65536;
59650    }else{
59651      return SQLITE_CORRUPT_BKPT;
59652    }
59653  }
59654
59655  /* If there is enough space between gap and top for one more cell pointer
59656  ** array entry offset, and if the freelist is not empty, then search the
59657  ** freelist looking for a free slot big enough to satisfy the request.
59658  */
59659  testcase( gap+2==top );
59660  testcase( gap+1==top );
59661  testcase( gap==top );
59662  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
59663    u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
59664    if( pSpace ){
59665      assert( pSpace>=data && (pSpace - data)<65536 );
59666      *pIdx = (int)(pSpace - data);
59667      return SQLITE_OK;
59668    }else if( rc ){
59669      return rc;
59670    }
59671  }
59672
59673  /* The request could not be fulfilled using a freelist slot.  Check
59674  ** to see if defragmentation is necessary.
59675  */
59676  testcase( gap+2+nByte==top );
59677  if( gap+2+nByte>top ){
59678    assert( pPage->nCell>0 || CORRUPT_DB );
59679    rc = defragmentPage(pPage);
59680    if( rc ) return rc;
59681    top = get2byteNotZero(&data[hdr+5]);
59682    assert( gap+nByte<=top );
59683  }
59684
59685
59686  /* Allocate memory from the gap in between the cell pointer array
59687  ** and the cell content area.  The btreeInitPage() call has already
59688  ** validated the freelist.  Given that the freelist is valid, there
59689  ** is no way that the allocation can extend off the end of the page.
59690  ** The assert() below verifies the previous sentence.
59691  */
59692  top -= nByte;
59693  put2byte(&data[hdr+5], top);
59694  assert( top+nByte <= (int)pPage->pBt->usableSize );
59695  *pIdx = top;
59696  return SQLITE_OK;
59697}
59698
59699/*
59700** Return a section of the pPage->aData to the freelist.
59701** The first byte of the new free block is pPage->aData[iStart]
59702** and the size of the block is iSize bytes.
59703**
59704** Adjacent freeblocks are coalesced.
59705**
59706** Note that even though the freeblock list was checked by btreeInitPage(),
59707** that routine will not detect overlap between cells or freeblocks.  Nor
59708** does it detect cells or freeblocks that encrouch into the reserved bytes
59709** at the end of the page.  So do additional corruption checks inside this
59710** routine and return SQLITE_CORRUPT if any problems are found.
59711*/
59712static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
59713  u16 iPtr;                             /* Address of ptr to next freeblock */
59714  u16 iFreeBlk;                         /* Address of the next freeblock */
59715  u8 hdr;                               /* Page header size.  0 or 100 */
59716  u8 nFrag = 0;                         /* Reduction in fragmentation */
59717  u16 iOrigSize = iSize;                /* Original value of iSize */
59718  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
59719  u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
59720  unsigned char *data = pPage->aData;   /* Page content */
59721
59722  assert( pPage->pBt!=0 );
59723  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59724  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
59725  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
59726  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59727  assert( iSize>=4 );   /* Minimum cell size is 4 */
59728  assert( iStart<=iLast );
59729
59730  /* Overwrite deleted information with zeros when the secure_delete
59731  ** option is enabled */
59732  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
59733    memset(&data[iStart], 0, iSize);
59734  }
59735
59736  /* The list of freeblocks must be in ascending order.  Find the
59737  ** spot on the list where iStart should be inserted.
59738  */
59739  hdr = pPage->hdrOffset;
59740  iPtr = hdr + 1;
59741  if( data[iPtr+1]==0 && data[iPtr]==0 ){
59742    iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
59743  }else{
59744    while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
59745      if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
59746      iPtr = iFreeBlk;
59747    }
59748    if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
59749    assert( iFreeBlk>iPtr || iFreeBlk==0 );
59750
59751    /* At this point:
59752    **    iFreeBlk:   First freeblock after iStart, or zero if none
59753    **    iPtr:       The address of a pointer to iFreeBlk
59754    **
59755    ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
59756    */
59757    if( iFreeBlk && iEnd+3>=iFreeBlk ){
59758      nFrag = iFreeBlk - iEnd;
59759      if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
59760      iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
59761      if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
59762      iSize = iEnd - iStart;
59763      iFreeBlk = get2byte(&data[iFreeBlk]);
59764    }
59765
59766    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
59767    ** pointer in the page header) then check to see if iStart should be
59768    ** coalesced onto the end of iPtr.
59769    */
59770    if( iPtr>hdr+1 ){
59771      int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
59772      if( iPtrEnd+3>=iStart ){
59773        if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
59774        nFrag += iStart - iPtrEnd;
59775        iSize = iEnd - iPtr;
59776        iStart = iPtr;
59777      }
59778    }
59779    if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
59780    data[hdr+7] -= nFrag;
59781  }
59782  if( iStart==get2byte(&data[hdr+5]) ){
59783    /* The new freeblock is at the beginning of the cell content area,
59784    ** so just extend the cell content area rather than create another
59785    ** freelist entry */
59786    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
59787    put2byte(&data[hdr+1], iFreeBlk);
59788    put2byte(&data[hdr+5], iEnd);
59789  }else{
59790    /* Insert the new freeblock into the freelist */
59791    put2byte(&data[iPtr], iStart);
59792    put2byte(&data[iStart], iFreeBlk);
59793    put2byte(&data[iStart+2], iSize);
59794  }
59795  pPage->nFree += iOrigSize;
59796  return SQLITE_OK;
59797}
59798
59799/*
59800** Decode the flags byte (the first byte of the header) for a page
59801** and initialize fields of the MemPage structure accordingly.
59802**
59803** Only the following combinations are supported.  Anything different
59804** indicates a corrupt database files:
59805**
59806**         PTF_ZERODATA
59807**         PTF_ZERODATA | PTF_LEAF
59808**         PTF_LEAFDATA | PTF_INTKEY
59809**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
59810*/
59811static int decodeFlags(MemPage *pPage, int flagByte){
59812  BtShared *pBt;     /* A copy of pPage->pBt */
59813
59814  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
59815  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59816  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
59817  flagByte &= ~PTF_LEAF;
59818  pPage->childPtrSize = 4-4*pPage->leaf;
59819  pPage->xCellSize = cellSizePtr;
59820  pBt = pPage->pBt;
59821  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59822    /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59823    ** interior table b-tree page. */
59824    assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59825    /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59826    ** leaf table b-tree page. */
59827    assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
59828    pPage->intKey = 1;
59829    if( pPage->leaf ){
59830      pPage->intKeyLeaf = 1;
59831      pPage->xParseCell = btreeParseCellPtr;
59832    }else{
59833      pPage->intKeyLeaf = 0;
59834      pPage->xCellSize = cellSizePtrNoPayload;
59835      pPage->xParseCell = btreeParseCellPtrNoPayload;
59836    }
59837    pPage->maxLocal = pBt->maxLeaf;
59838    pPage->minLocal = pBt->minLeaf;
59839  }else if( flagByte==PTF_ZERODATA ){
59840    /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59841    ** interior index b-tree page. */
59842    assert( (PTF_ZERODATA)==2 );
59843    /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59844    ** leaf index b-tree page. */
59845    assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59846    pPage->intKey = 0;
59847    pPage->intKeyLeaf = 0;
59848    pPage->xParseCell = btreeParseCellPtrIndex;
59849    pPage->maxLocal = pBt->maxLocal;
59850    pPage->minLocal = pBt->minLocal;
59851  }else{
59852    /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
59853    ** an error. */
59854    return SQLITE_CORRUPT_BKPT;
59855  }
59856  pPage->max1bytePayload = pBt->max1bytePayload;
59857  return SQLITE_OK;
59858}
59859
59860/*
59861** Initialize the auxiliary information for a disk block.
59862**
59863** Return SQLITE_OK on success.  If we see that the page does
59864** not contain a well-formed database page, then return
59865** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
59866** guarantee that the page is well-formed.  It only shows that
59867** we failed to detect any corruption.
59868*/
59869static int btreeInitPage(MemPage *pPage){
59870
59871  assert( pPage->pBt!=0 );
59872  assert( pPage->pBt->db!=0 );
59873  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59874  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
59875  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
59876  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
59877
59878  if( !pPage->isInit ){
59879    u16 pc;            /* Address of a freeblock within pPage->aData[] */
59880    u8 hdr;            /* Offset to beginning of page header */
59881    u8 *data;          /* Equal to pPage->aData */
59882    BtShared *pBt;        /* The main btree structure */
59883    int usableSize;    /* Amount of usable space on each page */
59884    u16 cellOffset;    /* Offset from start of page to first cell pointer */
59885    int nFree;         /* Number of unused bytes on the page */
59886    int top;           /* First byte of the cell content area */
59887    int iCellFirst;    /* First allowable cell or freeblock offset */
59888    int iCellLast;     /* Last possible cell or freeblock offset */
59889
59890    pBt = pPage->pBt;
59891
59892    hdr = pPage->hdrOffset;
59893    data = pPage->aData;
59894    /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
59895    ** the b-tree page type. */
59896    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
59897    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
59898    pPage->maskPage = (u16)(pBt->pageSize - 1);
59899    pPage->nOverflow = 0;
59900    usableSize = pBt->usableSize;
59901    pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
59902    pPage->aDataEnd = &data[usableSize];
59903    pPage->aCellIdx = &data[cellOffset];
59904    pPage->aDataOfst = &data[pPage->childPtrSize];
59905    /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
59906    ** the start of the cell content area. A zero value for this integer is
59907    ** interpreted as 65536. */
59908    top = get2byteNotZero(&data[hdr+5]);
59909    /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
59910    ** number of cells on the page. */
59911    pPage->nCell = get2byte(&data[hdr+3]);
59912    if( pPage->nCell>MX_CELL(pBt) ){
59913      /* To many cells for a single page.  The page must be corrupt */
59914      return SQLITE_CORRUPT_BKPT;
59915    }
59916    testcase( pPage->nCell==MX_CELL(pBt) );
59917    /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
59918    ** possible for a root page of a table that contains no rows) then the
59919    ** offset to the cell content area will equal the page size minus the
59920    ** bytes of reserved space. */
59921    assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
59922
59923    /* A malformed database page might cause us to read past the end
59924    ** of page when parsing a cell.
59925    **
59926    ** The following block of code checks early to see if a cell extends
59927    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
59928    ** returned if it does.
59929    */
59930    iCellFirst = cellOffset + 2*pPage->nCell;
59931    iCellLast = usableSize - 4;
59932    if( pBt->db->flags & SQLITE_CellSizeCk ){
59933      int i;            /* Index into the cell pointer array */
59934      int sz;           /* Size of a cell */
59935
59936      if( !pPage->leaf ) iCellLast--;
59937      for(i=0; i<pPage->nCell; i++){
59938        pc = get2byteAligned(&data[cellOffset+i*2]);
59939        testcase( pc==iCellFirst );
59940        testcase( pc==iCellLast );
59941        if( pc<iCellFirst || pc>iCellLast ){
59942          return SQLITE_CORRUPT_BKPT;
59943        }
59944        sz = pPage->xCellSize(pPage, &data[pc]);
59945        testcase( pc+sz==usableSize );
59946        if( pc+sz>usableSize ){
59947          return SQLITE_CORRUPT_BKPT;
59948        }
59949      }
59950      if( !pPage->leaf ) iCellLast++;
59951    }
59952
59953    /* Compute the total free space on the page
59954    ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
59955    ** start of the first freeblock on the page, or is zero if there are no
59956    ** freeblocks. */
59957    pc = get2byte(&data[hdr+1]);
59958    nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
59959    while( pc>0 ){
59960      u16 next, size;
59961      if( pc<iCellFirst || pc>iCellLast ){
59962        /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
59963        ** always be at least one cell before the first freeblock.
59964        **
59965        ** Or, the freeblock is off the end of the page
59966        */
59967        return SQLITE_CORRUPT_BKPT;
59968      }
59969      next = get2byte(&data[pc]);
59970      size = get2byte(&data[pc+2]);
59971      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
59972        /* Free blocks must be in ascending order. And the last byte of
59973        ** the free-block must lie on the database page.  */
59974        return SQLITE_CORRUPT_BKPT;
59975      }
59976      nFree = nFree + size;
59977      pc = next;
59978    }
59979
59980    /* At this point, nFree contains the sum of the offset to the start
59981    ** of the cell-content area plus the number of free bytes within
59982    ** the cell-content area. If this is greater than the usable-size
59983    ** of the page, then the page must be corrupted. This check also
59984    ** serves to verify that the offset to the start of the cell-content
59985    ** area, according to the page header, lies within the page.
59986    */
59987    if( nFree>usableSize ){
59988      return SQLITE_CORRUPT_BKPT;
59989    }
59990    pPage->nFree = (u16)(nFree - iCellFirst);
59991    pPage->isInit = 1;
59992  }
59993  return SQLITE_OK;
59994}
59995
59996/*
59997** Set up a raw page so that it looks like a database page holding
59998** no entries.
59999*/
60000static void zeroPage(MemPage *pPage, int flags){
60001  unsigned char *data = pPage->aData;
60002  BtShared *pBt = pPage->pBt;
60003  u8 hdr = pPage->hdrOffset;
60004  u16 first;
60005
60006  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
60007  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60008  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
60009  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60010  assert( sqlite3_mutex_held(pBt->mutex) );
60011  if( pBt->btsFlags & BTS_SECURE_DELETE ){
60012    memset(&data[hdr], 0, pBt->usableSize - hdr);
60013  }
60014  data[hdr] = (char)flags;
60015  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
60016  memset(&data[hdr+1], 0, 4);
60017  data[hdr+7] = 0;
60018  put2byte(&data[hdr+5], pBt->usableSize);
60019  pPage->nFree = (u16)(pBt->usableSize - first);
60020  decodeFlags(pPage, flags);
60021  pPage->cellOffset = first;
60022  pPage->aDataEnd = &data[pBt->usableSize];
60023  pPage->aCellIdx = &data[first];
60024  pPage->aDataOfst = &data[pPage->childPtrSize];
60025  pPage->nOverflow = 0;
60026  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60027  pPage->maskPage = (u16)(pBt->pageSize - 1);
60028  pPage->nCell = 0;
60029  pPage->isInit = 1;
60030}
60031
60032
60033/*
60034** Convert a DbPage obtained from the pager into a MemPage used by
60035** the btree layer.
60036*/
60037static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
60038  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60039  if( pgno!=pPage->pgno ){
60040    pPage->aData = sqlite3PagerGetData(pDbPage);
60041    pPage->pDbPage = pDbPage;
60042    pPage->pBt = pBt;
60043    pPage->pgno = pgno;
60044    pPage->hdrOffset = pgno==1 ? 100 : 0;
60045  }
60046  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
60047  return pPage;
60048}
60049
60050/*
60051** Get a page from the pager.  Initialize the MemPage.pBt and
60052** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
60053**
60054** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
60055** about the content of the page at this time.  So do not go to the disk
60056** to fetch the content.  Just fill in the content with zeros for now.
60057** If in the future we call sqlite3PagerWrite() on this page, that
60058** means we have started to be concerned about content and the disk
60059** read should occur at that point.
60060*/
60061static int btreeGetPage(
60062  BtShared *pBt,       /* The btree */
60063  Pgno pgno,           /* Number of the page to fetch */
60064  MemPage **ppPage,    /* Return the page in this parameter */
60065  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60066){
60067  int rc;
60068  DbPage *pDbPage;
60069
60070  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
60071  assert( sqlite3_mutex_held(pBt->mutex) );
60072  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
60073  if( rc ) return rc;
60074  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
60075  return SQLITE_OK;
60076}
60077
60078/*
60079** Retrieve a page from the pager cache. If the requested page is not
60080** already in the pager cache return NULL. Initialize the MemPage.pBt and
60081** MemPage.aData elements if needed.
60082*/
60083static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
60084  DbPage *pDbPage;
60085  assert( sqlite3_mutex_held(pBt->mutex) );
60086  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
60087  if( pDbPage ){
60088    return btreePageFromDbPage(pDbPage, pgno, pBt);
60089  }
60090  return 0;
60091}
60092
60093/*
60094** Return the size of the database file in pages. If there is any kind of
60095** error, return ((unsigned int)-1).
60096*/
60097static Pgno btreePagecount(BtShared *pBt){
60098  return pBt->nPage;
60099}
60100SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
60101  assert( sqlite3BtreeHoldsMutex(p) );
60102  assert( ((p->pBt->nPage)&0x8000000)==0 );
60103  return btreePagecount(p->pBt);
60104}
60105
60106/*
60107** Get a page from the pager and initialize it.
60108**
60109** If pCur!=0 then the page is being fetched as part of a moveToChild()
60110** call.  Do additional sanity checking on the page in this case.
60111** And if the fetch fails, this routine must decrement pCur->iPage.
60112**
60113** The page is fetched as read-write unless pCur is not NULL and is
60114** a read-only cursor.
60115**
60116** If an error occurs, then *ppPage is undefined. It
60117** may remain unchanged, or it may be set to an invalid value.
60118*/
60119static int getAndInitPage(
60120  BtShared *pBt,                  /* The database file */
60121  Pgno pgno,                      /* Number of the page to get */
60122  MemPage **ppPage,               /* Write the page pointer here */
60123  BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
60124  int bReadOnly                   /* True for a read-only page */
60125){
60126  int rc;
60127  DbPage *pDbPage;
60128  assert( sqlite3_mutex_held(pBt->mutex) );
60129  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
60130  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
60131  assert( pCur==0 || pCur->iPage>0 );
60132
60133  if( pgno>btreePagecount(pBt) ){
60134    rc = SQLITE_CORRUPT_BKPT;
60135    goto getAndInitPage_error;
60136  }
60137  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
60138  if( rc ){
60139    goto getAndInitPage_error;
60140  }
60141  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60142  if( (*ppPage)->isInit==0 ){
60143    btreePageFromDbPage(pDbPage, pgno, pBt);
60144    rc = btreeInitPage(*ppPage);
60145    if( rc!=SQLITE_OK ){
60146      releasePage(*ppPage);
60147      goto getAndInitPage_error;
60148    }
60149  }
60150  assert( (*ppPage)->pgno==pgno );
60151  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
60152
60153  /* If obtaining a child page for a cursor, we must verify that the page is
60154  ** compatible with the root page. */
60155  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
60156    rc = SQLITE_CORRUPT_BKPT;
60157    releasePage(*ppPage);
60158    goto getAndInitPage_error;
60159  }
60160  return SQLITE_OK;
60161
60162getAndInitPage_error:
60163  if( pCur ) pCur->iPage--;
60164  testcase( pgno==0 );
60165  assert( pgno!=0 || rc==SQLITE_CORRUPT );
60166  return rc;
60167}
60168
60169/*
60170** Release a MemPage.  This should be called once for each prior
60171** call to btreeGetPage.
60172*/
60173static void releasePageNotNull(MemPage *pPage){
60174  assert( pPage->aData );
60175  assert( pPage->pBt );
60176  assert( pPage->pDbPage!=0 );
60177  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60178  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
60179  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60180  sqlite3PagerUnrefNotNull(pPage->pDbPage);
60181}
60182static void releasePage(MemPage *pPage){
60183  if( pPage ) releasePageNotNull(pPage);
60184}
60185
60186/*
60187** Get an unused page.
60188**
60189** This works just like btreeGetPage() with the addition:
60190**
60191**   *  If the page is already in use for some other purpose, immediately
60192**      release it and return an SQLITE_CURRUPT error.
60193**   *  Make sure the isInit flag is clear
60194*/
60195static int btreeGetUnusedPage(
60196  BtShared *pBt,       /* The btree */
60197  Pgno pgno,           /* Number of the page to fetch */
60198  MemPage **ppPage,    /* Return the page in this parameter */
60199  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60200){
60201  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
60202  if( rc==SQLITE_OK ){
60203    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
60204      releasePage(*ppPage);
60205      *ppPage = 0;
60206      return SQLITE_CORRUPT_BKPT;
60207    }
60208    (*ppPage)->isInit = 0;
60209  }else{
60210    *ppPage = 0;
60211  }
60212  return rc;
60213}
60214
60215
60216/*
60217** During a rollback, when the pager reloads information into the cache
60218** so that the cache is restored to its original state at the start of
60219** the transaction, for each page restored this routine is called.
60220**
60221** This routine needs to reset the extra data section at the end of the
60222** page to agree with the restored data.
60223*/
60224static void pageReinit(DbPage *pData){
60225  MemPage *pPage;
60226  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
60227  assert( sqlite3PagerPageRefcount(pData)>0 );
60228  if( pPage->isInit ){
60229    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60230    pPage->isInit = 0;
60231    if( sqlite3PagerPageRefcount(pData)>1 ){
60232      /* pPage might not be a btree page;  it might be an overflow page
60233      ** or ptrmap page or a free page.  In those cases, the following
60234      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
60235      ** But no harm is done by this.  And it is very important that
60236      ** btreeInitPage() be called on every btree page so we make
60237      ** the call for every page that comes in for re-initing. */
60238      btreeInitPage(pPage);
60239    }
60240  }
60241}
60242
60243/*
60244** Invoke the busy handler for a btree.
60245*/
60246static int btreeInvokeBusyHandler(void *pArg){
60247  BtShared *pBt = (BtShared*)pArg;
60248  assert( pBt->db );
60249  assert( sqlite3_mutex_held(pBt->db->mutex) );
60250  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
60251}
60252
60253/*
60254** Open a database file.
60255**
60256** zFilename is the name of the database file.  If zFilename is NULL
60257** then an ephemeral database is created.  The ephemeral database might
60258** be exclusively in memory, or it might use a disk-based memory cache.
60259** Either way, the ephemeral database will be automatically deleted
60260** when sqlite3BtreeClose() is called.
60261**
60262** If zFilename is ":memory:" then an in-memory database is created
60263** that is automatically destroyed when it is closed.
60264**
60265** The "flags" parameter is a bitmask that might contain bits like
60266** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
60267**
60268** If the database is already opened in the same database connection
60269** and we are in shared cache mode, then the open will fail with an
60270** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
60271** objects in the same database connection since doing so will lead
60272** to problems with locking.
60273*/
60274SQLITE_PRIVATE int sqlite3BtreeOpen(
60275  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
60276  const char *zFilename,  /* Name of the file containing the BTree database */
60277  sqlite3 *db,            /* Associated database handle */
60278  Btree **ppBtree,        /* Pointer to new Btree object written here */
60279  int flags,              /* Options */
60280  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
60281){
60282  BtShared *pBt = 0;             /* Shared part of btree structure */
60283  Btree *p;                      /* Handle to return */
60284  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
60285  int rc = SQLITE_OK;            /* Result code from this function */
60286  u8 nReserve;                   /* Byte of unused space on each page */
60287  unsigned char zDbHeader[100];  /* Database header content */
60288
60289  /* True if opening an ephemeral, temporary database */
60290  const int isTempDb = zFilename==0 || zFilename[0]==0;
60291
60292  /* Set the variable isMemdb to true for an in-memory database, or
60293  ** false for a file-based database.
60294  */
60295#ifdef SQLITE_OMIT_MEMORYDB
60296  const int isMemdb = 0;
60297#else
60298  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
60299                       || (isTempDb && sqlite3TempInMemory(db))
60300                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
60301#endif
60302
60303  assert( db!=0 );
60304  assert( pVfs!=0 );
60305  assert( sqlite3_mutex_held(db->mutex) );
60306  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
60307
60308  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
60309  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
60310
60311  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
60312  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
60313
60314  if( isMemdb ){
60315    flags |= BTREE_MEMORY;
60316  }
60317  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
60318    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
60319  }
60320  p = sqlite3MallocZero(sizeof(Btree));
60321  if( !p ){
60322    return SQLITE_NOMEM_BKPT;
60323  }
60324  p->inTrans = TRANS_NONE;
60325  p->db = db;
60326#ifndef SQLITE_OMIT_SHARED_CACHE
60327  p->lock.pBtree = p;
60328  p->lock.iTable = 1;
60329#endif
60330
60331#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60332  /*
60333  ** If this Btree is a candidate for shared cache, try to find an
60334  ** existing BtShared object that we can share with
60335  */
60336  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
60337    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
60338      int nFilename = sqlite3Strlen30(zFilename)+1;
60339      int nFullPathname = pVfs->mxPathname+1;
60340      char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
60341      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60342
60343      p->sharable = 1;
60344      if( !zFullPathname ){
60345        sqlite3_free(p);
60346        return SQLITE_NOMEM_BKPT;
60347      }
60348      if( isMemdb ){
60349        memcpy(zFullPathname, zFilename, nFilename);
60350      }else{
60351        rc = sqlite3OsFullPathname(pVfs, zFilename,
60352                                   nFullPathname, zFullPathname);
60353        if( rc ){
60354          sqlite3_free(zFullPathname);
60355          sqlite3_free(p);
60356          return rc;
60357        }
60358      }
60359#if SQLITE_THREADSAFE
60360      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
60361      sqlite3_mutex_enter(mutexOpen);
60362      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
60363      sqlite3_mutex_enter(mutexShared);
60364#endif
60365      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
60366        assert( pBt->nRef>0 );
60367        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
60368                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
60369          int iDb;
60370          for(iDb=db->nDb-1; iDb>=0; iDb--){
60371            Btree *pExisting = db->aDb[iDb].pBt;
60372            if( pExisting && pExisting->pBt==pBt ){
60373              sqlite3_mutex_leave(mutexShared);
60374              sqlite3_mutex_leave(mutexOpen);
60375              sqlite3_free(zFullPathname);
60376              sqlite3_free(p);
60377              return SQLITE_CONSTRAINT;
60378            }
60379          }
60380          p->pBt = pBt;
60381          pBt->nRef++;
60382          break;
60383        }
60384      }
60385      sqlite3_mutex_leave(mutexShared);
60386      sqlite3_free(zFullPathname);
60387    }
60388#ifdef SQLITE_DEBUG
60389    else{
60390      /* In debug mode, we mark all persistent databases as sharable
60391      ** even when they are not.  This exercises the locking code and
60392      ** gives more opportunity for asserts(sqlite3_mutex_held())
60393      ** statements to find locking problems.
60394      */
60395      p->sharable = 1;
60396    }
60397#endif
60398  }
60399#endif
60400  if( pBt==0 ){
60401    /*
60402    ** The following asserts make sure that structures used by the btree are
60403    ** the right size.  This is to guard against size changes that result
60404    ** when compiling on a different architecture.
60405    */
60406    assert( sizeof(i64)==8 );
60407    assert( sizeof(u64)==8 );
60408    assert( sizeof(u32)==4 );
60409    assert( sizeof(u16)==2 );
60410    assert( sizeof(Pgno)==4 );
60411
60412    pBt = sqlite3MallocZero( sizeof(*pBt) );
60413    if( pBt==0 ){
60414      rc = SQLITE_NOMEM_BKPT;
60415      goto btree_open_out;
60416    }
60417    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
60418                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
60419    if( rc==SQLITE_OK ){
60420      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
60421      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
60422    }
60423    if( rc!=SQLITE_OK ){
60424      goto btree_open_out;
60425    }
60426    pBt->openFlags = (u8)flags;
60427    pBt->db = db;
60428    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
60429    p->pBt = pBt;
60430
60431    pBt->pCursor = 0;
60432    pBt->pPage1 = 0;
60433    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
60434#ifdef SQLITE_SECURE_DELETE
60435    pBt->btsFlags |= BTS_SECURE_DELETE;
60436#endif
60437    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
60438    ** determined by the 2-byte integer located at an offset of 16 bytes from
60439    ** the beginning of the database file. */
60440    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
60441    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
60442         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
60443      pBt->pageSize = 0;
60444#ifndef SQLITE_OMIT_AUTOVACUUM
60445      /* If the magic name ":memory:" will create an in-memory database, then
60446      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
60447      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
60448      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
60449      ** regular file-name. In this case the auto-vacuum applies as per normal.
60450      */
60451      if( zFilename && !isMemdb ){
60452        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
60453        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
60454      }
60455#endif
60456      nReserve = 0;
60457    }else{
60458      /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
60459      ** determined by the one-byte unsigned integer found at an offset of 20
60460      ** into the database file header. */
60461      nReserve = zDbHeader[20];
60462      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60463#ifndef SQLITE_OMIT_AUTOVACUUM
60464      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
60465      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
60466#endif
60467    }
60468    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60469    if( rc ) goto btree_open_out;
60470    pBt->usableSize = pBt->pageSize - nReserve;
60471    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
60472
60473#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60474    /* Add the new BtShared object to the linked list sharable BtShareds.
60475    */
60476    pBt->nRef = 1;
60477    if( p->sharable ){
60478      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60479      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
60480      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
60481        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
60482        if( pBt->mutex==0 ){
60483          rc = SQLITE_NOMEM_BKPT;
60484          goto btree_open_out;
60485        }
60486      }
60487      sqlite3_mutex_enter(mutexShared);
60488      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
60489      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
60490      sqlite3_mutex_leave(mutexShared);
60491    }
60492#endif
60493  }
60494
60495#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60496  /* If the new Btree uses a sharable pBtShared, then link the new
60497  ** Btree into the list of all sharable Btrees for the same connection.
60498  ** The list is kept in ascending order by pBt address.
60499  */
60500  if( p->sharable ){
60501    int i;
60502    Btree *pSib;
60503    for(i=0; i<db->nDb; i++){
60504      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
60505        while( pSib->pPrev ){ pSib = pSib->pPrev; }
60506        if( (uptr)p->pBt<(uptr)pSib->pBt ){
60507          p->pNext = pSib;
60508          p->pPrev = 0;
60509          pSib->pPrev = p;
60510        }else{
60511          while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
60512            pSib = pSib->pNext;
60513          }
60514          p->pNext = pSib->pNext;
60515          p->pPrev = pSib;
60516          if( p->pNext ){
60517            p->pNext->pPrev = p;
60518          }
60519          pSib->pNext = p;
60520        }
60521        break;
60522      }
60523    }
60524  }
60525#endif
60526  *ppBtree = p;
60527
60528btree_open_out:
60529  if( rc!=SQLITE_OK ){
60530    if( pBt && pBt->pPager ){
60531      sqlite3PagerClose(pBt->pPager);
60532    }
60533    sqlite3_free(pBt);
60534    sqlite3_free(p);
60535    *ppBtree = 0;
60536  }else{
60537    /* If the B-Tree was successfully opened, set the pager-cache size to the
60538    ** default value. Except, when opening on an existing shared pager-cache,
60539    ** do not change the pager-cache size.
60540    */
60541    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
60542      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
60543    }
60544  }
60545  if( mutexOpen ){
60546    assert( sqlite3_mutex_held(mutexOpen) );
60547    sqlite3_mutex_leave(mutexOpen);
60548  }
60549  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
60550  return rc;
60551}
60552
60553/*
60554** Decrement the BtShared.nRef counter.  When it reaches zero,
60555** remove the BtShared structure from the sharing list.  Return
60556** true if the BtShared.nRef counter reaches zero and return
60557** false if it is still positive.
60558*/
60559static int removeFromSharingList(BtShared *pBt){
60560#ifndef SQLITE_OMIT_SHARED_CACHE
60561  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
60562  BtShared *pList;
60563  int removed = 0;
60564
60565  assert( sqlite3_mutex_notheld(pBt->mutex) );
60566  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
60567  sqlite3_mutex_enter(pMaster);
60568  pBt->nRef--;
60569  if( pBt->nRef<=0 ){
60570    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
60571      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
60572    }else{
60573      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
60574      while( ALWAYS(pList) && pList->pNext!=pBt ){
60575        pList=pList->pNext;
60576      }
60577      if( ALWAYS(pList) ){
60578        pList->pNext = pBt->pNext;
60579      }
60580    }
60581    if( SQLITE_THREADSAFE ){
60582      sqlite3_mutex_free(pBt->mutex);
60583    }
60584    removed = 1;
60585  }
60586  sqlite3_mutex_leave(pMaster);
60587  return removed;
60588#else
60589  return 1;
60590#endif
60591}
60592
60593/*
60594** Make sure pBt->pTmpSpace points to an allocation of
60595** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
60596** pointer.
60597*/
60598static void allocateTempSpace(BtShared *pBt){
60599  if( !pBt->pTmpSpace ){
60600    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
60601
60602    /* One of the uses of pBt->pTmpSpace is to format cells before
60603    ** inserting them into a leaf page (function fillInCell()). If
60604    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
60605    ** by the various routines that manipulate binary cells. Which
60606    ** can mean that fillInCell() only initializes the first 2 or 3
60607    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
60608    ** it into a database page. This is not actually a problem, but it
60609    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
60610    ** data is passed to system call write(). So to avoid this error,
60611    ** zero the first 4 bytes of temp space here.
60612    **
60613    ** Also:  Provide four bytes of initialized space before the
60614    ** beginning of pTmpSpace as an area available to prepend the
60615    ** left-child pointer to the beginning of a cell.
60616    */
60617    if( pBt->pTmpSpace ){
60618      memset(pBt->pTmpSpace, 0, 8);
60619      pBt->pTmpSpace += 4;
60620    }
60621  }
60622}
60623
60624/*
60625** Free the pBt->pTmpSpace allocation
60626*/
60627static void freeTempSpace(BtShared *pBt){
60628  if( pBt->pTmpSpace ){
60629    pBt->pTmpSpace -= 4;
60630    sqlite3PageFree(pBt->pTmpSpace);
60631    pBt->pTmpSpace = 0;
60632  }
60633}
60634
60635/*
60636** Close an open database and invalidate all cursors.
60637*/
60638SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
60639  BtShared *pBt = p->pBt;
60640  BtCursor *pCur;
60641
60642  /* Close all cursors opened via this handle.  */
60643  assert( sqlite3_mutex_held(p->db->mutex) );
60644  sqlite3BtreeEnter(p);
60645  pCur = pBt->pCursor;
60646  while( pCur ){
60647    BtCursor *pTmp = pCur;
60648    pCur = pCur->pNext;
60649    if( pTmp->pBtree==p ){
60650      sqlite3BtreeCloseCursor(pTmp);
60651    }
60652  }
60653
60654  /* Rollback any active transaction and free the handle structure.
60655  ** The call to sqlite3BtreeRollback() drops any table-locks held by
60656  ** this handle.
60657  */
60658  sqlite3BtreeRollback(p, SQLITE_OK, 0);
60659  sqlite3BtreeLeave(p);
60660
60661  /* If there are still other outstanding references to the shared-btree
60662  ** structure, return now. The remainder of this procedure cleans
60663  ** up the shared-btree.
60664  */
60665  assert( p->wantToLock==0 && p->locked==0 );
60666  if( !p->sharable || removeFromSharingList(pBt) ){
60667    /* The pBt is no longer on the sharing list, so we can access
60668    ** it without having to hold the mutex.
60669    **
60670    ** Clean out and delete the BtShared object.
60671    */
60672    assert( !pBt->pCursor );
60673    sqlite3PagerClose(pBt->pPager);
60674    if( pBt->xFreeSchema && pBt->pSchema ){
60675      pBt->xFreeSchema(pBt->pSchema);
60676    }
60677    sqlite3DbFree(0, pBt->pSchema);
60678    freeTempSpace(pBt);
60679    sqlite3_free(pBt);
60680  }
60681
60682#ifndef SQLITE_OMIT_SHARED_CACHE
60683  assert( p->wantToLock==0 );
60684  assert( p->locked==0 );
60685  if( p->pPrev ) p->pPrev->pNext = p->pNext;
60686  if( p->pNext ) p->pNext->pPrev = p->pPrev;
60687#endif
60688
60689  sqlite3_free(p);
60690  return SQLITE_OK;
60691}
60692
60693/*
60694** Change the "soft" limit on the number of pages in the cache.
60695** Unused and unmodified pages will be recycled when the number of
60696** pages in the cache exceeds this soft limit.  But the size of the
60697** cache is allowed to grow larger than this limit if it contains
60698** dirty pages or pages still in active use.
60699*/
60700SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
60701  BtShared *pBt = p->pBt;
60702  assert( sqlite3_mutex_held(p->db->mutex) );
60703  sqlite3BtreeEnter(p);
60704  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
60705  sqlite3BtreeLeave(p);
60706  return SQLITE_OK;
60707}
60708
60709/*
60710** Change the "spill" limit on the number of pages in the cache.
60711** If the number of pages exceeds this limit during a write transaction,
60712** the pager might attempt to "spill" pages to the journal early in
60713** order to free up memory.
60714**
60715** The value returned is the current spill size.  If zero is passed
60716** as an argument, no changes are made to the spill size setting, so
60717** using mxPage of 0 is a way to query the current spill size.
60718*/
60719SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
60720  BtShared *pBt = p->pBt;
60721  int res;
60722  assert( sqlite3_mutex_held(p->db->mutex) );
60723  sqlite3BtreeEnter(p);
60724  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
60725  sqlite3BtreeLeave(p);
60726  return res;
60727}
60728
60729#if SQLITE_MAX_MMAP_SIZE>0
60730/*
60731** Change the limit on the amount of the database file that may be
60732** memory mapped.
60733*/
60734SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
60735  BtShared *pBt = p->pBt;
60736  assert( sqlite3_mutex_held(p->db->mutex) );
60737  sqlite3BtreeEnter(p);
60738  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
60739  sqlite3BtreeLeave(p);
60740  return SQLITE_OK;
60741}
60742#endif /* SQLITE_MAX_MMAP_SIZE>0 */
60743
60744/*
60745** Change the way data is synced to disk in order to increase or decrease
60746** how well the database resists damage due to OS crashes and power
60747** failures.  Level 1 is the same as asynchronous (no syncs() occur and
60748** there is a high probability of damage)  Level 2 is the default.  There
60749** is a very low but non-zero probability of damage.  Level 3 reduces the
60750** probability of damage to near zero but with a write performance reduction.
60751*/
60752#ifndef SQLITE_OMIT_PAGER_PRAGMAS
60753SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
60754  Btree *p,              /* The btree to set the safety level on */
60755  unsigned pgFlags       /* Various PAGER_* flags */
60756){
60757  BtShared *pBt = p->pBt;
60758  assert( sqlite3_mutex_held(p->db->mutex) );
60759  sqlite3BtreeEnter(p);
60760  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
60761  sqlite3BtreeLeave(p);
60762  return SQLITE_OK;
60763}
60764#endif
60765
60766/*
60767** Change the default pages size and the number of reserved bytes per page.
60768** Or, if the page size has already been fixed, return SQLITE_READONLY
60769** without changing anything.
60770**
60771** The page size must be a power of 2 between 512 and 65536.  If the page
60772** size supplied does not meet this constraint then the page size is not
60773** changed.
60774**
60775** Page sizes are constrained to be a power of two so that the region
60776** of the database file used for locking (beginning at PENDING_BYTE,
60777** the first byte past the 1GB boundary, 0x40000000) needs to occur
60778** at the beginning of a page.
60779**
60780** If parameter nReserve is less than zero, then the number of reserved
60781** bytes per page is left unchanged.
60782**
60783** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
60784** and autovacuum mode can no longer be changed.
60785*/
60786SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
60787  int rc = SQLITE_OK;
60788  BtShared *pBt = p->pBt;
60789  assert( nReserve>=-1 && nReserve<=255 );
60790  sqlite3BtreeEnter(p);
60791#if SQLITE_HAS_CODEC
60792  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
60793#endif
60794  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
60795    sqlite3BtreeLeave(p);
60796    return SQLITE_READONLY;
60797  }
60798  if( nReserve<0 ){
60799    nReserve = pBt->pageSize - pBt->usableSize;
60800  }
60801  assert( nReserve>=0 && nReserve<=255 );
60802  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
60803        ((pageSize-1)&pageSize)==0 ){
60804    assert( (pageSize & 7)==0 );
60805    assert( !pBt->pCursor );
60806    pBt->pageSize = (u32)pageSize;
60807    freeTempSpace(pBt);
60808  }
60809  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60810  pBt->usableSize = pBt->pageSize - (u16)nReserve;
60811  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60812  sqlite3BtreeLeave(p);
60813  return rc;
60814}
60815
60816/*
60817** Return the currently defined page size
60818*/
60819SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
60820  return p->pBt->pageSize;
60821}
60822
60823/*
60824** This function is similar to sqlite3BtreeGetReserve(), except that it
60825** may only be called if it is guaranteed that the b-tree mutex is already
60826** held.
60827**
60828** This is useful in one special case in the backup API code where it is
60829** known that the shared b-tree mutex is held, but the mutex on the
60830** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
60831** were to be called, it might collide with some other operation on the
60832** database handle that owns *p, causing undefined behavior.
60833*/
60834SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
60835  int n;
60836  assert( sqlite3_mutex_held(p->pBt->mutex) );
60837  n = p->pBt->pageSize - p->pBt->usableSize;
60838  return n;
60839}
60840
60841/*
60842** Return the number of bytes of space at the end of every page that
60843** are intentually left unused.  This is the "reserved" space that is
60844** sometimes used by extensions.
60845**
60846** If SQLITE_HAS_MUTEX is defined then the number returned is the
60847** greater of the current reserved space and the maximum requested
60848** reserve space.
60849*/
60850SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
60851  int n;
60852  sqlite3BtreeEnter(p);
60853  n = sqlite3BtreeGetReserveNoMutex(p);
60854#ifdef SQLITE_HAS_CODEC
60855  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
60856#endif
60857  sqlite3BtreeLeave(p);
60858  return n;
60859}
60860
60861
60862/*
60863** Set the maximum page count for a database if mxPage is positive.
60864** No changes are made if mxPage is 0 or negative.
60865** Regardless of the value of mxPage, return the maximum page count.
60866*/
60867SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
60868  int n;
60869  sqlite3BtreeEnter(p);
60870  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
60871  sqlite3BtreeLeave(p);
60872  return n;
60873}
60874
60875/*
60876** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
60877** then make no changes.  Always return the value of the BTS_SECURE_DELETE
60878** setting after the change.
60879*/
60880SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
60881  int b;
60882  if( p==0 ) return 0;
60883  sqlite3BtreeEnter(p);
60884  if( newFlag>=0 ){
60885    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
60886    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
60887  }
60888  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
60889  sqlite3BtreeLeave(p);
60890  return b;
60891}
60892
60893/*
60894** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
60895** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
60896** is disabled. The default value for the auto-vacuum property is
60897** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
60898*/
60899SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
60900#ifdef SQLITE_OMIT_AUTOVACUUM
60901  return SQLITE_READONLY;
60902#else
60903  BtShared *pBt = p->pBt;
60904  int rc = SQLITE_OK;
60905  u8 av = (u8)autoVacuum;
60906
60907  sqlite3BtreeEnter(p);
60908  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
60909    rc = SQLITE_READONLY;
60910  }else{
60911    pBt->autoVacuum = av ?1:0;
60912    pBt->incrVacuum = av==2 ?1:0;
60913  }
60914  sqlite3BtreeLeave(p);
60915  return rc;
60916#endif
60917}
60918
60919/*
60920** Return the value of the 'auto-vacuum' property. If auto-vacuum is
60921** enabled 1 is returned. Otherwise 0.
60922*/
60923SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
60924#ifdef SQLITE_OMIT_AUTOVACUUM
60925  return BTREE_AUTOVACUUM_NONE;
60926#else
60927  int rc;
60928  sqlite3BtreeEnter(p);
60929  rc = (
60930    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
60931    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
60932    BTREE_AUTOVACUUM_INCR
60933  );
60934  sqlite3BtreeLeave(p);
60935  return rc;
60936#endif
60937}
60938
60939
60940/*
60941** Get a reference to pPage1 of the database file.  This will
60942** also acquire a readlock on that file.
60943**
60944** SQLITE_OK is returned on success.  If the file is not a
60945** well-formed database file, then SQLITE_CORRUPT is returned.
60946** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
60947** is returned if we run out of memory.
60948*/
60949static int lockBtree(BtShared *pBt){
60950  int rc;              /* Result code from subfunctions */
60951  MemPage *pPage1;     /* Page 1 of the database file */
60952  int nPage;           /* Number of pages in the database */
60953  int nPageFile = 0;   /* Number of pages in the database file */
60954  int nPageHeader;     /* Number of pages in the database according to hdr */
60955
60956  assert( sqlite3_mutex_held(pBt->mutex) );
60957  assert( pBt->pPage1==0 );
60958  rc = sqlite3PagerSharedLock(pBt->pPager);
60959  if( rc!=SQLITE_OK ) return rc;
60960  rc = btreeGetPage(pBt, 1, &pPage1, 0);
60961  if( rc!=SQLITE_OK ) return rc;
60962
60963  /* Do some checking to help insure the file we opened really is
60964  ** a valid database file.
60965  */
60966  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
60967  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
60968  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
60969    nPage = nPageFile;
60970  }
60971  if( nPage>0 ){
60972    u32 pageSize;
60973    u32 usableSize;
60974    u8 *page1 = pPage1->aData;
60975    rc = SQLITE_NOTADB;
60976    /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
60977    ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
60978    ** 61 74 20 33 00. */
60979    if( memcmp(page1, zMagicHeader, 16)!=0 ){
60980      goto page1_init_failed;
60981    }
60982
60983#ifdef SQLITE_OMIT_WAL
60984    if( page1[18]>1 ){
60985      pBt->btsFlags |= BTS_READ_ONLY;
60986    }
60987    if( page1[19]>1 ){
60988      goto page1_init_failed;
60989    }
60990#else
60991    if( page1[18]>2 ){
60992      pBt->btsFlags |= BTS_READ_ONLY;
60993    }
60994    if( page1[19]>2 ){
60995      goto page1_init_failed;
60996    }
60997
60998    /* If the write version is set to 2, this database should be accessed
60999    ** in WAL mode. If the log is not already open, open it now. Then
61000    ** return SQLITE_OK and return without populating BtShared.pPage1.
61001    ** The caller detects this and calls this function again. This is
61002    ** required as the version of page 1 currently in the page1 buffer
61003    ** may not be the latest version - there may be a newer one in the log
61004    ** file.
61005    */
61006    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
61007      int isOpen = 0;
61008      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
61009      if( rc!=SQLITE_OK ){
61010        goto page1_init_failed;
61011      }else{
61012#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
61013        sqlite3 *db;
61014        Db *pDb;
61015        if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
61016          while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
61017          if( pDb->bSyncSet==0
61018           && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
61019          ){
61020            pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
61021            sqlite3PagerSetFlags(pBt->pPager,
61022               pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
61023          }
61024        }
61025#endif
61026        if( isOpen==0 ){
61027          releasePage(pPage1);
61028          return SQLITE_OK;
61029        }
61030      }
61031      rc = SQLITE_NOTADB;
61032    }
61033#endif
61034
61035    /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
61036    ** fractions and the leaf payload fraction values must be 64, 32, and 32.
61037    **
61038    ** The original design allowed these amounts to vary, but as of
61039    ** version 3.6.0, we require them to be fixed.
61040    */
61041    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
61042      goto page1_init_failed;
61043    }
61044    /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61045    ** determined by the 2-byte integer located at an offset of 16 bytes from
61046    ** the beginning of the database file. */
61047    pageSize = (page1[16]<<8) | (page1[17]<<16);
61048    /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
61049    ** between 512 and 65536 inclusive. */
61050    if( ((pageSize-1)&pageSize)!=0
61051     || pageSize>SQLITE_MAX_PAGE_SIZE
61052     || pageSize<=256
61053    ){
61054      goto page1_init_failed;
61055    }
61056    assert( (pageSize & 7)==0 );
61057    /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
61058    ** integer at offset 20 is the number of bytes of space at the end of
61059    ** each page to reserve for extensions.
61060    **
61061    ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61062    ** determined by the one-byte unsigned integer found at an offset of 20
61063    ** into the database file header. */
61064    usableSize = pageSize - page1[20];
61065    if( (u32)pageSize!=pBt->pageSize ){
61066      /* After reading the first page of the database assuming a page size
61067      ** of BtShared.pageSize, we have discovered that the page-size is
61068      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
61069      ** zero and return SQLITE_OK. The caller will call this function
61070      ** again with the correct page-size.
61071      */
61072      releasePage(pPage1);
61073      pBt->usableSize = usableSize;
61074      pBt->pageSize = pageSize;
61075      freeTempSpace(pBt);
61076      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
61077                                   pageSize-usableSize);
61078      return rc;
61079    }
61080    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
61081      rc = SQLITE_CORRUPT_BKPT;
61082      goto page1_init_failed;
61083    }
61084    /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
61085    ** be less than 480. In other words, if the page size is 512, then the
61086    ** reserved space size cannot exceed 32. */
61087    if( usableSize<480 ){
61088      goto page1_init_failed;
61089    }
61090    pBt->pageSize = pageSize;
61091    pBt->usableSize = usableSize;
61092#ifndef SQLITE_OMIT_AUTOVACUUM
61093    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
61094    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
61095#endif
61096  }
61097
61098  /* maxLocal is the maximum amount of payload to store locally for
61099  ** a cell.  Make sure it is small enough so that at least minFanout
61100  ** cells can will fit on one page.  We assume a 10-byte page header.
61101  ** Besides the payload, the cell must store:
61102  **     2-byte pointer to the cell
61103  **     4-byte child pointer
61104  **     9-byte nKey value
61105  **     4-byte nData value
61106  **     4-byte overflow page pointer
61107  ** So a cell consists of a 2-byte pointer, a header which is as much as
61108  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
61109  ** page pointer.
61110  */
61111  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
61112  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
61113  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
61114  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
61115  if( pBt->maxLocal>127 ){
61116    pBt->max1bytePayload = 127;
61117  }else{
61118    pBt->max1bytePayload = (u8)pBt->maxLocal;
61119  }
61120  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
61121  pBt->pPage1 = pPage1;
61122  pBt->nPage = nPage;
61123  return SQLITE_OK;
61124
61125page1_init_failed:
61126  releasePage(pPage1);
61127  pBt->pPage1 = 0;
61128  return rc;
61129}
61130
61131#ifndef NDEBUG
61132/*
61133** Return the number of cursors open on pBt. This is for use
61134** in assert() expressions, so it is only compiled if NDEBUG is not
61135** defined.
61136**
61137** Only write cursors are counted if wrOnly is true.  If wrOnly is
61138** false then all cursors are counted.
61139**
61140** For the purposes of this routine, a cursor is any cursor that
61141** is capable of reading or writing to the database.  Cursors that
61142** have been tripped into the CURSOR_FAULT state are not counted.
61143*/
61144static int countValidCursors(BtShared *pBt, int wrOnly){
61145  BtCursor *pCur;
61146  int r = 0;
61147  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
61148    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
61149     && pCur->eState!=CURSOR_FAULT ) r++;
61150  }
61151  return r;
61152}
61153#endif
61154
61155/*
61156** If there are no outstanding cursors and we are not in the middle
61157** of a transaction but there is a read lock on the database, then
61158** this routine unrefs the first page of the database file which
61159** has the effect of releasing the read lock.
61160**
61161** If there is a transaction in progress, this routine is a no-op.
61162*/
61163static void unlockBtreeIfUnused(BtShared *pBt){
61164  assert( sqlite3_mutex_held(pBt->mutex) );
61165  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
61166  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
61167    MemPage *pPage1 = pBt->pPage1;
61168    assert( pPage1->aData );
61169    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
61170    pBt->pPage1 = 0;
61171    releasePageNotNull(pPage1);
61172  }
61173}
61174
61175/*
61176** If pBt points to an empty file then convert that empty file
61177** into a new empty database by initializing the first page of
61178** the database.
61179*/
61180static int newDatabase(BtShared *pBt){
61181  MemPage *pP1;
61182  unsigned char *data;
61183  int rc;
61184
61185  assert( sqlite3_mutex_held(pBt->mutex) );
61186  if( pBt->nPage>0 ){
61187    return SQLITE_OK;
61188  }
61189  pP1 = pBt->pPage1;
61190  assert( pP1!=0 );
61191  data = pP1->aData;
61192  rc = sqlite3PagerWrite(pP1->pDbPage);
61193  if( rc ) return rc;
61194  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
61195  assert( sizeof(zMagicHeader)==16 );
61196  data[16] = (u8)((pBt->pageSize>>8)&0xff);
61197  data[17] = (u8)((pBt->pageSize>>16)&0xff);
61198  data[18] = 1;
61199  data[19] = 1;
61200  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
61201  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
61202  data[21] = 64;
61203  data[22] = 32;
61204  data[23] = 32;
61205  memset(&data[24], 0, 100-24);
61206  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
61207  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61208#ifndef SQLITE_OMIT_AUTOVACUUM
61209  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
61210  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
61211  put4byte(&data[36 + 4*4], pBt->autoVacuum);
61212  put4byte(&data[36 + 7*4], pBt->incrVacuum);
61213#endif
61214  pBt->nPage = 1;
61215  data[31] = 1;
61216  return SQLITE_OK;
61217}
61218
61219/*
61220** Initialize the first page of the database file (creating a database
61221** consisting of a single page and no schema objects). Return SQLITE_OK
61222** if successful, or an SQLite error code otherwise.
61223*/
61224SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
61225  int rc;
61226  sqlite3BtreeEnter(p);
61227  p->pBt->nPage = 0;
61228  rc = newDatabase(p->pBt);
61229  sqlite3BtreeLeave(p);
61230  return rc;
61231}
61232
61233/*
61234** Attempt to start a new transaction. A write-transaction
61235** is started if the second argument is nonzero, otherwise a read-
61236** transaction.  If the second argument is 2 or more and exclusive
61237** transaction is started, meaning that no other process is allowed
61238** to access the database.  A preexisting transaction may not be
61239** upgraded to exclusive by calling this routine a second time - the
61240** exclusivity flag only works for a new transaction.
61241**
61242** A write-transaction must be started before attempting any
61243** changes to the database.  None of the following routines
61244** will work unless a transaction is started first:
61245**
61246**      sqlite3BtreeCreateTable()
61247**      sqlite3BtreeCreateIndex()
61248**      sqlite3BtreeClearTable()
61249**      sqlite3BtreeDropTable()
61250**      sqlite3BtreeInsert()
61251**      sqlite3BtreeDelete()
61252**      sqlite3BtreeUpdateMeta()
61253**
61254** If an initial attempt to acquire the lock fails because of lock contention
61255** and the database was previously unlocked, then invoke the busy handler
61256** if there is one.  But if there was previously a read-lock, do not
61257** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
61258** returned when there is already a read-lock in order to avoid a deadlock.
61259**
61260** Suppose there are two processes A and B.  A has a read lock and B has
61261** a reserved lock.  B tries to promote to exclusive but is blocked because
61262** of A's read lock.  A tries to promote to reserved but is blocked by B.
61263** One or the other of the two processes must give way or there can be
61264** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
61265** when A already has a read lock, we encourage A to give up and let B
61266** proceed.
61267*/
61268SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
61269  BtShared *pBt = p->pBt;
61270  int rc = SQLITE_OK;
61271
61272  sqlite3BtreeEnter(p);
61273  btreeIntegrity(p);
61274
61275  /* If the btree is already in a write-transaction, or it
61276  ** is already in a read-transaction and a read-transaction
61277  ** is requested, this is a no-op.
61278  */
61279  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
61280    goto trans_begun;
61281  }
61282  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
61283
61284  /* Write transactions are not possible on a read-only database */
61285  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
61286    rc = SQLITE_READONLY;
61287    goto trans_begun;
61288  }
61289
61290#ifndef SQLITE_OMIT_SHARED_CACHE
61291  {
61292    sqlite3 *pBlock = 0;
61293    /* If another database handle has already opened a write transaction
61294    ** on this shared-btree structure and a second write transaction is
61295    ** requested, return SQLITE_LOCKED.
61296    */
61297    if( (wrflag && pBt->inTransaction==TRANS_WRITE)
61298     || (pBt->btsFlags & BTS_PENDING)!=0
61299    ){
61300      pBlock = pBt->pWriter->db;
61301    }else if( wrflag>1 ){
61302      BtLock *pIter;
61303      for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
61304        if( pIter->pBtree!=p ){
61305          pBlock = pIter->pBtree->db;
61306          break;
61307        }
61308      }
61309    }
61310    if( pBlock ){
61311      sqlite3ConnectionBlocked(p->db, pBlock);
61312      rc = SQLITE_LOCKED_SHAREDCACHE;
61313      goto trans_begun;
61314    }
61315  }
61316#endif
61317
61318  /* Any read-only or read-write transaction implies a read-lock on
61319  ** page 1. So if some other shared-cache client already has a write-lock
61320  ** on page 1, the transaction cannot be opened. */
61321  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
61322  if( SQLITE_OK!=rc ) goto trans_begun;
61323
61324  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
61325  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
61326  do {
61327    /* Call lockBtree() until either pBt->pPage1 is populated or
61328    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
61329    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
61330    ** reading page 1 it discovers that the page-size of the database
61331    ** file is not pBt->pageSize. In this case lockBtree() will update
61332    ** pBt->pageSize to the page-size of the file on disk.
61333    */
61334    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
61335
61336    if( rc==SQLITE_OK && wrflag ){
61337      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
61338        rc = SQLITE_READONLY;
61339      }else{
61340        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
61341        if( rc==SQLITE_OK ){
61342          rc = newDatabase(pBt);
61343        }
61344      }
61345    }
61346
61347    if( rc!=SQLITE_OK ){
61348      unlockBtreeIfUnused(pBt);
61349    }
61350  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
61351          btreeInvokeBusyHandler(pBt) );
61352
61353  if( rc==SQLITE_OK ){
61354    if( p->inTrans==TRANS_NONE ){
61355      pBt->nTransaction++;
61356#ifndef SQLITE_OMIT_SHARED_CACHE
61357      if( p->sharable ){
61358        assert( p->lock.pBtree==p && p->lock.iTable==1 );
61359        p->lock.eLock = READ_LOCK;
61360        p->lock.pNext = pBt->pLock;
61361        pBt->pLock = &p->lock;
61362      }
61363#endif
61364    }
61365    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
61366    if( p->inTrans>pBt->inTransaction ){
61367      pBt->inTransaction = p->inTrans;
61368    }
61369    if( wrflag ){
61370      MemPage *pPage1 = pBt->pPage1;
61371#ifndef SQLITE_OMIT_SHARED_CACHE
61372      assert( !pBt->pWriter );
61373      pBt->pWriter = p;
61374      pBt->btsFlags &= ~BTS_EXCLUSIVE;
61375      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
61376#endif
61377
61378      /* If the db-size header field is incorrect (as it may be if an old
61379      ** client has been writing the database file), update it now. Doing
61380      ** this sooner rather than later means the database size can safely
61381      ** re-read the database size from page 1 if a savepoint or transaction
61382      ** rollback occurs within the transaction.
61383      */
61384      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
61385        rc = sqlite3PagerWrite(pPage1->pDbPage);
61386        if( rc==SQLITE_OK ){
61387          put4byte(&pPage1->aData[28], pBt->nPage);
61388        }
61389      }
61390    }
61391  }
61392
61393
61394trans_begun:
61395  if( rc==SQLITE_OK && wrflag ){
61396    /* This call makes sure that the pager has the correct number of
61397    ** open savepoints. If the second parameter is greater than 0 and
61398    ** the sub-journal is not already open, then it will be opened here.
61399    */
61400    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
61401  }
61402
61403  btreeIntegrity(p);
61404  sqlite3BtreeLeave(p);
61405  return rc;
61406}
61407
61408#ifndef SQLITE_OMIT_AUTOVACUUM
61409
61410/*
61411** Set the pointer-map entries for all children of page pPage. Also, if
61412** pPage contains cells that point to overflow pages, set the pointer
61413** map entries for the overflow pages as well.
61414*/
61415static int setChildPtrmaps(MemPage *pPage){
61416  int i;                             /* Counter variable */
61417  int nCell;                         /* Number of cells in page pPage */
61418  int rc;                            /* Return code */
61419  BtShared *pBt = pPage->pBt;
61420  u8 isInitOrig = pPage->isInit;
61421  Pgno pgno = pPage->pgno;
61422
61423  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61424  rc = btreeInitPage(pPage);
61425  if( rc!=SQLITE_OK ){
61426    goto set_child_ptrmaps_out;
61427  }
61428  nCell = pPage->nCell;
61429
61430  for(i=0; i<nCell; i++){
61431    u8 *pCell = findCell(pPage, i);
61432
61433    ptrmapPutOvflPtr(pPage, pCell, &rc);
61434
61435    if( !pPage->leaf ){
61436      Pgno childPgno = get4byte(pCell);
61437      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61438    }
61439  }
61440
61441  if( !pPage->leaf ){
61442    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61443    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61444  }
61445
61446set_child_ptrmaps_out:
61447  pPage->isInit = isInitOrig;
61448  return rc;
61449}
61450
61451/*
61452** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
61453** that it points to iTo. Parameter eType describes the type of pointer to
61454** be modified, as  follows:
61455**
61456** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
61457**                   page of pPage.
61458**
61459** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
61460**                   page pointed to by one of the cells on pPage.
61461**
61462** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
61463**                   overflow page in the list.
61464*/
61465static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
61466  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61467  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61468  if( eType==PTRMAP_OVERFLOW2 ){
61469    /* The pointer is always the first 4 bytes of the page in this case.  */
61470    if( get4byte(pPage->aData)!=iFrom ){
61471      return SQLITE_CORRUPT_BKPT;
61472    }
61473    put4byte(pPage->aData, iTo);
61474  }else{
61475    u8 isInitOrig = pPage->isInit;
61476    int i;
61477    int nCell;
61478    int rc;
61479
61480    rc = btreeInitPage(pPage);
61481    if( rc ) return rc;
61482    nCell = pPage->nCell;
61483
61484    for(i=0; i<nCell; i++){
61485      u8 *pCell = findCell(pPage, i);
61486      if( eType==PTRMAP_OVERFLOW1 ){
61487        CellInfo info;
61488        pPage->xParseCell(pPage, pCell, &info);
61489        if( info.nLocal<info.nPayload
61490         && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
61491         && iFrom==get4byte(pCell+info.nSize-4)
61492        ){
61493          put4byte(pCell+info.nSize-4, iTo);
61494          break;
61495        }
61496      }else{
61497        if( get4byte(pCell)==iFrom ){
61498          put4byte(pCell, iTo);
61499          break;
61500        }
61501      }
61502    }
61503
61504    if( i==nCell ){
61505      if( eType!=PTRMAP_BTREE ||
61506          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
61507        return SQLITE_CORRUPT_BKPT;
61508      }
61509      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
61510    }
61511
61512    pPage->isInit = isInitOrig;
61513  }
61514  return SQLITE_OK;
61515}
61516
61517
61518/*
61519** Move the open database page pDbPage to location iFreePage in the
61520** database. The pDbPage reference remains valid.
61521**
61522** The isCommit flag indicates that there is no need to remember that
61523** the journal needs to be sync()ed before database page pDbPage->pgno
61524** can be written to. The caller has already promised not to write to that
61525** page.
61526*/
61527static int relocatePage(
61528  BtShared *pBt,           /* Btree */
61529  MemPage *pDbPage,        /* Open page to move */
61530  u8 eType,                /* Pointer map 'type' entry for pDbPage */
61531  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
61532  Pgno iFreePage,          /* The location to move pDbPage to */
61533  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
61534){
61535  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
61536  Pgno iDbPage = pDbPage->pgno;
61537  Pager *pPager = pBt->pPager;
61538  int rc;
61539
61540  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
61541      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
61542  assert( sqlite3_mutex_held(pBt->mutex) );
61543  assert( pDbPage->pBt==pBt );
61544
61545  /* Move page iDbPage from its current location to page number iFreePage */
61546  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
61547      iDbPage, iFreePage, iPtrPage, eType));
61548  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
61549  if( rc!=SQLITE_OK ){
61550    return rc;
61551  }
61552  pDbPage->pgno = iFreePage;
61553
61554  /* If pDbPage was a btree-page, then it may have child pages and/or cells
61555  ** that point to overflow pages. The pointer map entries for all these
61556  ** pages need to be changed.
61557  **
61558  ** If pDbPage is an overflow page, then the first 4 bytes may store a
61559  ** pointer to a subsequent overflow page. If this is the case, then
61560  ** the pointer map needs to be updated for the subsequent overflow page.
61561  */
61562  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
61563    rc = setChildPtrmaps(pDbPage);
61564    if( rc!=SQLITE_OK ){
61565      return rc;
61566    }
61567  }else{
61568    Pgno nextOvfl = get4byte(pDbPage->aData);
61569    if( nextOvfl!=0 ){
61570      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
61571      if( rc!=SQLITE_OK ){
61572        return rc;
61573      }
61574    }
61575  }
61576
61577  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
61578  ** that it points at iFreePage. Also fix the pointer map entry for
61579  ** iPtrPage.
61580  */
61581  if( eType!=PTRMAP_ROOTPAGE ){
61582    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
61583    if( rc!=SQLITE_OK ){
61584      return rc;
61585    }
61586    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
61587    if( rc!=SQLITE_OK ){
61588      releasePage(pPtrPage);
61589      return rc;
61590    }
61591    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
61592    releasePage(pPtrPage);
61593    if( rc==SQLITE_OK ){
61594      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
61595    }
61596  }
61597  return rc;
61598}
61599
61600/* Forward declaration required by incrVacuumStep(). */
61601static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
61602
61603/*
61604** Perform a single step of an incremental-vacuum. If successful, return
61605** SQLITE_OK. If there is no work to do (and therefore no point in
61606** calling this function again), return SQLITE_DONE. Or, if an error
61607** occurs, return some other error code.
61608**
61609** More specifically, this function attempts to re-organize the database so
61610** that the last page of the file currently in use is no longer in use.
61611**
61612** Parameter nFin is the number of pages that this database would contain
61613** were this function called until it returns SQLITE_DONE.
61614**
61615** If the bCommit parameter is non-zero, this function assumes that the
61616** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
61617** or an error. bCommit is passed true for an auto-vacuum-on-commit
61618** operation, or false for an incremental vacuum.
61619*/
61620static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
61621  Pgno nFreeList;           /* Number of pages still on the free-list */
61622  int rc;
61623
61624  assert( sqlite3_mutex_held(pBt->mutex) );
61625  assert( iLastPg>nFin );
61626
61627  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
61628    u8 eType;
61629    Pgno iPtrPage;
61630
61631    nFreeList = get4byte(&pBt->pPage1->aData[36]);
61632    if( nFreeList==0 ){
61633      return SQLITE_DONE;
61634    }
61635
61636    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
61637    if( rc!=SQLITE_OK ){
61638      return rc;
61639    }
61640    if( eType==PTRMAP_ROOTPAGE ){
61641      return SQLITE_CORRUPT_BKPT;
61642    }
61643
61644    if( eType==PTRMAP_FREEPAGE ){
61645      if( bCommit==0 ){
61646        /* Remove the page from the files free-list. This is not required
61647        ** if bCommit is non-zero. In that case, the free-list will be
61648        ** truncated to zero after this function returns, so it doesn't
61649        ** matter if it still contains some garbage entries.
61650        */
61651        Pgno iFreePg;
61652        MemPage *pFreePg;
61653        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
61654        if( rc!=SQLITE_OK ){
61655          return rc;
61656        }
61657        assert( iFreePg==iLastPg );
61658        releasePage(pFreePg);
61659      }
61660    } else {
61661      Pgno iFreePg;             /* Index of free page to move pLastPg to */
61662      MemPage *pLastPg;
61663      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
61664      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
61665
61666      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
61667      if( rc!=SQLITE_OK ){
61668        return rc;
61669      }
61670
61671      /* If bCommit is zero, this loop runs exactly once and page pLastPg
61672      ** is swapped with the first free page pulled off the free list.
61673      **
61674      ** On the other hand, if bCommit is greater than zero, then keep
61675      ** looping until a free-page located within the first nFin pages
61676      ** of the file is found.
61677      */
61678      if( bCommit==0 ){
61679        eMode = BTALLOC_LE;
61680        iNear = nFin;
61681      }
61682      do {
61683        MemPage *pFreePg;
61684        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
61685        if( rc!=SQLITE_OK ){
61686          releasePage(pLastPg);
61687          return rc;
61688        }
61689        releasePage(pFreePg);
61690      }while( bCommit && iFreePg>nFin );
61691      assert( iFreePg<iLastPg );
61692
61693      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
61694      releasePage(pLastPg);
61695      if( rc!=SQLITE_OK ){
61696        return rc;
61697      }
61698    }
61699  }
61700
61701  if( bCommit==0 ){
61702    do {
61703      iLastPg--;
61704    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
61705    pBt->bDoTruncate = 1;
61706    pBt->nPage = iLastPg;
61707  }
61708  return SQLITE_OK;
61709}
61710
61711/*
61712** The database opened by the first argument is an auto-vacuum database
61713** nOrig pages in size containing nFree free pages. Return the expected
61714** size of the database in pages following an auto-vacuum operation.
61715*/
61716static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
61717  int nEntry;                     /* Number of entries on one ptrmap page */
61718  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
61719  Pgno nFin;                      /* Return value */
61720
61721  nEntry = pBt->usableSize/5;
61722  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
61723  nFin = nOrig - nFree - nPtrmap;
61724  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
61725    nFin--;
61726  }
61727  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
61728    nFin--;
61729  }
61730
61731  return nFin;
61732}
61733
61734/*
61735** A write-transaction must be opened before calling this function.
61736** It performs a single unit of work towards an incremental vacuum.
61737**
61738** If the incremental vacuum is finished after this function has run,
61739** SQLITE_DONE is returned. If it is not finished, but no error occurred,
61740** SQLITE_OK is returned. Otherwise an SQLite error code.
61741*/
61742SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
61743  int rc;
61744  BtShared *pBt = p->pBt;
61745
61746  sqlite3BtreeEnter(p);
61747  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
61748  if( !pBt->autoVacuum ){
61749    rc = SQLITE_DONE;
61750  }else{
61751    Pgno nOrig = btreePagecount(pBt);
61752    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
61753    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
61754
61755    if( nOrig<nFin ){
61756      rc = SQLITE_CORRUPT_BKPT;
61757    }else if( nFree>0 ){
61758      rc = saveAllCursors(pBt, 0, 0);
61759      if( rc==SQLITE_OK ){
61760        invalidateAllOverflowCache(pBt);
61761        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
61762      }
61763      if( rc==SQLITE_OK ){
61764        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61765        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
61766      }
61767    }else{
61768      rc = SQLITE_DONE;
61769    }
61770  }
61771  sqlite3BtreeLeave(p);
61772  return rc;
61773}
61774
61775/*
61776** This routine is called prior to sqlite3PagerCommit when a transaction
61777** is committed for an auto-vacuum database.
61778**
61779** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
61780** the database file should be truncated to during the commit process.
61781** i.e. the database has been reorganized so that only the first *pnTrunc
61782** pages are in use.
61783*/
61784static int autoVacuumCommit(BtShared *pBt){
61785  int rc = SQLITE_OK;
61786  Pager *pPager = pBt->pPager;
61787  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
61788
61789  assert( sqlite3_mutex_held(pBt->mutex) );
61790  invalidateAllOverflowCache(pBt);
61791  assert(pBt->autoVacuum);
61792  if( !pBt->incrVacuum ){
61793    Pgno nFin;         /* Number of pages in database after autovacuuming */
61794    Pgno nFree;        /* Number of pages on the freelist initially */
61795    Pgno iFree;        /* The next page to be freed */
61796    Pgno nOrig;        /* Database size before freeing */
61797
61798    nOrig = btreePagecount(pBt);
61799    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
61800      /* It is not possible to create a database for which the final page
61801      ** is either a pointer-map page or the pending-byte page. If one
61802      ** is encountered, this indicates corruption.
61803      */
61804      return SQLITE_CORRUPT_BKPT;
61805    }
61806
61807    nFree = get4byte(&pBt->pPage1->aData[36]);
61808    nFin = finalDbSize(pBt, nOrig, nFree);
61809    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
61810    if( nFin<nOrig ){
61811      rc = saveAllCursors(pBt, 0, 0);
61812    }
61813    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
61814      rc = incrVacuumStep(pBt, nFin, iFree, 1);
61815    }
61816    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
61817      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61818      put4byte(&pBt->pPage1->aData[32], 0);
61819      put4byte(&pBt->pPage1->aData[36], 0);
61820      put4byte(&pBt->pPage1->aData[28], nFin);
61821      pBt->bDoTruncate = 1;
61822      pBt->nPage = nFin;
61823    }
61824    if( rc!=SQLITE_OK ){
61825      sqlite3PagerRollback(pPager);
61826    }
61827  }
61828
61829  assert( nRef>=sqlite3PagerRefcount(pPager) );
61830  return rc;
61831}
61832
61833#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
61834# define setChildPtrmaps(x) SQLITE_OK
61835#endif
61836
61837/*
61838** This routine does the first phase of a two-phase commit.  This routine
61839** causes a rollback journal to be created (if it does not already exist)
61840** and populated with enough information so that if a power loss occurs
61841** the database can be restored to its original state by playing back
61842** the journal.  Then the contents of the journal are flushed out to
61843** the disk.  After the journal is safely on oxide, the changes to the
61844** database are written into the database file and flushed to oxide.
61845** At the end of this call, the rollback journal still exists on the
61846** disk and we are still holding all locks, so the transaction has not
61847** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
61848** commit process.
61849**
61850** This call is a no-op if no write-transaction is currently active on pBt.
61851**
61852** Otherwise, sync the database file for the btree pBt. zMaster points to
61853** the name of a master journal file that should be written into the
61854** individual journal file, or is NULL, indicating no master journal file
61855** (single database transaction).
61856**
61857** When this is called, the master journal should already have been
61858** created, populated with this journal pointer and synced to disk.
61859**
61860** Once this is routine has returned, the only thing required to commit
61861** the write-transaction for this database file is to delete the journal.
61862*/
61863SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
61864  int rc = SQLITE_OK;
61865  if( p->inTrans==TRANS_WRITE ){
61866    BtShared *pBt = p->pBt;
61867    sqlite3BtreeEnter(p);
61868#ifndef SQLITE_OMIT_AUTOVACUUM
61869    if( pBt->autoVacuum ){
61870      rc = autoVacuumCommit(pBt);
61871      if( rc!=SQLITE_OK ){
61872        sqlite3BtreeLeave(p);
61873        return rc;
61874      }
61875    }
61876    if( pBt->bDoTruncate ){
61877      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
61878    }
61879#endif
61880    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
61881    sqlite3BtreeLeave(p);
61882  }
61883  return rc;
61884}
61885
61886/*
61887** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
61888** at the conclusion of a transaction.
61889*/
61890static void btreeEndTransaction(Btree *p){
61891  BtShared *pBt = p->pBt;
61892  sqlite3 *db = p->db;
61893  assert( sqlite3BtreeHoldsMutex(p) );
61894
61895#ifndef SQLITE_OMIT_AUTOVACUUM
61896  pBt->bDoTruncate = 0;
61897#endif
61898  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
61899    /* If there are other active statements that belong to this database
61900    ** handle, downgrade to a read-only transaction. The other statements
61901    ** may still be reading from the database.  */
61902    downgradeAllSharedCacheTableLocks(p);
61903    p->inTrans = TRANS_READ;
61904  }else{
61905    /* If the handle had any kind of transaction open, decrement the
61906    ** transaction count of the shared btree. If the transaction count
61907    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
61908    ** call below will unlock the pager.  */
61909    if( p->inTrans!=TRANS_NONE ){
61910      clearAllSharedCacheTableLocks(p);
61911      pBt->nTransaction--;
61912      if( 0==pBt->nTransaction ){
61913        pBt->inTransaction = TRANS_NONE;
61914      }
61915    }
61916
61917    /* Set the current transaction state to TRANS_NONE and unlock the
61918    ** pager if this call closed the only read or write transaction.  */
61919    p->inTrans = TRANS_NONE;
61920    unlockBtreeIfUnused(pBt);
61921  }
61922
61923  btreeIntegrity(p);
61924}
61925
61926/*
61927** Commit the transaction currently in progress.
61928**
61929** This routine implements the second phase of a 2-phase commit.  The
61930** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
61931** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
61932** routine did all the work of writing information out to disk and flushing the
61933** contents so that they are written onto the disk platter.  All this
61934** routine has to do is delete or truncate or zero the header in the
61935** the rollback journal (which causes the transaction to commit) and
61936** drop locks.
61937**
61938** Normally, if an error occurs while the pager layer is attempting to
61939** finalize the underlying journal file, this function returns an error and
61940** the upper layer will attempt a rollback. However, if the second argument
61941** is non-zero then this b-tree transaction is part of a multi-file
61942** transaction. In this case, the transaction has already been committed
61943** (by deleting a master journal file) and the caller will ignore this
61944** functions return code. So, even if an error occurs in the pager layer,
61945** reset the b-tree objects internal state to indicate that the write
61946** transaction has been closed. This is quite safe, as the pager will have
61947** transitioned to the error state.
61948**
61949** This will release the write lock on the database file.  If there
61950** are no active cursors, it also releases the read lock.
61951*/
61952SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
61953
61954  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
61955  sqlite3BtreeEnter(p);
61956  btreeIntegrity(p);
61957
61958  /* If the handle has a write-transaction open, commit the shared-btrees
61959  ** transaction and set the shared state to TRANS_READ.
61960  */
61961  if( p->inTrans==TRANS_WRITE ){
61962    int rc;
61963    BtShared *pBt = p->pBt;
61964    assert( pBt->inTransaction==TRANS_WRITE );
61965    assert( pBt->nTransaction>0 );
61966    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
61967    if( rc!=SQLITE_OK && bCleanup==0 ){
61968      sqlite3BtreeLeave(p);
61969      return rc;
61970    }
61971    p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
61972    pBt->inTransaction = TRANS_READ;
61973    btreeClearHasContent(pBt);
61974  }
61975
61976  btreeEndTransaction(p);
61977  sqlite3BtreeLeave(p);
61978  return SQLITE_OK;
61979}
61980
61981/*
61982** Do both phases of a commit.
61983*/
61984SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
61985  int rc;
61986  sqlite3BtreeEnter(p);
61987  rc = sqlite3BtreeCommitPhaseOne(p, 0);
61988  if( rc==SQLITE_OK ){
61989    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
61990  }
61991  sqlite3BtreeLeave(p);
61992  return rc;
61993}
61994
61995/*
61996** This routine sets the state to CURSOR_FAULT and the error
61997** code to errCode for every cursor on any BtShared that pBtree
61998** references.  Or if the writeOnly flag is set to 1, then only
61999** trip write cursors and leave read cursors unchanged.
62000**
62001** Every cursor is a candidate to be tripped, including cursors
62002** that belong to other database connections that happen to be
62003** sharing the cache with pBtree.
62004**
62005** This routine gets called when a rollback occurs. If the writeOnly
62006** flag is true, then only write-cursors need be tripped - read-only
62007** cursors save their current positions so that they may continue
62008** following the rollback. Or, if writeOnly is false, all cursors are
62009** tripped. In general, writeOnly is false if the transaction being
62010** rolled back modified the database schema. In this case b-tree root
62011** pages may be moved or deleted from the database altogether, making
62012** it unsafe for read cursors to continue.
62013**
62014** If the writeOnly flag is true and an error is encountered while
62015** saving the current position of a read-only cursor, all cursors,
62016** including all read-cursors are tripped.
62017**
62018** SQLITE_OK is returned if successful, or if an error occurs while
62019** saving a cursor position, an SQLite error code.
62020*/
62021SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
62022  BtCursor *p;
62023  int rc = SQLITE_OK;
62024
62025  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
62026  if( pBtree ){
62027    sqlite3BtreeEnter(pBtree);
62028    for(p=pBtree->pBt->pCursor; p; p=p->pNext){
62029      int i;
62030      if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
62031        if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
62032          rc = saveCursorPosition(p);
62033          if( rc!=SQLITE_OK ){
62034            (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
62035            break;
62036          }
62037        }
62038      }else{
62039        sqlite3BtreeClearCursor(p);
62040        p->eState = CURSOR_FAULT;
62041        p->skipNext = errCode;
62042      }
62043      for(i=0; i<=p->iPage; i++){
62044        releasePage(p->apPage[i]);
62045        p->apPage[i] = 0;
62046      }
62047    }
62048    sqlite3BtreeLeave(pBtree);
62049  }
62050  return rc;
62051}
62052
62053/*
62054** Rollback the transaction in progress.
62055**
62056** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
62057** Only write cursors are tripped if writeOnly is true but all cursors are
62058** tripped if writeOnly is false.  Any attempt to use
62059** a tripped cursor will result in an error.
62060**
62061** This will release the write lock on the database file.  If there
62062** are no active cursors, it also releases the read lock.
62063*/
62064SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
62065  int rc;
62066  BtShared *pBt = p->pBt;
62067  MemPage *pPage1;
62068
62069  assert( writeOnly==1 || writeOnly==0 );
62070  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
62071  sqlite3BtreeEnter(p);
62072  if( tripCode==SQLITE_OK ){
62073    rc = tripCode = saveAllCursors(pBt, 0, 0);
62074    if( rc ) writeOnly = 0;
62075  }else{
62076    rc = SQLITE_OK;
62077  }
62078  if( tripCode ){
62079    int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
62080    assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
62081    if( rc2!=SQLITE_OK ) rc = rc2;
62082  }
62083  btreeIntegrity(p);
62084
62085  if( p->inTrans==TRANS_WRITE ){
62086    int rc2;
62087
62088    assert( TRANS_WRITE==pBt->inTransaction );
62089    rc2 = sqlite3PagerRollback(pBt->pPager);
62090    if( rc2!=SQLITE_OK ){
62091      rc = rc2;
62092    }
62093
62094    /* The rollback may have destroyed the pPage1->aData value.  So
62095    ** call btreeGetPage() on page 1 again to make
62096    ** sure pPage1->aData is set correctly. */
62097    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
62098      int nPage = get4byte(28+(u8*)pPage1->aData);
62099      testcase( nPage==0 );
62100      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
62101      testcase( pBt->nPage!=nPage );
62102      pBt->nPage = nPage;
62103      releasePage(pPage1);
62104    }
62105    assert( countValidCursors(pBt, 1)==0 );
62106    pBt->inTransaction = TRANS_READ;
62107    btreeClearHasContent(pBt);
62108  }
62109
62110  btreeEndTransaction(p);
62111  sqlite3BtreeLeave(p);
62112  return rc;
62113}
62114
62115/*
62116** Start a statement subtransaction. The subtransaction can be rolled
62117** back independently of the main transaction. You must start a transaction
62118** before starting a subtransaction. The subtransaction is ended automatically
62119** if the main transaction commits or rolls back.
62120**
62121** Statement subtransactions are used around individual SQL statements
62122** that are contained within a BEGIN...COMMIT block.  If a constraint
62123** error occurs within the statement, the effect of that one statement
62124** can be rolled back without having to rollback the entire transaction.
62125**
62126** A statement sub-transaction is implemented as an anonymous savepoint. The
62127** value passed as the second parameter is the total number of savepoints,
62128** including the new anonymous savepoint, open on the B-Tree. i.e. if there
62129** are no active savepoints and no other statement-transactions open,
62130** iStatement is 1. This anonymous savepoint can be released or rolled back
62131** using the sqlite3BtreeSavepoint() function.
62132*/
62133SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
62134  int rc;
62135  BtShared *pBt = p->pBt;
62136  sqlite3BtreeEnter(p);
62137  assert( p->inTrans==TRANS_WRITE );
62138  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62139  assert( iStatement>0 );
62140  assert( iStatement>p->db->nSavepoint );
62141  assert( pBt->inTransaction==TRANS_WRITE );
62142  /* At the pager level, a statement transaction is a savepoint with
62143  ** an index greater than all savepoints created explicitly using
62144  ** SQL statements. It is illegal to open, release or rollback any
62145  ** such savepoints while the statement transaction savepoint is active.
62146  */
62147  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
62148  sqlite3BtreeLeave(p);
62149  return rc;
62150}
62151
62152/*
62153** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
62154** or SAVEPOINT_RELEASE. This function either releases or rolls back the
62155** savepoint identified by parameter iSavepoint, depending on the value
62156** of op.
62157**
62158** Normally, iSavepoint is greater than or equal to zero. However, if op is
62159** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
62160** contents of the entire transaction are rolled back. This is different
62161** from a normal transaction rollback, as no locks are released and the
62162** transaction remains open.
62163*/
62164SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
62165  int rc = SQLITE_OK;
62166  if( p && p->inTrans==TRANS_WRITE ){
62167    BtShared *pBt = p->pBt;
62168    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
62169    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
62170    sqlite3BtreeEnter(p);
62171    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
62172    if( rc==SQLITE_OK ){
62173      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
62174        pBt->nPage = 0;
62175      }
62176      rc = newDatabase(pBt);
62177      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
62178
62179      /* The database size was written into the offset 28 of the header
62180      ** when the transaction started, so we know that the value at offset
62181      ** 28 is nonzero. */
62182      assert( pBt->nPage>0 );
62183    }
62184    sqlite3BtreeLeave(p);
62185  }
62186  return rc;
62187}
62188
62189/*
62190** Create a new cursor for the BTree whose root is on the page
62191** iTable. If a read-only cursor is requested, it is assumed that
62192** the caller already has at least a read-only transaction open
62193** on the database already. If a write-cursor is requested, then
62194** the caller is assumed to have an open write transaction.
62195**
62196** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
62197** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
62198** can be used for reading or for writing if other conditions for writing
62199** are also met.  These are the conditions that must be met in order
62200** for writing to be allowed:
62201**
62202** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
62203**
62204** 2:  Other database connections that share the same pager cache
62205**     but which are not in the READ_UNCOMMITTED state may not have
62206**     cursors open with wrFlag==0 on the same table.  Otherwise
62207**     the changes made by this write cursor would be visible to
62208**     the read cursors in the other database connection.
62209**
62210** 3:  The database must be writable (not on read-only media)
62211**
62212** 4:  There must be an active transaction.
62213**
62214** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
62215** is set.  If FORDELETE is set, that is a hint to the implementation that
62216** this cursor will only be used to seek to and delete entries of an index
62217** as part of a larger DELETE statement.  The FORDELETE hint is not used by
62218** this implementation.  But in a hypothetical alternative storage engine
62219** in which index entries are automatically deleted when corresponding table
62220** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
62221** operations on this cursor can be no-ops and all READ operations can
62222** return a null row (2-bytes: 0x01 0x00).
62223**
62224** No checking is done to make sure that page iTable really is the
62225** root page of a b-tree.  If it is not, then the cursor acquired
62226** will not work correctly.
62227**
62228** It is assumed that the sqlite3BtreeCursorZero() has been called
62229** on pCur to initialize the memory space prior to invoking this routine.
62230*/
62231static int btreeCursor(
62232  Btree *p,                              /* The btree */
62233  int iTable,                            /* Root page of table to open */
62234  int wrFlag,                            /* 1 to write. 0 read-only */
62235  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
62236  BtCursor *pCur                         /* Space for new cursor */
62237){
62238  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
62239  BtCursor *pX;                          /* Looping over other all cursors */
62240
62241  assert( sqlite3BtreeHoldsMutex(p) );
62242  assert( wrFlag==0
62243       || wrFlag==BTREE_WRCSR
62244       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
62245  );
62246
62247  /* The following assert statements verify that if this is a sharable
62248  ** b-tree database, the connection is holding the required table locks,
62249  ** and that no other connection has any open cursor that conflicts with
62250  ** this lock.  */
62251  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
62252  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
62253
62254  /* Assert that the caller has opened the required transaction. */
62255  assert( p->inTrans>TRANS_NONE );
62256  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
62257  assert( pBt->pPage1 && pBt->pPage1->aData );
62258  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
62259
62260  if( wrFlag ){
62261    allocateTempSpace(pBt);
62262    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
62263  }
62264  if( iTable==1 && btreePagecount(pBt)==0 ){
62265    assert( wrFlag==0 );
62266    iTable = 0;
62267  }
62268
62269  /* Now that no other errors can occur, finish filling in the BtCursor
62270  ** variables and link the cursor into the BtShared list.  */
62271  pCur->pgnoRoot = (Pgno)iTable;
62272  pCur->iPage = -1;
62273  pCur->pKeyInfo = pKeyInfo;
62274  pCur->pBtree = p;
62275  pCur->pBt = pBt;
62276  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
62277  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
62278  /* If there are two or more cursors on the same btree, then all such
62279  ** cursors *must* have the BTCF_Multiple flag set. */
62280  for(pX=pBt->pCursor; pX; pX=pX->pNext){
62281    if( pX->pgnoRoot==(Pgno)iTable ){
62282      pX->curFlags |= BTCF_Multiple;
62283      pCur->curFlags |= BTCF_Multiple;
62284    }
62285  }
62286  pCur->pNext = pBt->pCursor;
62287  pBt->pCursor = pCur;
62288  pCur->eState = CURSOR_INVALID;
62289  return SQLITE_OK;
62290}
62291SQLITE_PRIVATE int sqlite3BtreeCursor(
62292  Btree *p,                                   /* The btree */
62293  int iTable,                                 /* Root page of table to open */
62294  int wrFlag,                                 /* 1 to write. 0 read-only */
62295  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
62296  BtCursor *pCur                              /* Write new cursor here */
62297){
62298  int rc;
62299  if( iTable<1 ){
62300    rc = SQLITE_CORRUPT_BKPT;
62301  }else{
62302    sqlite3BtreeEnter(p);
62303    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
62304    sqlite3BtreeLeave(p);
62305  }
62306  return rc;
62307}
62308
62309/*
62310** Return the size of a BtCursor object in bytes.
62311**
62312** This interfaces is needed so that users of cursors can preallocate
62313** sufficient storage to hold a cursor.  The BtCursor object is opaque
62314** to users so they cannot do the sizeof() themselves - they must call
62315** this routine.
62316*/
62317SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
62318  return ROUND8(sizeof(BtCursor));
62319}
62320
62321/*
62322** Initialize memory that will be converted into a BtCursor object.
62323**
62324** The simple approach here would be to memset() the entire object
62325** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
62326** do not need to be zeroed and they are large, so we can save a lot
62327** of run-time by skipping the initialization of those elements.
62328*/
62329SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
62330  memset(p, 0, offsetof(BtCursor, iPage));
62331}
62332
62333/*
62334** Close a cursor.  The read lock on the database file is released
62335** when the last cursor is closed.
62336*/
62337SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
62338  Btree *pBtree = pCur->pBtree;
62339  if( pBtree ){
62340    int i;
62341    BtShared *pBt = pCur->pBt;
62342    sqlite3BtreeEnter(pBtree);
62343    sqlite3BtreeClearCursor(pCur);
62344    assert( pBt->pCursor!=0 );
62345    if( pBt->pCursor==pCur ){
62346      pBt->pCursor = pCur->pNext;
62347    }else{
62348      BtCursor *pPrev = pBt->pCursor;
62349      do{
62350        if( pPrev->pNext==pCur ){
62351          pPrev->pNext = pCur->pNext;
62352          break;
62353        }
62354        pPrev = pPrev->pNext;
62355      }while( ALWAYS(pPrev) );
62356    }
62357    for(i=0; i<=pCur->iPage; i++){
62358      releasePage(pCur->apPage[i]);
62359    }
62360    unlockBtreeIfUnused(pBt);
62361    sqlite3_free(pCur->aOverflow);
62362    /* sqlite3_free(pCur); */
62363    sqlite3BtreeLeave(pBtree);
62364  }
62365  return SQLITE_OK;
62366}
62367
62368/*
62369** Make sure the BtCursor* given in the argument has a valid
62370** BtCursor.info structure.  If it is not already valid, call
62371** btreeParseCell() to fill it in.
62372**
62373** BtCursor.info is a cache of the information in the current cell.
62374** Using this cache reduces the number of calls to btreeParseCell().
62375*/
62376#ifndef NDEBUG
62377  static void assertCellInfo(BtCursor *pCur){
62378    CellInfo info;
62379    int iPage = pCur->iPage;
62380    memset(&info, 0, sizeof(info));
62381    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
62382    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
62383  }
62384#else
62385  #define assertCellInfo(x)
62386#endif
62387static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
62388  if( pCur->info.nSize==0 ){
62389    int iPage = pCur->iPage;
62390    pCur->curFlags |= BTCF_ValidNKey;
62391    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
62392  }else{
62393    assertCellInfo(pCur);
62394  }
62395}
62396
62397#ifndef NDEBUG  /* The next routine used only within assert() statements */
62398/*
62399** Return true if the given BtCursor is valid.  A valid cursor is one
62400** that is currently pointing to a row in a (non-empty) table.
62401** This is a verification routine is used only within assert() statements.
62402*/
62403SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
62404  return pCur && pCur->eState==CURSOR_VALID;
62405}
62406#endif /* NDEBUG */
62407
62408/*
62409** Return the value of the integer key or "rowid" for a table btree.
62410** This routine is only valid for a cursor that is pointing into a
62411** ordinary table btree.  If the cursor points to an index btree or
62412** is invalid, the result of this routine is undefined.
62413*/
62414SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
62415  assert( cursorHoldsMutex(pCur) );
62416  assert( pCur->eState==CURSOR_VALID );
62417  assert( pCur->curIntKey );
62418  getCellInfo(pCur);
62419  return pCur->info.nKey;
62420}
62421
62422/*
62423** Return the number of bytes of payload for the entry that pCur is
62424** currently pointing to.  For table btrees, this will be the amount
62425** of data.  For index btrees, this will be the size of the key.
62426**
62427** The caller must guarantee that the cursor is pointing to a non-NULL
62428** valid entry.  In other words, the calling procedure must guarantee
62429** that the cursor has Cursor.eState==CURSOR_VALID.
62430*/
62431SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
62432  assert( cursorHoldsMutex(pCur) );
62433  assert( pCur->eState==CURSOR_VALID );
62434  getCellInfo(pCur);
62435  return pCur->info.nPayload;
62436}
62437
62438/*
62439** Given the page number of an overflow page in the database (parameter
62440** ovfl), this function finds the page number of the next page in the
62441** linked list of overflow pages. If possible, it uses the auto-vacuum
62442** pointer-map data instead of reading the content of page ovfl to do so.
62443**
62444** If an error occurs an SQLite error code is returned. Otherwise:
62445**
62446** The page number of the next overflow page in the linked list is
62447** written to *pPgnoNext. If page ovfl is the last page in its linked
62448** list, *pPgnoNext is set to zero.
62449**
62450** If ppPage is not NULL, and a reference to the MemPage object corresponding
62451** to page number pOvfl was obtained, then *ppPage is set to point to that
62452** reference. It is the responsibility of the caller to call releasePage()
62453** on *ppPage to free the reference. In no reference was obtained (because
62454** the pointer-map was used to obtain the value for *pPgnoNext), then
62455** *ppPage is set to zero.
62456*/
62457static int getOverflowPage(
62458  BtShared *pBt,               /* The database file */
62459  Pgno ovfl,                   /* Current overflow page number */
62460  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
62461  Pgno *pPgnoNext              /* OUT: Next overflow page number */
62462){
62463  Pgno next = 0;
62464  MemPage *pPage = 0;
62465  int rc = SQLITE_OK;
62466
62467  assert( sqlite3_mutex_held(pBt->mutex) );
62468  assert(pPgnoNext);
62469
62470#ifndef SQLITE_OMIT_AUTOVACUUM
62471  /* Try to find the next page in the overflow list using the
62472  ** autovacuum pointer-map pages. Guess that the next page in
62473  ** the overflow list is page number (ovfl+1). If that guess turns
62474  ** out to be wrong, fall back to loading the data of page
62475  ** number ovfl to determine the next page number.
62476  */
62477  if( pBt->autoVacuum ){
62478    Pgno pgno;
62479    Pgno iGuess = ovfl+1;
62480    u8 eType;
62481
62482    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
62483      iGuess++;
62484    }
62485
62486    if( iGuess<=btreePagecount(pBt) ){
62487      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
62488      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
62489        next = iGuess;
62490        rc = SQLITE_DONE;
62491      }
62492    }
62493  }
62494#endif
62495
62496  assert( next==0 || rc==SQLITE_DONE );
62497  if( rc==SQLITE_OK ){
62498    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
62499    assert( rc==SQLITE_OK || pPage==0 );
62500    if( rc==SQLITE_OK ){
62501      next = get4byte(pPage->aData);
62502    }
62503  }
62504
62505  *pPgnoNext = next;
62506  if( ppPage ){
62507    *ppPage = pPage;
62508  }else{
62509    releasePage(pPage);
62510  }
62511  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
62512}
62513
62514/*
62515** Copy data from a buffer to a page, or from a page to a buffer.
62516**
62517** pPayload is a pointer to data stored on database page pDbPage.
62518** If argument eOp is false, then nByte bytes of data are copied
62519** from pPayload to the buffer pointed at by pBuf. If eOp is true,
62520** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
62521** of data are copied from the buffer pBuf to pPayload.
62522**
62523** SQLITE_OK is returned on success, otherwise an error code.
62524*/
62525static int copyPayload(
62526  void *pPayload,           /* Pointer to page data */
62527  void *pBuf,               /* Pointer to buffer */
62528  int nByte,                /* Number of bytes to copy */
62529  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
62530  DbPage *pDbPage           /* Page containing pPayload */
62531){
62532  if( eOp ){
62533    /* Copy data from buffer to page (a write operation) */
62534    int rc = sqlite3PagerWrite(pDbPage);
62535    if( rc!=SQLITE_OK ){
62536      return rc;
62537    }
62538    memcpy(pPayload, pBuf, nByte);
62539  }else{
62540    /* Copy data from page to buffer (a read operation) */
62541    memcpy(pBuf, pPayload, nByte);
62542  }
62543  return SQLITE_OK;
62544}
62545
62546/*
62547** This function is used to read or overwrite payload information
62548** for the entry that the pCur cursor is pointing to. The eOp
62549** argument is interpreted as follows:
62550**
62551**   0: The operation is a read. Populate the overflow cache.
62552**   1: The operation is a write. Populate the overflow cache.
62553**   2: The operation is a read. Do not populate the overflow cache.
62554**
62555** A total of "amt" bytes are read or written beginning at "offset".
62556** Data is read to or from the buffer pBuf.
62557**
62558** The content being read or written might appear on the main page
62559** or be scattered out on multiple overflow pages.
62560**
62561** If the current cursor entry uses one or more overflow pages and the
62562** eOp argument is not 2, this function may allocate space for and lazily
62563** populates the overflow page-list cache array (BtCursor.aOverflow).
62564** Subsequent calls use this cache to make seeking to the supplied offset
62565** more efficient.
62566**
62567** Once an overflow page-list cache has been allocated, it may be
62568** invalidated if some other cursor writes to the same table, or if
62569** the cursor is moved to a different row. Additionally, in auto-vacuum
62570** mode, the following events may invalidate an overflow page-list cache.
62571**
62572**   * An incremental vacuum,
62573**   * A commit in auto_vacuum="full" mode,
62574**   * Creating a table (may require moving an overflow page).
62575*/
62576static int accessPayload(
62577  BtCursor *pCur,      /* Cursor pointing to entry to read from */
62578  u32 offset,          /* Begin reading this far into payload */
62579  u32 amt,             /* Read this many bytes */
62580  unsigned char *pBuf, /* Write the bytes into this buffer */
62581  int eOp              /* zero to read. non-zero to write. */
62582){
62583  unsigned char *aPayload;
62584  int rc = SQLITE_OK;
62585  int iIdx = 0;
62586  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
62587  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
62588#ifdef SQLITE_DIRECT_OVERFLOW_READ
62589  unsigned char * const pBufStart = pBuf;
62590  int bEnd;                                 /* True if reading to end of data */
62591#endif
62592
62593  assert( pPage );
62594  assert( pCur->eState==CURSOR_VALID );
62595  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62596  assert( cursorHoldsMutex(pCur) );
62597  assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
62598
62599  getCellInfo(pCur);
62600  aPayload = pCur->info.pPayload;
62601#ifdef SQLITE_DIRECT_OVERFLOW_READ
62602  bEnd = offset+amt==pCur->info.nPayload;
62603#endif
62604  assert( offset+amt <= pCur->info.nPayload );
62605
62606  assert( aPayload > pPage->aData );
62607  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
62608    /* Trying to read or write past the end of the data is an error.  The
62609    ** conditional above is really:
62610    **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
62611    ** but is recast into its current form to avoid integer overflow problems
62612    */
62613    return SQLITE_CORRUPT_BKPT;
62614  }
62615
62616  /* Check if data must be read/written to/from the btree page itself. */
62617  if( offset<pCur->info.nLocal ){
62618    int a = amt;
62619    if( a+offset>pCur->info.nLocal ){
62620      a = pCur->info.nLocal - offset;
62621    }
62622    rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
62623    offset = 0;
62624    pBuf += a;
62625    amt -= a;
62626  }else{
62627    offset -= pCur->info.nLocal;
62628  }
62629
62630
62631  if( rc==SQLITE_OK && amt>0 ){
62632    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
62633    Pgno nextPage;
62634
62635    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
62636
62637    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
62638    ** Except, do not allocate aOverflow[] for eOp==2.
62639    **
62640    ** The aOverflow[] array is sized at one entry for each overflow page
62641    ** in the overflow chain. The page number of the first overflow page is
62642    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
62643    ** means "not yet known" (the cache is lazily populated).
62644    */
62645    if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
62646      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
62647      if( nOvfl>pCur->nOvflAlloc ){
62648        Pgno *aNew = (Pgno*)sqlite3Realloc(
62649            pCur->aOverflow, nOvfl*2*sizeof(Pgno)
62650        );
62651        if( aNew==0 ){
62652          rc = SQLITE_NOMEM_BKPT;
62653        }else{
62654          pCur->nOvflAlloc = nOvfl*2;
62655          pCur->aOverflow = aNew;
62656        }
62657      }
62658      if( rc==SQLITE_OK ){
62659        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
62660        pCur->curFlags |= BTCF_ValidOvfl;
62661      }
62662    }
62663
62664    /* If the overflow page-list cache has been allocated and the
62665    ** entry for the first required overflow page is valid, skip
62666    ** directly to it.
62667    */
62668    if( (pCur->curFlags & BTCF_ValidOvfl)!=0
62669     && pCur->aOverflow[offset/ovflSize]
62670    ){
62671      iIdx = (offset/ovflSize);
62672      nextPage = pCur->aOverflow[iIdx];
62673      offset = (offset%ovflSize);
62674    }
62675
62676    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
62677
62678      /* If required, populate the overflow page-list cache. */
62679      if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
62680        assert( pCur->aOverflow[iIdx]==0
62681                || pCur->aOverflow[iIdx]==nextPage
62682                || CORRUPT_DB );
62683        pCur->aOverflow[iIdx] = nextPage;
62684      }
62685
62686      if( offset>=ovflSize ){
62687        /* The only reason to read this page is to obtain the page
62688        ** number for the next page in the overflow chain. The page
62689        ** data is not required. So first try to lookup the overflow
62690        ** page-list cache, if any, then fall back to the getOverflowPage()
62691        ** function.
62692        **
62693        ** Note that the aOverflow[] array must be allocated because eOp!=2
62694        ** here.  If eOp==2, then offset==0 and this branch is never taken.
62695        */
62696        assert( eOp!=2 );
62697        assert( pCur->curFlags & BTCF_ValidOvfl );
62698        assert( pCur->pBtree->db==pBt->db );
62699        if( pCur->aOverflow[iIdx+1] ){
62700          nextPage = pCur->aOverflow[iIdx+1];
62701        }else{
62702          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
62703        }
62704        offset -= ovflSize;
62705      }else{
62706        /* Need to read this page properly. It contains some of the
62707        ** range of data that is being read (eOp==0) or written (eOp!=0).
62708        */
62709#ifdef SQLITE_DIRECT_OVERFLOW_READ
62710        sqlite3_file *fd;
62711#endif
62712        int a = amt;
62713        if( a + offset > ovflSize ){
62714          a = ovflSize - offset;
62715        }
62716
62717#ifdef SQLITE_DIRECT_OVERFLOW_READ
62718        /* If all the following are true:
62719        **
62720        **   1) this is a read operation, and
62721        **   2) data is required from the start of this overflow page, and
62722        **   3) the database is file-backed, and
62723        **   4) there is no open write-transaction, and
62724        **   5) the database is not a WAL database,
62725        **   6) all data from the page is being read.
62726        **   7) at least 4 bytes have already been read into the output buffer
62727        **
62728        ** then data can be read directly from the database file into the
62729        ** output buffer, bypassing the page-cache altogether. This speeds
62730        ** up loading large records that span many overflow pages.
62731        */
62732        if( (eOp&0x01)==0                                      /* (1) */
62733         && offset==0                                          /* (2) */
62734         && (bEnd || a==ovflSize)                              /* (6) */
62735         && pBt->inTransaction==TRANS_READ                     /* (4) */
62736         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
62737         && pBt->pPage1->aData[19]==0x01                       /* (5) */
62738         && &pBuf[-4]>=pBufStart                               /* (7) */
62739        ){
62740          u8 aSave[4];
62741          u8 *aWrite = &pBuf[-4];
62742          assert( aWrite>=pBufStart );                         /* hence (7) */
62743          memcpy(aSave, aWrite, 4);
62744          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
62745          nextPage = get4byte(aWrite);
62746          memcpy(aWrite, aSave, 4);
62747        }else
62748#endif
62749
62750        {
62751          DbPage *pDbPage;
62752          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
62753              ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
62754          );
62755          if( rc==SQLITE_OK ){
62756            aPayload = sqlite3PagerGetData(pDbPage);
62757            nextPage = get4byte(aPayload);
62758            rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
62759            sqlite3PagerUnref(pDbPage);
62760            offset = 0;
62761          }
62762        }
62763        amt -= a;
62764        pBuf += a;
62765      }
62766    }
62767  }
62768
62769  if( rc==SQLITE_OK && amt>0 ){
62770    return SQLITE_CORRUPT_BKPT;
62771  }
62772  return rc;
62773}
62774
62775/*
62776** Read part of the key associated with cursor pCur.  Exactly
62777** "amt" bytes will be transferred into pBuf[].  The transfer
62778** begins at "offset".
62779**
62780** The caller must ensure that pCur is pointing to a valid row
62781** in the table.
62782**
62783** Return SQLITE_OK on success or an error code if anything goes
62784** wrong.  An error is returned if "offset+amt" is larger than
62785** the available payload.
62786*/
62787SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62788  assert( cursorHoldsMutex(pCur) );
62789  assert( pCur->eState==CURSOR_VALID );
62790  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62791  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62792  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
62793}
62794
62795/*
62796** Read part of the data associated with cursor pCur.  Exactly
62797** "amt" bytes will be transfered into pBuf[].  The transfer
62798** begins at "offset".
62799**
62800** Return SQLITE_OK on success or an error code if anything goes
62801** wrong.  An error is returned if "offset+amt" is larger than
62802** the available payload.
62803*/
62804SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62805  int rc;
62806
62807#ifndef SQLITE_OMIT_INCRBLOB
62808  if ( pCur->eState==CURSOR_INVALID ){
62809    return SQLITE_ABORT;
62810  }
62811#endif
62812
62813  assert( cursorOwnsBtShared(pCur) );
62814  rc = restoreCursorPosition(pCur);
62815  if( rc==SQLITE_OK ){
62816    assert( pCur->eState==CURSOR_VALID );
62817    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62818    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62819    rc = accessPayload(pCur, offset, amt, pBuf, 0);
62820  }
62821  return rc;
62822}
62823
62824/*
62825** Return a pointer to payload information from the entry that the
62826** pCur cursor is pointing to.  The pointer is to the beginning of
62827** the key if index btrees (pPage->intKey==0) and is the data for
62828** table btrees (pPage->intKey==1). The number of bytes of available
62829** key/data is written into *pAmt.  If *pAmt==0, then the value
62830** returned will not be a valid pointer.
62831**
62832** This routine is an optimization.  It is common for the entire key
62833** and data to fit on the local page and for there to be no overflow
62834** pages.  When that is so, this routine can be used to access the
62835** key and data without making a copy.  If the key and/or data spills
62836** onto overflow pages, then accessPayload() must be used to reassemble
62837** the key/data and copy it into a preallocated buffer.
62838**
62839** The pointer returned by this routine looks directly into the cached
62840** page of the database.  The data might change or move the next time
62841** any btree routine is called.
62842*/
62843static const void *fetchPayload(
62844  BtCursor *pCur,      /* Cursor pointing to entry to read from */
62845  u32 *pAmt            /* Write the number of available bytes here */
62846){
62847  u32 amt;
62848  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
62849  assert( pCur->eState==CURSOR_VALID );
62850  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62851  assert( cursorOwnsBtShared(pCur) );
62852  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62853  assert( pCur->info.nSize>0 );
62854  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
62855  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
62856  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
62857  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
62858  *pAmt = amt;
62859  return (void*)pCur->info.pPayload;
62860}
62861
62862
62863/*
62864** For the entry that cursor pCur is point to, return as
62865** many bytes of the key or data as are available on the local
62866** b-tree page.  Write the number of available bytes into *pAmt.
62867**
62868** The pointer returned is ephemeral.  The key/data may move
62869** or be destroyed on the next call to any Btree routine,
62870** including calls from other threads against the same cache.
62871** Hence, a mutex on the BtShared should be held prior to calling
62872** this routine.
62873**
62874** These routines is used to get quick access to key and data
62875** in the common case where no overflow pages are used.
62876*/
62877SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
62878  return fetchPayload(pCur, pAmt);
62879}
62880
62881
62882/*
62883** Move the cursor down to a new child page.  The newPgno argument is the
62884** page number of the child page to move to.
62885**
62886** This function returns SQLITE_CORRUPT if the page-header flags field of
62887** the new child page does not match the flags field of the parent (i.e.
62888** if an intkey page appears to be the parent of a non-intkey page, or
62889** vice-versa).
62890*/
62891static int moveToChild(BtCursor *pCur, u32 newPgno){
62892  BtShared *pBt = pCur->pBt;
62893
62894  assert( cursorOwnsBtShared(pCur) );
62895  assert( pCur->eState==CURSOR_VALID );
62896  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
62897  assert( pCur->iPage>=0 );
62898  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
62899    return SQLITE_CORRUPT_BKPT;
62900  }
62901  pCur->info.nSize = 0;
62902  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
62903  pCur->iPage++;
62904  pCur->aiIdx[pCur->iPage] = 0;
62905  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
62906                        pCur, pCur->curPagerFlags);
62907}
62908
62909#if SQLITE_DEBUG
62910/*
62911** Page pParent is an internal (non-leaf) tree page. This function
62912** asserts that page number iChild is the left-child if the iIdx'th
62913** cell in page pParent. Or, if iIdx is equal to the total number of
62914** cells in pParent, that page number iChild is the right-child of
62915** the page.
62916*/
62917static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
62918  if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
62919                            ** in a corrupt database */
62920  assert( iIdx<=pParent->nCell );
62921  if( iIdx==pParent->nCell ){
62922    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
62923  }else{
62924    assert( get4byte(findCell(pParent, iIdx))==iChild );
62925  }
62926}
62927#else
62928#  define assertParentIndex(x,y,z)
62929#endif
62930
62931/*
62932** Move the cursor up to the parent page.
62933**
62934** pCur->idx is set to the cell index that contains the pointer
62935** to the page we are coming from.  If we are coming from the
62936** right-most child page then pCur->idx is set to one more than
62937** the largest cell index.
62938*/
62939static void moveToParent(BtCursor *pCur){
62940  assert( cursorOwnsBtShared(pCur) );
62941  assert( pCur->eState==CURSOR_VALID );
62942  assert( pCur->iPage>0 );
62943  assert( pCur->apPage[pCur->iPage] );
62944  assertParentIndex(
62945    pCur->apPage[pCur->iPage-1],
62946    pCur->aiIdx[pCur->iPage-1],
62947    pCur->apPage[pCur->iPage]->pgno
62948  );
62949  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
62950  pCur->info.nSize = 0;
62951  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
62952  releasePageNotNull(pCur->apPage[pCur->iPage--]);
62953}
62954
62955/*
62956** Move the cursor to point to the root page of its b-tree structure.
62957**
62958** If the table has a virtual root page, then the cursor is moved to point
62959** to the virtual root page instead of the actual root page. A table has a
62960** virtual root page when the actual root page contains no cells and a
62961** single child page. This can only happen with the table rooted at page 1.
62962**
62963** If the b-tree structure is empty, the cursor state is set to
62964** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
62965** cell located on the root (or virtual root) page and the cursor state
62966** is set to CURSOR_VALID.
62967**
62968** If this function returns successfully, it may be assumed that the
62969** page-header flags indicate that the [virtual] root-page is the expected
62970** kind of b-tree page (i.e. if when opening the cursor the caller did not
62971** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
62972** indicating a table b-tree, or if the caller did specify a KeyInfo
62973** structure the flags byte is set to 0x02 or 0x0A, indicating an index
62974** b-tree).
62975*/
62976static int moveToRoot(BtCursor *pCur){
62977  MemPage *pRoot;
62978  int rc = SQLITE_OK;
62979
62980  assert( cursorOwnsBtShared(pCur) );
62981  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
62982  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
62983  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
62984  if( pCur->eState>=CURSOR_REQUIRESEEK ){
62985    if( pCur->eState==CURSOR_FAULT ){
62986      assert( pCur->skipNext!=SQLITE_OK );
62987      return pCur->skipNext;
62988    }
62989    sqlite3BtreeClearCursor(pCur);
62990  }
62991
62992  if( pCur->iPage>=0 ){
62993    while( pCur->iPage ){
62994      assert( pCur->apPage[pCur->iPage]!=0 );
62995      releasePageNotNull(pCur->apPage[pCur->iPage--]);
62996    }
62997  }else if( pCur->pgnoRoot==0 ){
62998    pCur->eState = CURSOR_INVALID;
62999    return SQLITE_OK;
63000  }else{
63001    assert( pCur->iPage==(-1) );
63002    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
63003                        0, pCur->curPagerFlags);
63004    if( rc!=SQLITE_OK ){
63005      pCur->eState = CURSOR_INVALID;
63006      return rc;
63007    }
63008    pCur->iPage = 0;
63009    pCur->curIntKey = pCur->apPage[0]->intKey;
63010  }
63011  pRoot = pCur->apPage[0];
63012  assert( pRoot->pgno==pCur->pgnoRoot );
63013
63014  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
63015  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
63016  ** NULL, the caller expects a table b-tree. If this is not the case,
63017  ** return an SQLITE_CORRUPT error.
63018  **
63019  ** Earlier versions of SQLite assumed that this test could not fail
63020  ** if the root page was already loaded when this function was called (i.e.
63021  ** if pCur->iPage>=0). But this is not so if the database is corrupted
63022  ** in such a way that page pRoot is linked into a second b-tree table
63023  ** (or the freelist).  */
63024  assert( pRoot->intKey==1 || pRoot->intKey==0 );
63025  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
63026    return SQLITE_CORRUPT_BKPT;
63027  }
63028
63029  pCur->aiIdx[0] = 0;
63030  pCur->info.nSize = 0;
63031  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
63032
63033  if( pRoot->nCell>0 ){
63034    pCur->eState = CURSOR_VALID;
63035  }else if( !pRoot->leaf ){
63036    Pgno subpage;
63037    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
63038    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
63039    pCur->eState = CURSOR_VALID;
63040    rc = moveToChild(pCur, subpage);
63041  }else{
63042    pCur->eState = CURSOR_INVALID;
63043  }
63044  return rc;
63045}
63046
63047/*
63048** Move the cursor down to the left-most leaf entry beneath the
63049** entry to which it is currently pointing.
63050**
63051** The left-most leaf is the one with the smallest key - the first
63052** in ascending order.
63053*/
63054static int moveToLeftmost(BtCursor *pCur){
63055  Pgno pgno;
63056  int rc = SQLITE_OK;
63057  MemPage *pPage;
63058
63059  assert( cursorOwnsBtShared(pCur) );
63060  assert( pCur->eState==CURSOR_VALID );
63061  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63062    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63063    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
63064    rc = moveToChild(pCur, pgno);
63065  }
63066  return rc;
63067}
63068
63069/*
63070** Move the cursor down to the right-most leaf entry beneath the
63071** page to which it is currently pointing.  Notice the difference
63072** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
63073** finds the left-most entry beneath the *entry* whereas moveToRightmost()
63074** finds the right-most entry beneath the *page*.
63075**
63076** The right-most entry is the one with the largest key - the last
63077** key in ascending order.
63078*/
63079static int moveToRightmost(BtCursor *pCur){
63080  Pgno pgno;
63081  int rc = SQLITE_OK;
63082  MemPage *pPage = 0;
63083
63084  assert( cursorOwnsBtShared(pCur) );
63085  assert( pCur->eState==CURSOR_VALID );
63086  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63087    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63088    pCur->aiIdx[pCur->iPage] = pPage->nCell;
63089    rc = moveToChild(pCur, pgno);
63090    if( rc ) return rc;
63091  }
63092  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
63093  assert( pCur->info.nSize==0 );
63094  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
63095  return SQLITE_OK;
63096}
63097
63098/* Move the cursor to the first entry in the table.  Return SQLITE_OK
63099** on success.  Set *pRes to 0 if the cursor actually points to something
63100** or set *pRes to 1 if the table is empty.
63101*/
63102SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
63103  int rc;
63104
63105  assert( cursorOwnsBtShared(pCur) );
63106  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63107  rc = moveToRoot(pCur);
63108  if( rc==SQLITE_OK ){
63109    if( pCur->eState==CURSOR_INVALID ){
63110      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63111      *pRes = 1;
63112    }else{
63113      assert( pCur->apPage[pCur->iPage]->nCell>0 );
63114      *pRes = 0;
63115      rc = moveToLeftmost(pCur);
63116    }
63117  }
63118  return rc;
63119}
63120
63121/* Move the cursor to the last entry in the table.  Return SQLITE_OK
63122** on success.  Set *pRes to 0 if the cursor actually points to something
63123** or set *pRes to 1 if the table is empty.
63124*/
63125SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
63126  int rc;
63127
63128  assert( cursorOwnsBtShared(pCur) );
63129  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63130
63131  /* If the cursor already points to the last entry, this is a no-op. */
63132  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
63133#ifdef SQLITE_DEBUG
63134    /* This block serves to assert() that the cursor really does point
63135    ** to the last entry in the b-tree. */
63136    int ii;
63137    for(ii=0; ii<pCur->iPage; ii++){
63138      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
63139    }
63140    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
63141    assert( pCur->apPage[pCur->iPage]->leaf );
63142#endif
63143    return SQLITE_OK;
63144  }
63145
63146  rc = moveToRoot(pCur);
63147  if( rc==SQLITE_OK ){
63148    if( CURSOR_INVALID==pCur->eState ){
63149      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63150      *pRes = 1;
63151    }else{
63152      assert( pCur->eState==CURSOR_VALID );
63153      *pRes = 0;
63154      rc = moveToRightmost(pCur);
63155      if( rc==SQLITE_OK ){
63156        pCur->curFlags |= BTCF_AtLast;
63157      }else{
63158        pCur->curFlags &= ~BTCF_AtLast;
63159      }
63160
63161    }
63162  }
63163  return rc;
63164}
63165
63166/* Move the cursor so that it points to an entry near the key
63167** specified by pIdxKey or intKey.   Return a success code.
63168**
63169** For INTKEY tables, the intKey parameter is used.  pIdxKey
63170** must be NULL.  For index tables, pIdxKey is used and intKey
63171** is ignored.
63172**
63173** If an exact match is not found, then the cursor is always
63174** left pointing at a leaf page which would hold the entry if it
63175** were present.  The cursor might point to an entry that comes
63176** before or after the key.
63177**
63178** An integer is written into *pRes which is the result of
63179** comparing the key with the entry to which the cursor is
63180** pointing.  The meaning of the integer written into
63181** *pRes is as follows:
63182**
63183**     *pRes<0      The cursor is left pointing at an entry that
63184**                  is smaller than intKey/pIdxKey or if the table is empty
63185**                  and the cursor is therefore left point to nothing.
63186**
63187**     *pRes==0     The cursor is left pointing at an entry that
63188**                  exactly matches intKey/pIdxKey.
63189**
63190**     *pRes>0      The cursor is left pointing at an entry that
63191**                  is larger than intKey/pIdxKey.
63192**
63193** For index tables, the pIdxKey->eqSeen field is set to 1 if there
63194** exists an entry in the table that exactly matches pIdxKey.
63195*/
63196SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
63197  BtCursor *pCur,          /* The cursor to be moved */
63198  UnpackedRecord *pIdxKey, /* Unpacked index key */
63199  i64 intKey,              /* The table key */
63200  int biasRight,           /* If true, bias the search to the high end */
63201  int *pRes                /* Write search results here */
63202){
63203  int rc;
63204  RecordCompare xRecordCompare;
63205
63206  assert( cursorOwnsBtShared(pCur) );
63207  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63208  assert( pRes );
63209  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
63210  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
63211
63212  /* If the cursor is already positioned at the point we are trying
63213  ** to move to, then just return without doing any work */
63214  if( pIdxKey==0
63215   && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
63216  ){
63217    if( pCur->info.nKey==intKey ){
63218      *pRes = 0;
63219      return SQLITE_OK;
63220    }
63221    if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
63222      *pRes = -1;
63223      return SQLITE_OK;
63224    }
63225  }
63226
63227  if( pIdxKey ){
63228    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
63229    pIdxKey->errCode = 0;
63230    assert( pIdxKey->default_rc==1
63231         || pIdxKey->default_rc==0
63232         || pIdxKey->default_rc==-1
63233    );
63234  }else{
63235    xRecordCompare = 0; /* All keys are integers */
63236  }
63237
63238  rc = moveToRoot(pCur);
63239  if( rc ){
63240    return rc;
63241  }
63242  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
63243  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
63244  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
63245  if( pCur->eState==CURSOR_INVALID ){
63246    *pRes = -1;
63247    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63248    return SQLITE_OK;
63249  }
63250  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
63251  assert( pCur->curIntKey || pIdxKey );
63252  for(;;){
63253    int lwr, upr, idx, c;
63254    Pgno chldPg;
63255    MemPage *pPage = pCur->apPage[pCur->iPage];
63256    u8 *pCell;                          /* Pointer to current cell in pPage */
63257
63258    /* pPage->nCell must be greater than zero. If this is the root-page
63259    ** the cursor would have been INVALID above and this for(;;) loop
63260    ** not run. If this is not the root-page, then the moveToChild() routine
63261    ** would have already detected db corruption. Similarly, pPage must
63262    ** be the right kind (index or table) of b-tree page. Otherwise
63263    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
63264    assert( pPage->nCell>0 );
63265    assert( pPage->intKey==(pIdxKey==0) );
63266    lwr = 0;
63267    upr = pPage->nCell-1;
63268    assert( biasRight==0 || biasRight==1 );
63269    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
63270    pCur->aiIdx[pCur->iPage] = (u16)idx;
63271    if( xRecordCompare==0 ){
63272      for(;;){
63273        i64 nCellKey;
63274        pCell = findCellPastPtr(pPage, idx);
63275        if( pPage->intKeyLeaf ){
63276          while( 0x80 <= *(pCell++) ){
63277            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
63278          }
63279        }
63280        getVarint(pCell, (u64*)&nCellKey);
63281        if( nCellKey<intKey ){
63282          lwr = idx+1;
63283          if( lwr>upr ){ c = -1; break; }
63284        }else if( nCellKey>intKey ){
63285          upr = idx-1;
63286          if( lwr>upr ){ c = +1; break; }
63287        }else{
63288          assert( nCellKey==intKey );
63289          pCur->curFlags |= BTCF_ValidNKey;
63290          pCur->info.nKey = nCellKey;
63291          pCur->aiIdx[pCur->iPage] = (u16)idx;
63292          if( !pPage->leaf ){
63293            lwr = idx;
63294            goto moveto_next_layer;
63295          }else{
63296            *pRes = 0;
63297            rc = SQLITE_OK;
63298            goto moveto_finish;
63299          }
63300        }
63301        assert( lwr+upr>=0 );
63302        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
63303      }
63304    }else{
63305      for(;;){
63306        int nCell;  /* Size of the pCell cell in bytes */
63307        pCell = findCellPastPtr(pPage, idx);
63308
63309        /* The maximum supported page-size is 65536 bytes. This means that
63310        ** the maximum number of record bytes stored on an index B-Tree
63311        ** page is less than 16384 bytes and may be stored as a 2-byte
63312        ** varint. This information is used to attempt to avoid parsing
63313        ** the entire cell by checking for the cases where the record is
63314        ** stored entirely within the b-tree page by inspecting the first
63315        ** 2 bytes of the cell.
63316        */
63317        nCell = pCell[0];
63318        if( nCell<=pPage->max1bytePayload ){
63319          /* This branch runs if the record-size field of the cell is a
63320          ** single byte varint and the record fits entirely on the main
63321          ** b-tree page.  */
63322          testcase( pCell+nCell+1==pPage->aDataEnd );
63323          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
63324        }else if( !(pCell[1] & 0x80)
63325          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
63326        ){
63327          /* The record-size field is a 2 byte varint and the record
63328          ** fits entirely on the main b-tree page.  */
63329          testcase( pCell+nCell+2==pPage->aDataEnd );
63330          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
63331        }else{
63332          /* The record flows over onto one or more overflow pages. In
63333          ** this case the whole cell needs to be parsed, a buffer allocated
63334          ** and accessPayload() used to retrieve the record into the
63335          ** buffer before VdbeRecordCompare() can be called.
63336          **
63337          ** If the record is corrupt, the xRecordCompare routine may read
63338          ** up to two varints past the end of the buffer. An extra 18
63339          ** bytes of padding is allocated at the end of the buffer in
63340          ** case this happens.  */
63341          void *pCellKey;
63342          u8 * const pCellBody = pCell - pPage->childPtrSize;
63343          pPage->xParseCell(pPage, pCellBody, &pCur->info);
63344          nCell = (int)pCur->info.nKey;
63345          testcase( nCell<0 );   /* True if key size is 2^32 or more */
63346          testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
63347          testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
63348          testcase( nCell==2 );  /* Minimum legal index key size */
63349          if( nCell<2 ){
63350            rc = SQLITE_CORRUPT_BKPT;
63351            goto moveto_finish;
63352          }
63353          pCellKey = sqlite3Malloc( nCell+18 );
63354          if( pCellKey==0 ){
63355            rc = SQLITE_NOMEM_BKPT;
63356            goto moveto_finish;
63357          }
63358          pCur->aiIdx[pCur->iPage] = (u16)idx;
63359          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
63360          if( rc ){
63361            sqlite3_free(pCellKey);
63362            goto moveto_finish;
63363          }
63364          c = xRecordCompare(nCell, pCellKey, pIdxKey);
63365          sqlite3_free(pCellKey);
63366        }
63367        assert(
63368            (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
63369         && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
63370        );
63371        if( c<0 ){
63372          lwr = idx+1;
63373        }else if( c>0 ){
63374          upr = idx-1;
63375        }else{
63376          assert( c==0 );
63377          *pRes = 0;
63378          rc = SQLITE_OK;
63379          pCur->aiIdx[pCur->iPage] = (u16)idx;
63380          if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
63381          goto moveto_finish;
63382        }
63383        if( lwr>upr ) break;
63384        assert( lwr+upr>=0 );
63385        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
63386      }
63387    }
63388    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
63389    assert( pPage->isInit );
63390    if( pPage->leaf ){
63391      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63392      pCur->aiIdx[pCur->iPage] = (u16)idx;
63393      *pRes = c;
63394      rc = SQLITE_OK;
63395      goto moveto_finish;
63396    }
63397moveto_next_layer:
63398    if( lwr>=pPage->nCell ){
63399      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63400    }else{
63401      chldPg = get4byte(findCell(pPage, lwr));
63402    }
63403    pCur->aiIdx[pCur->iPage] = (u16)lwr;
63404    rc = moveToChild(pCur, chldPg);
63405    if( rc ) break;
63406  }
63407moveto_finish:
63408  pCur->info.nSize = 0;
63409  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63410  return rc;
63411}
63412
63413
63414/*
63415** Return TRUE if the cursor is not pointing at an entry of the table.
63416**
63417** TRUE will be returned after a call to sqlite3BtreeNext() moves
63418** past the last entry in the table or sqlite3BtreePrev() moves past
63419** the first entry.  TRUE is also returned if the table is empty.
63420*/
63421SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
63422  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
63423  ** have been deleted? This API will need to change to return an error code
63424  ** as well as the boolean result value.
63425  */
63426  return (CURSOR_VALID!=pCur->eState);
63427}
63428
63429/*
63430** Advance the cursor to the next entry in the database.  If
63431** successful then set *pRes=0.  If the cursor
63432** was already pointing to the last entry in the database before
63433** this routine was called, then set *pRes=1.
63434**
63435** The main entry point is sqlite3BtreeNext().  That routine is optimized
63436** for the common case of merely incrementing the cell counter BtCursor.aiIdx
63437** to the next cell on the current page.  The (slower) btreeNext() helper
63438** routine is called when it is necessary to move to a different page or
63439** to restore the cursor.
63440**
63441** The calling function will set *pRes to 0 or 1.  The initial *pRes value
63442** will be 1 if the cursor being stepped corresponds to an SQL index and
63443** if this routine could have been skipped if that SQL index had been
63444** a unique index.  Otherwise the caller will have set *pRes to zero.
63445** Zero is the common case. The btree implementation is free to use the
63446** initial *pRes value as a hint to improve performance, but the current
63447** SQLite btree implementation does not. (Note that the comdb2 btree
63448** implementation does use this hint, however.)
63449*/
63450static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
63451  int rc;
63452  int idx;
63453  MemPage *pPage;
63454
63455  assert( cursorOwnsBtShared(pCur) );
63456  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63457  assert( *pRes==0 );
63458  if( pCur->eState!=CURSOR_VALID ){
63459    assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
63460    rc = restoreCursorPosition(pCur);
63461    if( rc!=SQLITE_OK ){
63462      return rc;
63463    }
63464    if( CURSOR_INVALID==pCur->eState ){
63465      *pRes = 1;
63466      return SQLITE_OK;
63467    }
63468    if( pCur->skipNext ){
63469      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63470      pCur->eState = CURSOR_VALID;
63471      if( pCur->skipNext>0 ){
63472        pCur->skipNext = 0;
63473        return SQLITE_OK;
63474      }
63475      pCur->skipNext = 0;
63476    }
63477  }
63478
63479  pPage = pCur->apPage[pCur->iPage];
63480  idx = ++pCur->aiIdx[pCur->iPage];
63481  assert( pPage->isInit );
63482
63483  /* If the database file is corrupt, it is possible for the value of idx
63484  ** to be invalid here. This can only occur if a second cursor modifies
63485  ** the page while cursor pCur is holding a reference to it. Which can
63486  ** only happen if the database is corrupt in such a way as to link the
63487  ** page into more than one b-tree structure. */
63488  testcase( idx>pPage->nCell );
63489
63490  if( idx>=pPage->nCell ){
63491    if( !pPage->leaf ){
63492      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63493      if( rc ) return rc;
63494      return moveToLeftmost(pCur);
63495    }
63496    do{
63497      if( pCur->iPage==0 ){
63498        *pRes = 1;
63499        pCur->eState = CURSOR_INVALID;
63500        return SQLITE_OK;
63501      }
63502      moveToParent(pCur);
63503      pPage = pCur->apPage[pCur->iPage];
63504    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
63505    if( pPage->intKey ){
63506      return sqlite3BtreeNext(pCur, pRes);
63507    }else{
63508      return SQLITE_OK;
63509    }
63510  }
63511  if( pPage->leaf ){
63512    return SQLITE_OK;
63513  }else{
63514    return moveToLeftmost(pCur);
63515  }
63516}
63517SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
63518  MemPage *pPage;
63519  assert( cursorOwnsBtShared(pCur) );
63520  assert( pRes!=0 );
63521  assert( *pRes==0 || *pRes==1 );
63522  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63523  pCur->info.nSize = 0;
63524  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63525  *pRes = 0;
63526  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
63527  pPage = pCur->apPage[pCur->iPage];
63528  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
63529    pCur->aiIdx[pCur->iPage]--;
63530    return btreeNext(pCur, pRes);
63531  }
63532  if( pPage->leaf ){
63533    return SQLITE_OK;
63534  }else{
63535    return moveToLeftmost(pCur);
63536  }
63537}
63538
63539/*
63540** Step the cursor to the back to the previous entry in the database.  If
63541** successful then set *pRes=0.  If the cursor
63542** was already pointing to the first entry in the database before
63543** this routine was called, then set *pRes=1.
63544**
63545** The main entry point is sqlite3BtreePrevious().  That routine is optimized
63546** for the common case of merely decrementing the cell counter BtCursor.aiIdx
63547** to the previous cell on the current page.  The (slower) btreePrevious()
63548** helper routine is called when it is necessary to move to a different page
63549** or to restore the cursor.
63550**
63551** The calling function will set *pRes to 0 or 1.  The initial *pRes value
63552** will be 1 if the cursor being stepped corresponds to an SQL index and
63553** if this routine could have been skipped if that SQL index had been
63554** a unique index.  Otherwise the caller will have set *pRes to zero.
63555** Zero is the common case. The btree implementation is free to use the
63556** initial *pRes value as a hint to improve performance, but the current
63557** SQLite btree implementation does not. (Note that the comdb2 btree
63558** implementation does use this hint, however.)
63559*/
63560static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
63561  int rc;
63562  MemPage *pPage;
63563
63564  assert( cursorOwnsBtShared(pCur) );
63565  assert( pRes!=0 );
63566  assert( *pRes==0 );
63567  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63568  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
63569  assert( pCur->info.nSize==0 );
63570  if( pCur->eState!=CURSOR_VALID ){
63571    rc = restoreCursorPosition(pCur);
63572    if( rc!=SQLITE_OK ){
63573      return rc;
63574    }
63575    if( CURSOR_INVALID==pCur->eState ){
63576      *pRes = 1;
63577      return SQLITE_OK;
63578    }
63579    if( pCur->skipNext ){
63580      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63581      pCur->eState = CURSOR_VALID;
63582      if( pCur->skipNext<0 ){
63583        pCur->skipNext = 0;
63584        return SQLITE_OK;
63585      }
63586      pCur->skipNext = 0;
63587    }
63588  }
63589
63590  pPage = pCur->apPage[pCur->iPage];
63591  assert( pPage->isInit );
63592  if( !pPage->leaf ){
63593    int idx = pCur->aiIdx[pCur->iPage];
63594    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
63595    if( rc ) return rc;
63596    rc = moveToRightmost(pCur);
63597  }else{
63598    while( pCur->aiIdx[pCur->iPage]==0 ){
63599      if( pCur->iPage==0 ){
63600        pCur->eState = CURSOR_INVALID;
63601        *pRes = 1;
63602        return SQLITE_OK;
63603      }
63604      moveToParent(pCur);
63605    }
63606    assert( pCur->info.nSize==0 );
63607    assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
63608
63609    pCur->aiIdx[pCur->iPage]--;
63610    pPage = pCur->apPage[pCur->iPage];
63611    if( pPage->intKey && !pPage->leaf ){
63612      rc = sqlite3BtreePrevious(pCur, pRes);
63613    }else{
63614      rc = SQLITE_OK;
63615    }
63616  }
63617  return rc;
63618}
63619SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
63620  assert( cursorOwnsBtShared(pCur) );
63621  assert( pRes!=0 );
63622  assert( *pRes==0 || *pRes==1 );
63623  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63624  *pRes = 0;
63625  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
63626  pCur->info.nSize = 0;
63627  if( pCur->eState!=CURSOR_VALID
63628   || pCur->aiIdx[pCur->iPage]==0
63629   || pCur->apPage[pCur->iPage]->leaf==0
63630  ){
63631    return btreePrevious(pCur, pRes);
63632  }
63633  pCur->aiIdx[pCur->iPage]--;
63634  return SQLITE_OK;
63635}
63636
63637/*
63638** Allocate a new page from the database file.
63639**
63640** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
63641** has already been called on the new page.)  The new page has also
63642** been referenced and the calling routine is responsible for calling
63643** sqlite3PagerUnref() on the new page when it is done.
63644**
63645** SQLITE_OK is returned on success.  Any other return value indicates
63646** an error.  *ppPage is set to NULL in the event of an error.
63647**
63648** If the "nearby" parameter is not 0, then an effort is made to
63649** locate a page close to the page number "nearby".  This can be used in an
63650** attempt to keep related pages close to each other in the database file,
63651** which in turn can make database access faster.
63652**
63653** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
63654** anywhere on the free-list, then it is guaranteed to be returned.  If
63655** eMode is BTALLOC_LT then the page returned will be less than or equal
63656** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
63657** are no restrictions on which page is returned.
63658*/
63659static int allocateBtreePage(
63660  BtShared *pBt,         /* The btree */
63661  MemPage **ppPage,      /* Store pointer to the allocated page here */
63662  Pgno *pPgno,           /* Store the page number here */
63663  Pgno nearby,           /* Search for a page near this one */
63664  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
63665){
63666  MemPage *pPage1;
63667  int rc;
63668  u32 n;     /* Number of pages on the freelist */
63669  u32 k;     /* Number of leaves on the trunk of the freelist */
63670  MemPage *pTrunk = 0;
63671  MemPage *pPrevTrunk = 0;
63672  Pgno mxPage;     /* Total size of the database file */
63673
63674  assert( sqlite3_mutex_held(pBt->mutex) );
63675  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
63676  pPage1 = pBt->pPage1;
63677  mxPage = btreePagecount(pBt);
63678  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
63679  ** stores stores the total number of pages on the freelist. */
63680  n = get4byte(&pPage1->aData[36]);
63681  testcase( n==mxPage-1 );
63682  if( n>=mxPage ){
63683    return SQLITE_CORRUPT_BKPT;
63684  }
63685  if( n>0 ){
63686    /* There are pages on the freelist.  Reuse one of those pages. */
63687    Pgno iTrunk;
63688    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
63689    u32 nSearch = 0;   /* Count of the number of search attempts */
63690
63691    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
63692    ** shows that the page 'nearby' is somewhere on the free-list, then
63693    ** the entire-list will be searched for that page.
63694    */
63695#ifndef SQLITE_OMIT_AUTOVACUUM
63696    if( eMode==BTALLOC_EXACT ){
63697      if( nearby<=mxPage ){
63698        u8 eType;
63699        assert( nearby>0 );
63700        assert( pBt->autoVacuum );
63701        rc = ptrmapGet(pBt, nearby, &eType, 0);
63702        if( rc ) return rc;
63703        if( eType==PTRMAP_FREEPAGE ){
63704          searchList = 1;
63705        }
63706      }
63707    }else if( eMode==BTALLOC_LE ){
63708      searchList = 1;
63709    }
63710#endif
63711
63712    /* Decrement the free-list count by 1. Set iTrunk to the index of the
63713    ** first free-list trunk page. iPrevTrunk is initially 1.
63714    */
63715    rc = sqlite3PagerWrite(pPage1->pDbPage);
63716    if( rc ) return rc;
63717    put4byte(&pPage1->aData[36], n-1);
63718
63719    /* The code within this loop is run only once if the 'searchList' variable
63720    ** is not true. Otherwise, it runs once for each trunk-page on the
63721    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
63722    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
63723    */
63724    do {
63725      pPrevTrunk = pTrunk;
63726      if( pPrevTrunk ){
63727        /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
63728        ** is the page number of the next freelist trunk page in the list or
63729        ** zero if this is the last freelist trunk page. */
63730        iTrunk = get4byte(&pPrevTrunk->aData[0]);
63731      }else{
63732        /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
63733        ** stores the page number of the first page of the freelist, or zero if
63734        ** the freelist is empty. */
63735        iTrunk = get4byte(&pPage1->aData[32]);
63736      }
63737      testcase( iTrunk==mxPage );
63738      if( iTrunk>mxPage || nSearch++ > n ){
63739        rc = SQLITE_CORRUPT_BKPT;
63740      }else{
63741        rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
63742      }
63743      if( rc ){
63744        pTrunk = 0;
63745        goto end_allocate_page;
63746      }
63747      assert( pTrunk!=0 );
63748      assert( pTrunk->aData!=0 );
63749      /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
63750      ** is the number of leaf page pointers to follow. */
63751      k = get4byte(&pTrunk->aData[4]);
63752      if( k==0 && !searchList ){
63753        /* The trunk has no leaves and the list is not being searched.
63754        ** So extract the trunk page itself and use it as the newly
63755        ** allocated page */
63756        assert( pPrevTrunk==0 );
63757        rc = sqlite3PagerWrite(pTrunk->pDbPage);
63758        if( rc ){
63759          goto end_allocate_page;
63760        }
63761        *pPgno = iTrunk;
63762        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63763        *ppPage = pTrunk;
63764        pTrunk = 0;
63765        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63766      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
63767        /* Value of k is out of range.  Database corruption */
63768        rc = SQLITE_CORRUPT_BKPT;
63769        goto end_allocate_page;
63770#ifndef SQLITE_OMIT_AUTOVACUUM
63771      }else if( searchList
63772            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
63773      ){
63774        /* The list is being searched and this trunk page is the page
63775        ** to allocate, regardless of whether it has leaves.
63776        */
63777        *pPgno = iTrunk;
63778        *ppPage = pTrunk;
63779        searchList = 0;
63780        rc = sqlite3PagerWrite(pTrunk->pDbPage);
63781        if( rc ){
63782          goto end_allocate_page;
63783        }
63784        if( k==0 ){
63785          if( !pPrevTrunk ){
63786            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63787          }else{
63788            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63789            if( rc!=SQLITE_OK ){
63790              goto end_allocate_page;
63791            }
63792            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
63793          }
63794        }else{
63795          /* The trunk page is required by the caller but it contains
63796          ** pointers to free-list leaves. The first leaf becomes a trunk
63797          ** page in this case.
63798          */
63799          MemPage *pNewTrunk;
63800          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
63801          if( iNewTrunk>mxPage ){
63802            rc = SQLITE_CORRUPT_BKPT;
63803            goto end_allocate_page;
63804          }
63805          testcase( iNewTrunk==mxPage );
63806          rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
63807          if( rc!=SQLITE_OK ){
63808            goto end_allocate_page;
63809          }
63810          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
63811          if( rc!=SQLITE_OK ){
63812            releasePage(pNewTrunk);
63813            goto end_allocate_page;
63814          }
63815          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
63816          put4byte(&pNewTrunk->aData[4], k-1);
63817          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
63818          releasePage(pNewTrunk);
63819          if( !pPrevTrunk ){
63820            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
63821            put4byte(&pPage1->aData[32], iNewTrunk);
63822          }else{
63823            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63824            if( rc ){
63825              goto end_allocate_page;
63826            }
63827            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
63828          }
63829        }
63830        pTrunk = 0;
63831        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63832#endif
63833      }else if( k>0 ){
63834        /* Extract a leaf from the trunk */
63835        u32 closest;
63836        Pgno iPage;
63837        unsigned char *aData = pTrunk->aData;
63838        if( nearby>0 ){
63839          u32 i;
63840          closest = 0;
63841          if( eMode==BTALLOC_LE ){
63842            for(i=0; i<k; i++){
63843              iPage = get4byte(&aData[8+i*4]);
63844              if( iPage<=nearby ){
63845                closest = i;
63846                break;
63847              }
63848            }
63849          }else{
63850            int dist;
63851            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
63852            for(i=1; i<k; i++){
63853              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
63854              if( d2<dist ){
63855                closest = i;
63856                dist = d2;
63857              }
63858            }
63859          }
63860        }else{
63861          closest = 0;
63862        }
63863
63864        iPage = get4byte(&aData[8+closest*4]);
63865        testcase( iPage==mxPage );
63866        if( iPage>mxPage ){
63867          rc = SQLITE_CORRUPT_BKPT;
63868          goto end_allocate_page;
63869        }
63870        testcase( iPage==mxPage );
63871        if( !searchList
63872         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
63873        ){
63874          int noContent;
63875          *pPgno = iPage;
63876          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
63877                 ": %d more free pages\n",
63878                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
63879          rc = sqlite3PagerWrite(pTrunk->pDbPage);
63880          if( rc ) goto end_allocate_page;
63881          if( closest<k-1 ){
63882            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
63883          }
63884          put4byte(&aData[4], k-1);
63885          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
63886          rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
63887          if( rc==SQLITE_OK ){
63888            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63889            if( rc!=SQLITE_OK ){
63890              releasePage(*ppPage);
63891              *ppPage = 0;
63892            }
63893          }
63894          searchList = 0;
63895        }
63896      }
63897      releasePage(pPrevTrunk);
63898      pPrevTrunk = 0;
63899    }while( searchList );
63900  }else{
63901    /* There are no pages on the freelist, so append a new page to the
63902    ** database image.
63903    **
63904    ** Normally, new pages allocated by this block can be requested from the
63905    ** pager layer with the 'no-content' flag set. This prevents the pager
63906    ** from trying to read the pages content from disk. However, if the
63907    ** current transaction has already run one or more incremental-vacuum
63908    ** steps, then the page we are about to allocate may contain content
63909    ** that is required in the event of a rollback. In this case, do
63910    ** not set the no-content flag. This causes the pager to load and journal
63911    ** the current page content before overwriting it.
63912    **
63913    ** Note that the pager will not actually attempt to load or journal
63914    ** content for any page that really does lie past the end of the database
63915    ** file on disk. So the effects of disabling the no-content optimization
63916    ** here are confined to those pages that lie between the end of the
63917    ** database image and the end of the database file.
63918    */
63919    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
63920
63921    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63922    if( rc ) return rc;
63923    pBt->nPage++;
63924    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
63925
63926#ifndef SQLITE_OMIT_AUTOVACUUM
63927    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
63928      /* If *pPgno refers to a pointer-map page, allocate two new pages
63929      ** at the end of the file instead of one. The first allocated page
63930      ** becomes a new pointer-map page, the second is used by the caller.
63931      */
63932      MemPage *pPg = 0;
63933      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
63934      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
63935      rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
63936      if( rc==SQLITE_OK ){
63937        rc = sqlite3PagerWrite(pPg->pDbPage);
63938        releasePage(pPg);
63939      }
63940      if( rc ) return rc;
63941      pBt->nPage++;
63942      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
63943    }
63944#endif
63945    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
63946    *pPgno = pBt->nPage;
63947
63948    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63949    rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
63950    if( rc ) return rc;
63951    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63952    if( rc!=SQLITE_OK ){
63953      releasePage(*ppPage);
63954      *ppPage = 0;
63955    }
63956    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
63957  }
63958
63959  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63960
63961end_allocate_page:
63962  releasePage(pTrunk);
63963  releasePage(pPrevTrunk);
63964  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
63965  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
63966  return rc;
63967}
63968
63969/*
63970** This function is used to add page iPage to the database file free-list.
63971** It is assumed that the page is not already a part of the free-list.
63972**
63973** The value passed as the second argument to this function is optional.
63974** If the caller happens to have a pointer to the MemPage object
63975** corresponding to page iPage handy, it may pass it as the second value.
63976** Otherwise, it may pass NULL.
63977**
63978** If a pointer to a MemPage object is passed as the second argument,
63979** its reference count is not altered by this function.
63980*/
63981static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
63982  MemPage *pTrunk = 0;                /* Free-list trunk page */
63983  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
63984  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
63985  MemPage *pPage;                     /* Page being freed. May be NULL. */
63986  int rc;                             /* Return Code */
63987  int nFree;                          /* Initial number of pages on free-list */
63988
63989  assert( sqlite3_mutex_held(pBt->mutex) );
63990  assert( CORRUPT_DB || iPage>1 );
63991  assert( !pMemPage || pMemPage->pgno==iPage );
63992
63993  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
63994  if( pMemPage ){
63995    pPage = pMemPage;
63996    sqlite3PagerRef(pPage->pDbPage);
63997  }else{
63998    pPage = btreePageLookup(pBt, iPage);
63999  }
64000
64001  /* Increment the free page count on pPage1 */
64002  rc = sqlite3PagerWrite(pPage1->pDbPage);
64003  if( rc ) goto freepage_out;
64004  nFree = get4byte(&pPage1->aData[36]);
64005  put4byte(&pPage1->aData[36], nFree+1);
64006
64007  if( pBt->btsFlags & BTS_SECURE_DELETE ){
64008    /* If the secure_delete option is enabled, then
64009    ** always fully overwrite deleted information with zeros.
64010    */
64011    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
64012     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
64013    ){
64014      goto freepage_out;
64015    }
64016    memset(pPage->aData, 0, pPage->pBt->pageSize);
64017  }
64018
64019  /* If the database supports auto-vacuum, write an entry in the pointer-map
64020  ** to indicate that the page is free.
64021  */
64022  if( ISAUTOVACUUM ){
64023    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
64024    if( rc ) goto freepage_out;
64025  }
64026
64027  /* Now manipulate the actual database free-list structure. There are two
64028  ** possibilities. If the free-list is currently empty, or if the first
64029  ** trunk page in the free-list is full, then this page will become a
64030  ** new free-list trunk page. Otherwise, it will become a leaf of the
64031  ** first trunk page in the current free-list. This block tests if it
64032  ** is possible to add the page as a new free-list leaf.
64033  */
64034  if( nFree!=0 ){
64035    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
64036
64037    iTrunk = get4byte(&pPage1->aData[32]);
64038    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
64039    if( rc!=SQLITE_OK ){
64040      goto freepage_out;
64041    }
64042
64043    nLeaf = get4byte(&pTrunk->aData[4]);
64044    assert( pBt->usableSize>32 );
64045    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
64046      rc = SQLITE_CORRUPT_BKPT;
64047      goto freepage_out;
64048    }
64049    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
64050      /* In this case there is room on the trunk page to insert the page
64051      ** being freed as a new leaf.
64052      **
64053      ** Note that the trunk page is not really full until it contains
64054      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
64055      ** coded.  But due to a coding error in versions of SQLite prior to
64056      ** 3.6.0, databases with freelist trunk pages holding more than
64057      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
64058      ** to maintain backwards compatibility with older versions of SQLite,
64059      ** we will continue to restrict the number of entries to usableSize/4 - 8
64060      ** for now.  At some point in the future (once everyone has upgraded
64061      ** to 3.6.0 or later) we should consider fixing the conditional above
64062      ** to read "usableSize/4-2" instead of "usableSize/4-8".
64063      **
64064      ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
64065      ** avoid using the last six entries in the freelist trunk page array in
64066      ** order that database files created by newer versions of SQLite can be
64067      ** read by older versions of SQLite.
64068      */
64069      rc = sqlite3PagerWrite(pTrunk->pDbPage);
64070      if( rc==SQLITE_OK ){
64071        put4byte(&pTrunk->aData[4], nLeaf+1);
64072        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
64073        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
64074          sqlite3PagerDontWrite(pPage->pDbPage);
64075        }
64076        rc = btreeSetHasContent(pBt, iPage);
64077      }
64078      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
64079      goto freepage_out;
64080    }
64081  }
64082
64083  /* If control flows to this point, then it was not possible to add the
64084  ** the page being freed as a leaf page of the first trunk in the free-list.
64085  ** Possibly because the free-list is empty, or possibly because the
64086  ** first trunk in the free-list is full. Either way, the page being freed
64087  ** will become the new first trunk page in the free-list.
64088  */
64089  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
64090    goto freepage_out;
64091  }
64092  rc = sqlite3PagerWrite(pPage->pDbPage);
64093  if( rc!=SQLITE_OK ){
64094    goto freepage_out;
64095  }
64096  put4byte(pPage->aData, iTrunk);
64097  put4byte(&pPage->aData[4], 0);
64098  put4byte(&pPage1->aData[32], iPage);
64099  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
64100
64101freepage_out:
64102  if( pPage ){
64103    pPage->isInit = 0;
64104  }
64105  releasePage(pPage);
64106  releasePage(pTrunk);
64107  return rc;
64108}
64109static void freePage(MemPage *pPage, int *pRC){
64110  if( (*pRC)==SQLITE_OK ){
64111    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
64112  }
64113}
64114
64115/*
64116** Free any overflow pages associated with the given Cell.  Write the
64117** local Cell size (the number of bytes on the original page, omitting
64118** overflow) into *pnSize.
64119*/
64120static int clearCell(
64121  MemPage *pPage,          /* The page that contains the Cell */
64122  unsigned char *pCell,    /* First byte of the Cell */
64123  u16 *pnSize              /* Write the size of the Cell here */
64124){
64125  BtShared *pBt = pPage->pBt;
64126  CellInfo info;
64127  Pgno ovflPgno;
64128  int rc;
64129  int nOvfl;
64130  u32 ovflPageSize;
64131
64132  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64133  pPage->xParseCell(pPage, pCell, &info);
64134  *pnSize = info.nSize;
64135  if( info.nLocal==info.nPayload ){
64136    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
64137  }
64138  if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
64139    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
64140  }
64141  ovflPgno = get4byte(pCell + info.nSize - 4);
64142  assert( pBt->usableSize > 4 );
64143  ovflPageSize = pBt->usableSize - 4;
64144  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
64145  assert( nOvfl>0 ||
64146    (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
64147  );
64148  while( nOvfl-- ){
64149    Pgno iNext = 0;
64150    MemPage *pOvfl = 0;
64151    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
64152      /* 0 is not a legal page number and page 1 cannot be an
64153      ** overflow page. Therefore if ovflPgno<2 or past the end of the
64154      ** file the database must be corrupt. */
64155      return SQLITE_CORRUPT_BKPT;
64156    }
64157    if( nOvfl ){
64158      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
64159      if( rc ) return rc;
64160    }
64161
64162    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
64163     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
64164    ){
64165      /* There is no reason any cursor should have an outstanding reference
64166      ** to an overflow page belonging to a cell that is being deleted/updated.
64167      ** So if there exists more than one reference to this page, then it
64168      ** must not really be an overflow page and the database must be corrupt.
64169      ** It is helpful to detect this before calling freePage2(), as
64170      ** freePage2() may zero the page contents if secure-delete mode is
64171      ** enabled. If this 'overflow' page happens to be a page that the
64172      ** caller is iterating through or using in some other way, this
64173      ** can be problematic.
64174      */
64175      rc = SQLITE_CORRUPT_BKPT;
64176    }else{
64177      rc = freePage2(pBt, pOvfl, ovflPgno);
64178    }
64179
64180    if( pOvfl ){
64181      sqlite3PagerUnref(pOvfl->pDbPage);
64182    }
64183    if( rc ) return rc;
64184    ovflPgno = iNext;
64185  }
64186  return SQLITE_OK;
64187}
64188
64189/*
64190** Create the byte sequence used to represent a cell on page pPage
64191** and write that byte sequence into pCell[].  Overflow pages are
64192** allocated and filled in as necessary.  The calling procedure
64193** is responsible for making sure sufficient space has been allocated
64194** for pCell[].
64195**
64196** Note that pCell does not necessary need to point to the pPage->aData
64197** area.  pCell might point to some temporary storage.  The cell will
64198** be constructed in this temporary area then copied into pPage->aData
64199** later.
64200*/
64201static int fillInCell(
64202  MemPage *pPage,                /* The page that contains the cell */
64203  unsigned char *pCell,          /* Complete text of the cell */
64204  const BtreePayload *pX,        /* Payload with which to construct the cell */
64205  int *pnSize                    /* Write cell size here */
64206){
64207  int nPayload;
64208  const u8 *pSrc;
64209  int nSrc, n, rc;
64210  int spaceLeft;
64211  MemPage *pOvfl = 0;
64212  MemPage *pToRelease = 0;
64213  unsigned char *pPrior;
64214  unsigned char *pPayload;
64215  BtShared *pBt = pPage->pBt;
64216  Pgno pgnoOvfl = 0;
64217  int nHeader;
64218
64219  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64220
64221  /* pPage is not necessarily writeable since pCell might be auxiliary
64222  ** buffer space that is separate from the pPage buffer area */
64223  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
64224            || sqlite3PagerIswriteable(pPage->pDbPage) );
64225
64226  /* Fill in the header. */
64227  nHeader = pPage->childPtrSize;
64228  if( pPage->intKey ){
64229    nPayload = pX->nData + pX->nZero;
64230    pSrc = pX->pData;
64231    nSrc = pX->nData;
64232    assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
64233    nHeader += putVarint32(&pCell[nHeader], nPayload);
64234    nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
64235  }else{
64236    assert( pX->nData==0 );
64237    assert( pX->nZero==0 );
64238    assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
64239    nSrc = nPayload = (int)pX->nKey;
64240    pSrc = pX->pKey;
64241    nHeader += putVarint32(&pCell[nHeader], nPayload);
64242  }
64243
64244  /* Fill in the payload */
64245  if( nPayload<=pPage->maxLocal ){
64246    n = nHeader + nPayload;
64247    testcase( n==3 );
64248    testcase( n==4 );
64249    if( n<4 ) n = 4;
64250    *pnSize = n;
64251    spaceLeft = nPayload;
64252    pPrior = pCell;
64253  }else{
64254    int mn = pPage->minLocal;
64255    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
64256    testcase( n==pPage->maxLocal );
64257    testcase( n==pPage->maxLocal+1 );
64258    if( n > pPage->maxLocal ) n = mn;
64259    spaceLeft = n;
64260    *pnSize = n + nHeader + 4;
64261    pPrior = &pCell[nHeader+n];
64262  }
64263  pPayload = &pCell[nHeader];
64264
64265  /* At this point variables should be set as follows:
64266  **
64267  **   nPayload           Total payload size in bytes
64268  **   pPayload           Begin writing payload here
64269  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
64270  **                      that means content must spill into overflow pages.
64271  **   *pnSize            Size of the local cell (not counting overflow pages)
64272  **   pPrior             Where to write the pgno of the first overflow page
64273  **
64274  ** Use a call to btreeParseCellPtr() to verify that the values above
64275  ** were computed correctly.
64276  */
64277#if SQLITE_DEBUG
64278  {
64279    CellInfo info;
64280    pPage->xParseCell(pPage, pCell, &info);
64281    assert( nHeader==(int)(info.pPayload - pCell) );
64282    assert( info.nKey==pX->nKey );
64283    assert( *pnSize == info.nSize );
64284    assert( spaceLeft == info.nLocal );
64285  }
64286#endif
64287
64288  /* Write the payload into the local Cell and any extra into overflow pages */
64289  while( nPayload>0 ){
64290    if( spaceLeft==0 ){
64291#ifndef SQLITE_OMIT_AUTOVACUUM
64292      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
64293      if( pBt->autoVacuum ){
64294        do{
64295          pgnoOvfl++;
64296        } while(
64297          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
64298        );
64299      }
64300#endif
64301      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
64302#ifndef SQLITE_OMIT_AUTOVACUUM
64303      /* If the database supports auto-vacuum, and the second or subsequent
64304      ** overflow page is being allocated, add an entry to the pointer-map
64305      ** for that page now.
64306      **
64307      ** If this is the first overflow page, then write a partial entry
64308      ** to the pointer-map. If we write nothing to this pointer-map slot,
64309      ** then the optimistic overflow chain processing in clearCell()
64310      ** may misinterpret the uninitialized values and delete the
64311      ** wrong pages from the database.
64312      */
64313      if( pBt->autoVacuum && rc==SQLITE_OK ){
64314        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
64315        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
64316        if( rc ){
64317          releasePage(pOvfl);
64318        }
64319      }
64320#endif
64321      if( rc ){
64322        releasePage(pToRelease);
64323        return rc;
64324      }
64325
64326      /* If pToRelease is not zero than pPrior points into the data area
64327      ** of pToRelease.  Make sure pToRelease is still writeable. */
64328      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64329
64330      /* If pPrior is part of the data area of pPage, then make sure pPage
64331      ** is still writeable */
64332      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
64333            || sqlite3PagerIswriteable(pPage->pDbPage) );
64334
64335      put4byte(pPrior, pgnoOvfl);
64336      releasePage(pToRelease);
64337      pToRelease = pOvfl;
64338      pPrior = pOvfl->aData;
64339      put4byte(pPrior, 0);
64340      pPayload = &pOvfl->aData[4];
64341      spaceLeft = pBt->usableSize - 4;
64342    }
64343    n = nPayload;
64344    if( n>spaceLeft ) n = spaceLeft;
64345
64346    /* If pToRelease is not zero than pPayload points into the data area
64347    ** of pToRelease.  Make sure pToRelease is still writeable. */
64348    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64349
64350    /* If pPayload is part of the data area of pPage, then make sure pPage
64351    ** is still writeable */
64352    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
64353            || sqlite3PagerIswriteable(pPage->pDbPage) );
64354
64355    if( nSrc>0 ){
64356      if( n>nSrc ) n = nSrc;
64357      assert( pSrc );
64358      memcpy(pPayload, pSrc, n);
64359    }else{
64360      memset(pPayload, 0, n);
64361    }
64362    nPayload -= n;
64363    pPayload += n;
64364    pSrc += n;
64365    nSrc -= n;
64366    spaceLeft -= n;
64367  }
64368  releasePage(pToRelease);
64369  return SQLITE_OK;
64370}
64371
64372/*
64373** Remove the i-th cell from pPage.  This routine effects pPage only.
64374** The cell content is not freed or deallocated.  It is assumed that
64375** the cell content has been copied someplace else.  This routine just
64376** removes the reference to the cell from pPage.
64377**
64378** "sz" must be the number of bytes in the cell.
64379*/
64380static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
64381  u32 pc;         /* Offset to cell content of cell being deleted */
64382  u8 *data;       /* pPage->aData */
64383  u8 *ptr;        /* Used to move bytes around within data[] */
64384  int rc;         /* The return code */
64385  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
64386
64387  if( *pRC ) return;
64388
64389  assert( idx>=0 && idx<pPage->nCell );
64390  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
64391  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64392  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64393  data = pPage->aData;
64394  ptr = &pPage->aCellIdx[2*idx];
64395  pc = get2byte(ptr);
64396  hdr = pPage->hdrOffset;
64397  testcase( pc==get2byte(&data[hdr+5]) );
64398  testcase( pc+sz==pPage->pBt->usableSize );
64399  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
64400    *pRC = SQLITE_CORRUPT_BKPT;
64401    return;
64402  }
64403  rc = freeSpace(pPage, pc, sz);
64404  if( rc ){
64405    *pRC = rc;
64406    return;
64407  }
64408  pPage->nCell--;
64409  if( pPage->nCell==0 ){
64410    memset(&data[hdr+1], 0, 4);
64411    data[hdr+7] = 0;
64412    put2byte(&data[hdr+5], pPage->pBt->usableSize);
64413    pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
64414                       - pPage->childPtrSize - 8;
64415  }else{
64416    memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
64417    put2byte(&data[hdr+3], pPage->nCell);
64418    pPage->nFree += 2;
64419  }
64420}
64421
64422/*
64423** Insert a new cell on pPage at cell index "i".  pCell points to the
64424** content of the cell.
64425**
64426** If the cell content will fit on the page, then put it there.  If it
64427** will not fit, then make a copy of the cell content into pTemp if
64428** pTemp is not null.  Regardless of pTemp, allocate a new entry
64429** in pPage->apOvfl[] and make it point to the cell content (either
64430** in pTemp or the original pCell) and also record its index.
64431** Allocating a new entry in pPage->aCell[] implies that
64432** pPage->nOverflow is incremented.
64433**
64434** *pRC must be SQLITE_OK when this routine is called.
64435*/
64436static void insertCell(
64437  MemPage *pPage,   /* Page into which we are copying */
64438  int i,            /* New cell becomes the i-th cell of the page */
64439  u8 *pCell,        /* Content of the new cell */
64440  int sz,           /* Bytes of content in pCell */
64441  u8 *pTemp,        /* Temp storage space for pCell, if needed */
64442  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
64443  int *pRC          /* Read and write return code from here */
64444){
64445  int idx = 0;      /* Where to write new cell content in data[] */
64446  int j;            /* Loop counter */
64447  u8 *data;         /* The content of the whole page */
64448  u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
64449
64450  assert( *pRC==SQLITE_OK );
64451  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
64452  assert( MX_CELL(pPage->pBt)<=10921 );
64453  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
64454  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
64455  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
64456  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64457  /* The cell should normally be sized correctly.  However, when moving a
64458  ** malformed cell from a leaf page to an interior page, if the cell size
64459  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
64460  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
64461  ** the term after the || in the following assert(). */
64462  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
64463  if( pPage->nOverflow || sz+2>pPage->nFree ){
64464    if( pTemp ){
64465      memcpy(pTemp, pCell, sz);
64466      pCell = pTemp;
64467    }
64468    if( iChild ){
64469      put4byte(pCell, iChild);
64470    }
64471    j = pPage->nOverflow++;
64472    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
64473    pPage->apOvfl[j] = pCell;
64474    pPage->aiOvfl[j] = (u16)i;
64475
64476    /* When multiple overflows occur, they are always sequential and in
64477    ** sorted order.  This invariants arise because multiple overflows can
64478    ** only occur when inserting divider cells into the parent page during
64479    ** balancing, and the dividers are adjacent and sorted.
64480    */
64481    assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
64482    assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
64483  }else{
64484    int rc = sqlite3PagerWrite(pPage->pDbPage);
64485    if( rc!=SQLITE_OK ){
64486      *pRC = rc;
64487      return;
64488    }
64489    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64490    data = pPage->aData;
64491    assert( &data[pPage->cellOffset]==pPage->aCellIdx );
64492    rc = allocateSpace(pPage, sz, &idx);
64493    if( rc ){ *pRC = rc; return; }
64494    /* The allocateSpace() routine guarantees the following properties
64495    ** if it returns successfully */
64496    assert( idx >= 0 );
64497    assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
64498    assert( idx+sz <= (int)pPage->pBt->usableSize );
64499    pPage->nFree -= (u16)(2 + sz);
64500    memcpy(&data[idx], pCell, sz);
64501    if( iChild ){
64502      put4byte(&data[idx], iChild);
64503    }
64504    pIns = pPage->aCellIdx + i*2;
64505    memmove(pIns+2, pIns, 2*(pPage->nCell - i));
64506    put2byte(pIns, idx);
64507    pPage->nCell++;
64508    /* increment the cell count */
64509    if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
64510    assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
64511#ifndef SQLITE_OMIT_AUTOVACUUM
64512    if( pPage->pBt->autoVacuum ){
64513      /* The cell may contain a pointer to an overflow page. If so, write
64514      ** the entry for the overflow page into the pointer map.
64515      */
64516      ptrmapPutOvflPtr(pPage, pCell, pRC);
64517    }
64518#endif
64519  }
64520}
64521
64522/*
64523** A CellArray object contains a cache of pointers and sizes for a
64524** consecutive sequence of cells that might be held on multiple pages.
64525*/
64526typedef struct CellArray CellArray;
64527struct CellArray {
64528  int nCell;              /* Number of cells in apCell[] */
64529  MemPage *pRef;          /* Reference page */
64530  u8 **apCell;            /* All cells begin balanced */
64531  u16 *szCell;            /* Local size of all cells in apCell[] */
64532};
64533
64534/*
64535** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
64536** computed.
64537*/
64538static void populateCellCache(CellArray *p, int idx, int N){
64539  assert( idx>=0 && idx+N<=p->nCell );
64540  while( N>0 ){
64541    assert( p->apCell[idx]!=0 );
64542    if( p->szCell[idx]==0 ){
64543      p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
64544    }else{
64545      assert( CORRUPT_DB ||
64546              p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
64547    }
64548    idx++;
64549    N--;
64550  }
64551}
64552
64553/*
64554** Return the size of the Nth element of the cell array
64555*/
64556static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
64557  assert( N>=0 && N<p->nCell );
64558  assert( p->szCell[N]==0 );
64559  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
64560  return p->szCell[N];
64561}
64562static u16 cachedCellSize(CellArray *p, int N){
64563  assert( N>=0 && N<p->nCell );
64564  if( p->szCell[N] ) return p->szCell[N];
64565  return computeCellSize(p, N);
64566}
64567
64568/*
64569** Array apCell[] contains pointers to nCell b-tree page cells. The
64570** szCell[] array contains the size in bytes of each cell. This function
64571** replaces the current contents of page pPg with the contents of the cell
64572** array.
64573**
64574** Some of the cells in apCell[] may currently be stored in pPg. This
64575** function works around problems caused by this by making a copy of any
64576** such cells before overwriting the page data.
64577**
64578** The MemPage.nFree field is invalidated by this function. It is the
64579** responsibility of the caller to set it correctly.
64580*/
64581static int rebuildPage(
64582  MemPage *pPg,                   /* Edit this page */
64583  int nCell,                      /* Final number of cells on page */
64584  u8 **apCell,                    /* Array of cells */
64585  u16 *szCell                     /* Array of cell sizes */
64586){
64587  const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
64588  u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
64589  const int usableSize = pPg->pBt->usableSize;
64590  u8 * const pEnd = &aData[usableSize];
64591  int i;
64592  u8 *pCellptr = pPg->aCellIdx;
64593  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64594  u8 *pData;
64595
64596  i = get2byte(&aData[hdr+5]);
64597  memcpy(&pTmp[i], &aData[i], usableSize - i);
64598
64599  pData = pEnd;
64600  for(i=0; i<nCell; i++){
64601    u8 *pCell = apCell[i];
64602    if( SQLITE_WITHIN(pCell,aData,pEnd) ){
64603      pCell = &pTmp[pCell - aData];
64604    }
64605    pData -= szCell[i];
64606    put2byte(pCellptr, (pData - aData));
64607    pCellptr += 2;
64608    if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
64609    memcpy(pData, pCell, szCell[i]);
64610    assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
64611    testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
64612  }
64613
64614  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
64615  pPg->nCell = nCell;
64616  pPg->nOverflow = 0;
64617
64618  put2byte(&aData[hdr+1], 0);
64619  put2byte(&aData[hdr+3], pPg->nCell);
64620  put2byte(&aData[hdr+5], pData - aData);
64621  aData[hdr+7] = 0x00;
64622  return SQLITE_OK;
64623}
64624
64625/*
64626** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64627** contains the size in bytes of each such cell. This function attempts to
64628** add the cells stored in the array to page pPg. If it cannot (because
64629** the page needs to be defragmented before the cells will fit), non-zero
64630** is returned. Otherwise, if the cells are added successfully, zero is
64631** returned.
64632**
64633** Argument pCellptr points to the first entry in the cell-pointer array
64634** (part of page pPg) to populate. After cell apCell[0] is written to the
64635** page body, a 16-bit offset is written to pCellptr. And so on, for each
64636** cell in the array. It is the responsibility of the caller to ensure
64637** that it is safe to overwrite this part of the cell-pointer array.
64638**
64639** When this function is called, *ppData points to the start of the
64640** content area on page pPg. If the size of the content area is extended,
64641** *ppData is updated to point to the new start of the content area
64642** before returning.
64643**
64644** Finally, argument pBegin points to the byte immediately following the
64645** end of the space required by this page for the cell-pointer area (for
64646** all cells - not just those inserted by the current call). If the content
64647** area must be extended to before this point in order to accomodate all
64648** cells in apCell[], then the cells do not fit and non-zero is returned.
64649*/
64650static int pageInsertArray(
64651  MemPage *pPg,                   /* Page to add cells to */
64652  u8 *pBegin,                     /* End of cell-pointer array */
64653  u8 **ppData,                    /* IN/OUT: Page content -area pointer */
64654  u8 *pCellptr,                   /* Pointer to cell-pointer area */
64655  int iFirst,                     /* Index of first cell to add */
64656  int nCell,                      /* Number of cells to add to pPg */
64657  CellArray *pCArray              /* Array of cells */
64658){
64659  int i;
64660  u8 *aData = pPg->aData;
64661  u8 *pData = *ppData;
64662  int iEnd = iFirst + nCell;
64663  assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
64664  for(i=iFirst; i<iEnd; i++){
64665    int sz, rc;
64666    u8 *pSlot;
64667    sz = cachedCellSize(pCArray, i);
64668    if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64669      if( (pData - pBegin)<sz ) return 1;
64670      pData -= sz;
64671      pSlot = pData;
64672    }
64673    /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64674    ** database.  But they might for a corrupt database.  Hence use memmove()
64675    ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
64676    assert( (pSlot+sz)<=pCArray->apCell[i]
64677         || pSlot>=(pCArray->apCell[i]+sz)
64678         || CORRUPT_DB );
64679    memmove(pSlot, pCArray->apCell[i], sz);
64680    put2byte(pCellptr, (pSlot - aData));
64681    pCellptr += 2;
64682  }
64683  *ppData = pData;
64684  return 0;
64685}
64686
64687/*
64688** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64689** contains the size in bytes of each such cell. This function adds the
64690** space associated with each cell in the array that is currently stored
64691** within the body of pPg to the pPg free-list. The cell-pointers and other
64692** fields of the page are not updated.
64693**
64694** This function returns the total number of cells added to the free-list.
64695*/
64696static int pageFreeArray(
64697  MemPage *pPg,                   /* Page to edit */
64698  int iFirst,                     /* First cell to delete */
64699  int nCell,                      /* Cells to delete */
64700  CellArray *pCArray              /* Array of cells */
64701){
64702  u8 * const aData = pPg->aData;
64703  u8 * const pEnd = &aData[pPg->pBt->usableSize];
64704  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
64705  int nRet = 0;
64706  int i;
64707  int iEnd = iFirst + nCell;
64708  u8 *pFree = 0;
64709  int szFree = 0;
64710
64711  for(i=iFirst; i<iEnd; i++){
64712    u8 *pCell = pCArray->apCell[i];
64713    if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
64714      int sz;
64715      /* No need to use cachedCellSize() here.  The sizes of all cells that
64716      ** are to be freed have already been computing while deciding which
64717      ** cells need freeing */
64718      sz = pCArray->szCell[i];  assert( sz>0 );
64719      if( pFree!=(pCell + sz) ){
64720        if( pFree ){
64721          assert( pFree>aData && (pFree - aData)<65536 );
64722          freeSpace(pPg, (u16)(pFree - aData), szFree);
64723        }
64724        pFree = pCell;
64725        szFree = sz;
64726        if( pFree+sz>pEnd ) return 0;
64727      }else{
64728        pFree = pCell;
64729        szFree += sz;
64730      }
64731      nRet++;
64732    }
64733  }
64734  if( pFree ){
64735    assert( pFree>aData && (pFree - aData)<65536 );
64736    freeSpace(pPg, (u16)(pFree - aData), szFree);
64737  }
64738  return nRet;
64739}
64740
64741/*
64742** apCell[] and szCell[] contains pointers to and sizes of all cells in the
64743** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
64744** with apCell[iOld].  After balancing, this page should hold nNew cells
64745** starting at apCell[iNew].
64746**
64747** This routine makes the necessary adjustments to pPg so that it contains
64748** the correct cells after being balanced.
64749**
64750** The pPg->nFree field is invalid when this function returns. It is the
64751** responsibility of the caller to set it correctly.
64752*/
64753static int editPage(
64754  MemPage *pPg,                   /* Edit this page */
64755  int iOld,                       /* Index of first cell currently on page */
64756  int iNew,                       /* Index of new first cell on page */
64757  int nNew,                       /* Final number of cells on page */
64758  CellArray *pCArray              /* Array of cells and sizes */
64759){
64760  u8 * const aData = pPg->aData;
64761  const int hdr = pPg->hdrOffset;
64762  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
64763  int nCell = pPg->nCell;       /* Cells stored on pPg */
64764  u8 *pData;
64765  u8 *pCellptr;
64766  int i;
64767  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
64768  int iNewEnd = iNew + nNew;
64769
64770#ifdef SQLITE_DEBUG
64771  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64772  memcpy(pTmp, aData, pPg->pBt->usableSize);
64773#endif
64774
64775  /* Remove cells from the start and end of the page */
64776  if( iOld<iNew ){
64777    int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
64778    memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
64779    nCell -= nShift;
64780  }
64781  if( iNewEnd < iOldEnd ){
64782    nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
64783  }
64784
64785  pData = &aData[get2byteNotZero(&aData[hdr+5])];
64786  if( pData<pBegin ) goto editpage_fail;
64787
64788  /* Add cells to the start of the page */
64789  if( iNew<iOld ){
64790    int nAdd = MIN(nNew,iOld-iNew);
64791    assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
64792    pCellptr = pPg->aCellIdx;
64793    memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
64794    if( pageInsertArray(
64795          pPg, pBegin, &pData, pCellptr,
64796          iNew, nAdd, pCArray
64797    ) ) goto editpage_fail;
64798    nCell += nAdd;
64799  }
64800
64801  /* Add any overflow cells */
64802  for(i=0; i<pPg->nOverflow; i++){
64803    int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
64804    if( iCell>=0 && iCell<nNew ){
64805      pCellptr = &pPg->aCellIdx[iCell * 2];
64806      memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
64807      nCell++;
64808      if( pageInsertArray(
64809            pPg, pBegin, &pData, pCellptr,
64810            iCell+iNew, 1, pCArray
64811      ) ) goto editpage_fail;
64812    }
64813  }
64814
64815  /* Append cells to the end of the page */
64816  pCellptr = &pPg->aCellIdx[nCell*2];
64817  if( pageInsertArray(
64818        pPg, pBegin, &pData, pCellptr,
64819        iNew+nCell, nNew-nCell, pCArray
64820  ) ) goto editpage_fail;
64821
64822  pPg->nCell = nNew;
64823  pPg->nOverflow = 0;
64824
64825  put2byte(&aData[hdr+3], pPg->nCell);
64826  put2byte(&aData[hdr+5], pData - aData);
64827
64828#ifdef SQLITE_DEBUG
64829  for(i=0; i<nNew && !CORRUPT_DB; i++){
64830    u8 *pCell = pCArray->apCell[i+iNew];
64831    int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64832    if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64833      pCell = &pTmp[pCell - aData];
64834    }
64835    assert( 0==memcmp(pCell, &aData[iOff],
64836            pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64837  }
64838#endif
64839
64840  return SQLITE_OK;
64841 editpage_fail:
64842  /* Unable to edit this page. Rebuild it from scratch instead. */
64843  populateCellCache(pCArray, iNew, nNew);
64844  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
64845}
64846
64847/*
64848** The following parameters determine how many adjacent pages get involved
64849** in a balancing operation.  NN is the number of neighbors on either side
64850** of the page that participate in the balancing operation.  NB is the
64851** total number of pages that participate, including the target page and
64852** NN neighbors on either side.
64853**
64854** The minimum value of NN is 1 (of course).  Increasing NN above 1
64855** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
64856** in exchange for a larger degradation in INSERT and UPDATE performance.
64857** The value of NN appears to give the best results overall.
64858*/
64859#define NN 1             /* Number of neighbors on either side of pPage */
64860#define NB (NN*2+1)      /* Total pages involved in the balance */
64861
64862
64863#ifndef SQLITE_OMIT_QUICKBALANCE
64864/*
64865** This version of balance() handles the common special case where
64866** a new entry is being inserted on the extreme right-end of the
64867** tree, in other words, when the new entry will become the largest
64868** entry in the tree.
64869**
64870** Instead of trying to balance the 3 right-most leaf pages, just add
64871** a new page to the right-hand side and put the one new entry in
64872** that page.  This leaves the right side of the tree somewhat
64873** unbalanced.  But odds are that we will be inserting new entries
64874** at the end soon afterwards so the nearly empty page will quickly
64875** fill up.  On average.
64876**
64877** pPage is the leaf page which is the right-most page in the tree.
64878** pParent is its parent.  pPage must have a single overflow entry
64879** which is also the right-most entry on the page.
64880**
64881** The pSpace buffer is used to store a temporary copy of the divider
64882** cell that will be inserted into pParent. Such a cell consists of a 4
64883** byte page number followed by a variable length integer. In other
64884** words, at most 13 bytes. Hence the pSpace buffer must be at
64885** least 13 bytes in size.
64886*/
64887static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
64888  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
64889  MemPage *pNew;                       /* Newly allocated page */
64890  int rc;                              /* Return Code */
64891  Pgno pgnoNew;                        /* Page number of pNew */
64892
64893  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64894  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
64895  assert( pPage->nOverflow==1 );
64896
64897  /* This error condition is now caught prior to reaching this function */
64898  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
64899
64900  /* Allocate a new page. This page will become the right-sibling of
64901  ** pPage. Make the parent page writable, so that the new divider cell
64902  ** may be inserted. If both these operations are successful, proceed.
64903  */
64904  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
64905
64906  if( rc==SQLITE_OK ){
64907
64908    u8 *pOut = &pSpace[4];
64909    u8 *pCell = pPage->apOvfl[0];
64910    u16 szCell = pPage->xCellSize(pPage, pCell);
64911    u8 *pStop;
64912
64913    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
64914    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
64915    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
64916    rc = rebuildPage(pNew, 1, &pCell, &szCell);
64917    if( NEVER(rc) ) return rc;
64918    pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
64919
64920    /* If this is an auto-vacuum database, update the pointer map
64921    ** with entries for the new page, and any pointer from the
64922    ** cell on the page to an overflow page. If either of these
64923    ** operations fails, the return code is set, but the contents
64924    ** of the parent page are still manipulated by thh code below.
64925    ** That is Ok, at this point the parent page is guaranteed to
64926    ** be marked as dirty. Returning an error code will cause a
64927    ** rollback, undoing any changes made to the parent page.
64928    */
64929    if( ISAUTOVACUUM ){
64930      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
64931      if( szCell>pNew->minLocal ){
64932        ptrmapPutOvflPtr(pNew, pCell, &rc);
64933      }
64934    }
64935
64936    /* Create a divider cell to insert into pParent. The divider cell
64937    ** consists of a 4-byte page number (the page number of pPage) and
64938    ** a variable length key value (which must be the same value as the
64939    ** largest key on pPage).
64940    **
64941    ** To find the largest key value on pPage, first find the right-most
64942    ** cell on pPage. The first two fields of this cell are the
64943    ** record-length (a variable length integer at most 32-bits in size)
64944    ** and the key value (a variable length integer, may have any value).
64945    ** The first of the while(...) loops below skips over the record-length
64946    ** field. The second while(...) loop copies the key value from the
64947    ** cell on pPage into the pSpace buffer.
64948    */
64949    pCell = findCell(pPage, pPage->nCell-1);
64950    pStop = &pCell[9];
64951    while( (*(pCell++)&0x80) && pCell<pStop );
64952    pStop = &pCell[9];
64953    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
64954
64955    /* Insert the new divider cell into pParent. */
64956    if( rc==SQLITE_OK ){
64957      insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
64958                   0, pPage->pgno, &rc);
64959    }
64960
64961    /* Set the right-child pointer of pParent to point to the new page. */
64962    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
64963
64964    /* Release the reference to the new page. */
64965    releasePage(pNew);
64966  }
64967
64968  return rc;
64969}
64970#endif /* SQLITE_OMIT_QUICKBALANCE */
64971
64972#if 0
64973/*
64974** This function does not contribute anything to the operation of SQLite.
64975** it is sometimes activated temporarily while debugging code responsible
64976** for setting pointer-map entries.
64977*/
64978static int ptrmapCheckPages(MemPage **apPage, int nPage){
64979  int i, j;
64980  for(i=0; i<nPage; i++){
64981    Pgno n;
64982    u8 e;
64983    MemPage *pPage = apPage[i];
64984    BtShared *pBt = pPage->pBt;
64985    assert( pPage->isInit );
64986
64987    for(j=0; j<pPage->nCell; j++){
64988      CellInfo info;
64989      u8 *z;
64990
64991      z = findCell(pPage, j);
64992      pPage->xParseCell(pPage, z, &info);
64993      if( info.nLocal<info.nPayload ){
64994        Pgno ovfl = get4byte(&z[info.nSize-4]);
64995        ptrmapGet(pBt, ovfl, &e, &n);
64996        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
64997      }
64998      if( !pPage->leaf ){
64999        Pgno child = get4byte(z);
65000        ptrmapGet(pBt, child, &e, &n);
65001        assert( n==pPage->pgno && e==PTRMAP_BTREE );
65002      }
65003    }
65004    if( !pPage->leaf ){
65005      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
65006      ptrmapGet(pBt, child, &e, &n);
65007      assert( n==pPage->pgno && e==PTRMAP_BTREE );
65008    }
65009  }
65010  return 1;
65011}
65012#endif
65013
65014/*
65015** This function is used to copy the contents of the b-tree node stored
65016** on page pFrom to page pTo. If page pFrom was not a leaf page, then
65017** the pointer-map entries for each child page are updated so that the
65018** parent page stored in the pointer map is page pTo. If pFrom contained
65019** any cells with overflow page pointers, then the corresponding pointer
65020** map entries are also updated so that the parent page is page pTo.
65021**
65022** If pFrom is currently carrying any overflow cells (entries in the
65023** MemPage.apOvfl[] array), they are not copied to pTo.
65024**
65025** Before returning, page pTo is reinitialized using btreeInitPage().
65026**
65027** The performance of this function is not critical. It is only used by
65028** the balance_shallower() and balance_deeper() procedures, neither of
65029** which are called often under normal circumstances.
65030*/
65031static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
65032  if( (*pRC)==SQLITE_OK ){
65033    BtShared * const pBt = pFrom->pBt;
65034    u8 * const aFrom = pFrom->aData;
65035    u8 * const aTo = pTo->aData;
65036    int const iFromHdr = pFrom->hdrOffset;
65037    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
65038    int rc;
65039    int iData;
65040
65041
65042    assert( pFrom->isInit );
65043    assert( pFrom->nFree>=iToHdr );
65044    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
65045
65046    /* Copy the b-tree node content from page pFrom to page pTo. */
65047    iData = get2byte(&aFrom[iFromHdr+5]);
65048    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
65049    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
65050
65051    /* Reinitialize page pTo so that the contents of the MemPage structure
65052    ** match the new data. The initialization of pTo can actually fail under
65053    ** fairly obscure circumstances, even though it is a copy of initialized
65054    ** page pFrom.
65055    */
65056    pTo->isInit = 0;
65057    rc = btreeInitPage(pTo);
65058    if( rc!=SQLITE_OK ){
65059      *pRC = rc;
65060      return;
65061    }
65062
65063    /* If this is an auto-vacuum database, update the pointer-map entries
65064    ** for any b-tree or overflow pages that pTo now contains the pointers to.
65065    */
65066    if( ISAUTOVACUUM ){
65067      *pRC = setChildPtrmaps(pTo);
65068    }
65069  }
65070}
65071
65072/*
65073** This routine redistributes cells on the iParentIdx'th child of pParent
65074** (hereafter "the page") and up to 2 siblings so that all pages have about the
65075** same amount of free space. Usually a single sibling on either side of the
65076** page are used in the balancing, though both siblings might come from one
65077** side if the page is the first or last child of its parent. If the page
65078** has fewer than 2 siblings (something which can only happen if the page
65079** is a root page or a child of a root page) then all available siblings
65080** participate in the balancing.
65081**
65082** The number of siblings of the page might be increased or decreased by
65083** one or two in an effort to keep pages nearly full but not over full.
65084**
65085** Note that when this routine is called, some of the cells on the page
65086** might not actually be stored in MemPage.aData[]. This can happen
65087** if the page is overfull. This routine ensures that all cells allocated
65088** to the page and its siblings fit into MemPage.aData[] before returning.
65089**
65090** In the course of balancing the page and its siblings, cells may be
65091** inserted into or removed from the parent page (pParent). Doing so
65092** may cause the parent page to become overfull or underfull. If this
65093** happens, it is the responsibility of the caller to invoke the correct
65094** balancing routine to fix this problem (see the balance() routine).
65095**
65096** If this routine fails for any reason, it might leave the database
65097** in a corrupted state. So if this routine fails, the database should
65098** be rolled back.
65099**
65100** The third argument to this function, aOvflSpace, is a pointer to a
65101** buffer big enough to hold one page. If while inserting cells into the parent
65102** page (pParent) the parent page becomes overfull, this buffer is
65103** used to store the parent's overflow cells. Because this function inserts
65104** a maximum of four divider cells into the parent page, and the maximum
65105** size of a cell stored within an internal node is always less than 1/4
65106** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
65107** enough for all overflow cells.
65108**
65109** If aOvflSpace is set to a null pointer, this function returns
65110** SQLITE_NOMEM.
65111*/
65112static int balance_nonroot(
65113  MemPage *pParent,               /* Parent page of siblings being balanced */
65114  int iParentIdx,                 /* Index of "the page" in pParent */
65115  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
65116  int isRoot,                     /* True if pParent is a root-page */
65117  int bBulk                       /* True if this call is part of a bulk load */
65118){
65119  BtShared *pBt;               /* The whole database */
65120  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
65121  int nNew = 0;                /* Number of pages in apNew[] */
65122  int nOld;                    /* Number of pages in apOld[] */
65123  int i, j, k;                 /* Loop counters */
65124  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
65125  int rc = SQLITE_OK;          /* The return code */
65126  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
65127  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
65128  int usableSpace;             /* Bytes in pPage beyond the header */
65129  int pageFlags;               /* Value of pPage->aData[0] */
65130  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
65131  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
65132  int szScratch;               /* Size of scratch memory requested */
65133  MemPage *apOld[NB];          /* pPage and up to two siblings */
65134  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
65135  u8 *pRight;                  /* Location in parent of right-sibling pointer */
65136  u8 *apDiv[NB-1];             /* Divider cells in pParent */
65137  int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
65138  int cntOld[NB+2];            /* Old index in b.apCell[] */
65139  int szNew[NB+2];             /* Combined size of cells placed on i-th page */
65140  u8 *aSpace1;                 /* Space for copies of dividers cells */
65141  Pgno pgno;                   /* Temp var to store a page number in */
65142  u8 abDone[NB+2];             /* True after i'th new page is populated */
65143  Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
65144  Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
65145  u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
65146  CellArray b;                  /* Parsed information on cells being balanced */
65147
65148  memset(abDone, 0, sizeof(abDone));
65149  b.nCell = 0;
65150  b.apCell = 0;
65151  pBt = pParent->pBt;
65152  assert( sqlite3_mutex_held(pBt->mutex) );
65153  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65154
65155#if 0
65156  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
65157#endif
65158
65159  /* At this point pParent may have at most one overflow cell. And if
65160  ** this overflow cell is present, it must be the cell with
65161  ** index iParentIdx. This scenario comes about when this function
65162  ** is called (indirectly) from sqlite3BtreeDelete().
65163  */
65164  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
65165  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
65166
65167  if( !aOvflSpace ){
65168    return SQLITE_NOMEM_BKPT;
65169  }
65170
65171  /* Find the sibling pages to balance. Also locate the cells in pParent
65172  ** that divide the siblings. An attempt is made to find NN siblings on
65173  ** either side of pPage. More siblings are taken from one side, however,
65174  ** if there are fewer than NN siblings on the other side. If pParent
65175  ** has NB or fewer children then all children of pParent are taken.
65176  **
65177  ** This loop also drops the divider cells from the parent page. This
65178  ** way, the remainder of the function does not have to deal with any
65179  ** overflow cells in the parent page, since if any existed they will
65180  ** have already been removed.
65181  */
65182  i = pParent->nOverflow + pParent->nCell;
65183  if( i<2 ){
65184    nxDiv = 0;
65185  }else{
65186    assert( bBulk==0 || bBulk==1 );
65187    if( iParentIdx==0 ){
65188      nxDiv = 0;
65189    }else if( iParentIdx==i ){
65190      nxDiv = i-2+bBulk;
65191    }else{
65192      nxDiv = iParentIdx-1;
65193    }
65194    i = 2-bBulk;
65195  }
65196  nOld = i+1;
65197  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
65198    pRight = &pParent->aData[pParent->hdrOffset+8];
65199  }else{
65200    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
65201  }
65202  pgno = get4byte(pRight);
65203  while( 1 ){
65204    rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
65205    if( rc ){
65206      memset(apOld, 0, (i+1)*sizeof(MemPage*));
65207      goto balance_cleanup;
65208    }
65209    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
65210    if( (i--)==0 ) break;
65211
65212    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
65213      apDiv[i] = pParent->apOvfl[0];
65214      pgno = get4byte(apDiv[i]);
65215      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65216      pParent->nOverflow = 0;
65217    }else{
65218      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
65219      pgno = get4byte(apDiv[i]);
65220      szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65221
65222      /* Drop the cell from the parent page. apDiv[i] still points to
65223      ** the cell within the parent, even though it has been dropped.
65224      ** This is safe because dropping a cell only overwrites the first
65225      ** four bytes of it, and this function does not need the first
65226      ** four bytes of the divider cell. So the pointer is safe to use
65227      ** later on.
65228      **
65229      ** But not if we are in secure-delete mode. In secure-delete mode,
65230      ** the dropCell() routine will overwrite the entire cell with zeroes.
65231      ** In this case, temporarily copy the cell into the aOvflSpace[]
65232      ** buffer. It will be copied out again as soon as the aSpace[] buffer
65233      ** is allocated.  */
65234      if( pBt->btsFlags & BTS_SECURE_DELETE ){
65235        int iOff;
65236
65237        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
65238        if( (iOff+szNew[i])>(int)pBt->usableSize ){
65239          rc = SQLITE_CORRUPT_BKPT;
65240          memset(apOld, 0, (i+1)*sizeof(MemPage*));
65241          goto balance_cleanup;
65242        }else{
65243          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
65244          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
65245        }
65246      }
65247      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
65248    }
65249  }
65250
65251  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
65252  ** alignment */
65253  nMaxCells = (nMaxCells + 3)&~3;
65254
65255  /*
65256  ** Allocate space for memory structures
65257  */
65258  szScratch =
65259       nMaxCells*sizeof(u8*)                       /* b.apCell */
65260     + nMaxCells*sizeof(u16)                       /* b.szCell */
65261     + pBt->pageSize;                              /* aSpace1 */
65262
65263  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
65264  ** that is more than 6 times the database page size. */
65265  assert( szScratch<=6*(int)pBt->pageSize );
65266  b.apCell = sqlite3ScratchMalloc( szScratch );
65267  if( b.apCell==0 ){
65268    rc = SQLITE_NOMEM_BKPT;
65269    goto balance_cleanup;
65270  }
65271  b.szCell = (u16*)&b.apCell[nMaxCells];
65272  aSpace1 = (u8*)&b.szCell[nMaxCells];
65273  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
65274
65275  /*
65276  ** Load pointers to all cells on sibling pages and the divider cells
65277  ** into the local b.apCell[] array.  Make copies of the divider cells
65278  ** into space obtained from aSpace1[]. The divider cells have already
65279  ** been removed from pParent.
65280  **
65281  ** If the siblings are on leaf pages, then the child pointers of the
65282  ** divider cells are stripped from the cells before they are copied
65283  ** into aSpace1[].  In this way, all cells in b.apCell[] are without
65284  ** child pointers.  If siblings are not leaves, then all cell in
65285  ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
65286  ** are alike.
65287  **
65288  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
65289  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
65290  */
65291  b.pRef = apOld[0];
65292  leafCorrection = b.pRef->leaf*4;
65293  leafData = b.pRef->intKeyLeaf;
65294  for(i=0; i<nOld; i++){
65295    MemPage *pOld = apOld[i];
65296    int limit = pOld->nCell;
65297    u8 *aData = pOld->aData;
65298    u16 maskPage = pOld->maskPage;
65299    u8 *piCell = aData + pOld->cellOffset;
65300    u8 *piEnd;
65301
65302    /* Verify that all sibling pages are of the same "type" (table-leaf,
65303    ** table-interior, index-leaf, or index-interior).
65304    */
65305    if( pOld->aData[0]!=apOld[0]->aData[0] ){
65306      rc = SQLITE_CORRUPT_BKPT;
65307      goto balance_cleanup;
65308    }
65309
65310    /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
65311    ** constains overflow cells, include them in the b.apCell[] array
65312    ** in the correct spot.
65313    **
65314    ** Note that when there are multiple overflow cells, it is always the
65315    ** case that they are sequential and adjacent.  This invariant arises
65316    ** because multiple overflows can only occurs when inserting divider
65317    ** cells into a parent on a prior balance, and divider cells are always
65318    ** adjacent and are inserted in order.  There is an assert() tagged
65319    ** with "NOTE 1" in the overflow cell insertion loop to prove this
65320    ** invariant.
65321    **
65322    ** This must be done in advance.  Once the balance starts, the cell
65323    ** offset section of the btree page will be overwritten and we will no
65324    ** long be able to find the cells if a pointer to each cell is not saved
65325    ** first.
65326    */
65327    memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
65328    if( pOld->nOverflow>0 ){
65329      limit = pOld->aiOvfl[0];
65330      for(j=0; j<limit; j++){
65331        b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65332        piCell += 2;
65333        b.nCell++;
65334      }
65335      for(k=0; k<pOld->nOverflow; k++){
65336        assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
65337        b.apCell[b.nCell] = pOld->apOvfl[k];
65338        b.nCell++;
65339      }
65340    }
65341    piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
65342    while( piCell<piEnd ){
65343      assert( b.nCell<nMaxCells );
65344      b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65345      piCell += 2;
65346      b.nCell++;
65347    }
65348
65349    cntOld[i] = b.nCell;
65350    if( i<nOld-1 && !leafData){
65351      u16 sz = (u16)szNew[i];
65352      u8 *pTemp;
65353      assert( b.nCell<nMaxCells );
65354      b.szCell[b.nCell] = sz;
65355      pTemp = &aSpace1[iSpace1];
65356      iSpace1 += sz;
65357      assert( sz<=pBt->maxLocal+23 );
65358      assert( iSpace1 <= (int)pBt->pageSize );
65359      memcpy(pTemp, apDiv[i], sz);
65360      b.apCell[b.nCell] = pTemp+leafCorrection;
65361      assert( leafCorrection==0 || leafCorrection==4 );
65362      b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
65363      if( !pOld->leaf ){
65364        assert( leafCorrection==0 );
65365        assert( pOld->hdrOffset==0 );
65366        /* The right pointer of the child page pOld becomes the left
65367        ** pointer of the divider cell */
65368        memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
65369      }else{
65370        assert( leafCorrection==4 );
65371        while( b.szCell[b.nCell]<4 ){
65372          /* Do not allow any cells smaller than 4 bytes. If a smaller cell
65373          ** does exist, pad it with 0x00 bytes. */
65374          assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
65375          assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
65376          aSpace1[iSpace1++] = 0x00;
65377          b.szCell[b.nCell]++;
65378        }
65379      }
65380      b.nCell++;
65381    }
65382  }
65383
65384  /*
65385  ** Figure out the number of pages needed to hold all b.nCell cells.
65386  ** Store this number in "k".  Also compute szNew[] which is the total
65387  ** size of all cells on the i-th page and cntNew[] which is the index
65388  ** in b.apCell[] of the cell that divides page i from page i+1.
65389  ** cntNew[k] should equal b.nCell.
65390  **
65391  ** Values computed by this block:
65392  **
65393  **           k: The total number of sibling pages
65394  **    szNew[i]: Spaced used on the i-th sibling page.
65395  **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
65396  **              the right of the i-th sibling page.
65397  ** usableSpace: Number of bytes of space available on each sibling.
65398  **
65399  */
65400  usableSpace = pBt->usableSize - 12 + leafCorrection;
65401  for(i=0; i<nOld; i++){
65402    MemPage *p = apOld[i];
65403    szNew[i] = usableSpace - p->nFree;
65404    if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65405    for(j=0; j<p->nOverflow; j++){
65406      szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
65407    }
65408    cntNew[i] = cntOld[i];
65409  }
65410  k = nOld;
65411  for(i=0; i<k; i++){
65412    int sz;
65413    while( szNew[i]>usableSpace ){
65414      if( i+1>=k ){
65415        k = i+2;
65416        if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65417        szNew[k-1] = 0;
65418        cntNew[k-1] = b.nCell;
65419      }
65420      sz = 2 + cachedCellSize(&b, cntNew[i]-1);
65421      szNew[i] -= sz;
65422      if( !leafData ){
65423        if( cntNew[i]<b.nCell ){
65424          sz = 2 + cachedCellSize(&b, cntNew[i]);
65425        }else{
65426          sz = 0;
65427        }
65428      }
65429      szNew[i+1] += sz;
65430      cntNew[i]--;
65431    }
65432    while( cntNew[i]<b.nCell ){
65433      sz = 2 + cachedCellSize(&b, cntNew[i]);
65434      if( szNew[i]+sz>usableSpace ) break;
65435      szNew[i] += sz;
65436      cntNew[i]++;
65437      if( !leafData ){
65438        if( cntNew[i]<b.nCell ){
65439          sz = 2 + cachedCellSize(&b, cntNew[i]);
65440        }else{
65441          sz = 0;
65442        }
65443      }
65444      szNew[i+1] -= sz;
65445    }
65446    if( cntNew[i]>=b.nCell ){
65447      k = i+1;
65448    }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
65449      rc = SQLITE_CORRUPT_BKPT;
65450      goto balance_cleanup;
65451    }
65452  }
65453
65454  /*
65455  ** The packing computed by the previous block is biased toward the siblings
65456  ** on the left side (siblings with smaller keys). The left siblings are
65457  ** always nearly full, while the right-most sibling might be nearly empty.
65458  ** The next block of code attempts to adjust the packing of siblings to
65459  ** get a better balance.
65460  **
65461  ** This adjustment is more than an optimization.  The packing above might
65462  ** be so out of balance as to be illegal.  For example, the right-most
65463  ** sibling might be completely empty.  This adjustment is not optional.
65464  */
65465  for(i=k-1; i>0; i--){
65466    int szRight = szNew[i];  /* Size of sibling on the right */
65467    int szLeft = szNew[i-1]; /* Size of sibling on the left */
65468    int r;              /* Index of right-most cell in left sibling */
65469    int d;              /* Index of first cell to the left of right sibling */
65470
65471    r = cntNew[i-1] - 1;
65472    d = r + 1 - leafData;
65473    (void)cachedCellSize(&b, d);
65474    do{
65475      assert( d<nMaxCells );
65476      assert( r<nMaxCells );
65477      (void)cachedCellSize(&b, r);
65478      if( szRight!=0
65479       && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
65480        break;
65481      }
65482      szRight += b.szCell[d] + 2;
65483      szLeft -= b.szCell[r] + 2;
65484      cntNew[i-1] = r;
65485      r--;
65486      d--;
65487    }while( r>=0 );
65488    szNew[i] = szRight;
65489    szNew[i-1] = szLeft;
65490    if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
65491      rc = SQLITE_CORRUPT_BKPT;
65492      goto balance_cleanup;
65493    }
65494  }
65495
65496  /* Sanity check:  For a non-corrupt database file one of the follwing
65497  ** must be true:
65498  **    (1) We found one or more cells (cntNew[0])>0), or
65499  **    (2) pPage is a virtual root page.  A virtual root page is when
65500  **        the real root page is page 1 and we are the only child of
65501  **        that page.
65502  */
65503  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
65504  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
65505    apOld[0]->pgno, apOld[0]->nCell,
65506    nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
65507    nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
65508  ));
65509
65510  /*
65511  ** Allocate k new pages.  Reuse old pages where possible.
65512  */
65513  pageFlags = apOld[0]->aData[0];
65514  for(i=0; i<k; i++){
65515    MemPage *pNew;
65516    if( i<nOld ){
65517      pNew = apNew[i] = apOld[i];
65518      apOld[i] = 0;
65519      rc = sqlite3PagerWrite(pNew->pDbPage);
65520      nNew++;
65521      if( rc ) goto balance_cleanup;
65522    }else{
65523      assert( i>0 );
65524      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
65525      if( rc ) goto balance_cleanup;
65526      zeroPage(pNew, pageFlags);
65527      apNew[i] = pNew;
65528      nNew++;
65529      cntOld[i] = b.nCell;
65530
65531      /* Set the pointer-map entry for the new sibling page. */
65532      if( ISAUTOVACUUM ){
65533        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
65534        if( rc!=SQLITE_OK ){
65535          goto balance_cleanup;
65536        }
65537      }
65538    }
65539  }
65540
65541  /*
65542  ** Reassign page numbers so that the new pages are in ascending order.
65543  ** This helps to keep entries in the disk file in order so that a scan
65544  ** of the table is closer to a linear scan through the file. That in turn
65545  ** helps the operating system to deliver pages from the disk more rapidly.
65546  **
65547  ** An O(n^2) insertion sort algorithm is used, but since n is never more
65548  ** than (NB+2) (a small constant), that should not be a problem.
65549  **
65550  ** When NB==3, this one optimization makes the database about 25% faster
65551  ** for large insertions and deletions.
65552  */
65553  for(i=0; i<nNew; i++){
65554    aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
65555    aPgFlags[i] = apNew[i]->pDbPage->flags;
65556    for(j=0; j<i; j++){
65557      if( aPgno[j]==aPgno[i] ){
65558        /* This branch is taken if the set of sibling pages somehow contains
65559        ** duplicate entries. This can happen if the database is corrupt.
65560        ** It would be simpler to detect this as part of the loop below, but
65561        ** we do the detection here in order to avoid populating the pager
65562        ** cache with two separate objects associated with the same
65563        ** page number.  */
65564        assert( CORRUPT_DB );
65565        rc = SQLITE_CORRUPT_BKPT;
65566        goto balance_cleanup;
65567      }
65568    }
65569  }
65570  for(i=0; i<nNew; i++){
65571    int iBest = 0;                /* aPgno[] index of page number to use */
65572    for(j=1; j<nNew; j++){
65573      if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
65574    }
65575    pgno = aPgOrder[iBest];
65576    aPgOrder[iBest] = 0xffffffff;
65577    if( iBest!=i ){
65578      if( iBest>i ){
65579        sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
65580      }
65581      sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
65582      apNew[i]->pgno = pgno;
65583    }
65584  }
65585
65586  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
65587         "%d(%d nc=%d) %d(%d nc=%d)\n",
65588    apNew[0]->pgno, szNew[0], cntNew[0],
65589    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
65590    nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
65591    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
65592    nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
65593    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
65594    nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
65595    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
65596    nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
65597  ));
65598
65599  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65600  put4byte(pRight, apNew[nNew-1]->pgno);
65601
65602  /* If the sibling pages are not leaves, ensure that the right-child pointer
65603  ** of the right-most new sibling page is set to the value that was
65604  ** originally in the same field of the right-most old sibling page. */
65605  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
65606    MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
65607    memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
65608  }
65609
65610  /* Make any required updates to pointer map entries associated with
65611  ** cells stored on sibling pages following the balance operation. Pointer
65612  ** map entries associated with divider cells are set by the insertCell()
65613  ** routine. The associated pointer map entries are:
65614  **
65615  **   a) if the cell contains a reference to an overflow chain, the
65616  **      entry associated with the first page in the overflow chain, and
65617  **
65618  **   b) if the sibling pages are not leaves, the child page associated
65619  **      with the cell.
65620  **
65621  ** If the sibling pages are not leaves, then the pointer map entry
65622  ** associated with the right-child of each sibling may also need to be
65623  ** updated. This happens below, after the sibling pages have been
65624  ** populated, not here.
65625  */
65626  if( ISAUTOVACUUM ){
65627    MemPage *pNew = apNew[0];
65628    u8 *aOld = pNew->aData;
65629    int cntOldNext = pNew->nCell + pNew->nOverflow;
65630    int usableSize = pBt->usableSize;
65631    int iNew = 0;
65632    int iOld = 0;
65633
65634    for(i=0; i<b.nCell; i++){
65635      u8 *pCell = b.apCell[i];
65636      if( i==cntOldNext ){
65637        MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
65638        cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
65639        aOld = pOld->aData;
65640      }
65641      if( i==cntNew[iNew] ){
65642        pNew = apNew[++iNew];
65643        if( !leafData ) continue;
65644      }
65645
65646      /* Cell pCell is destined for new sibling page pNew. Originally, it
65647      ** was either part of sibling page iOld (possibly an overflow cell),
65648      ** or else the divider cell to the left of sibling page iOld. So,
65649      ** if sibling page iOld had the same page number as pNew, and if
65650      ** pCell really was a part of sibling page iOld (not a divider or
65651      ** overflow cell), we can skip updating the pointer map entries.  */
65652      if( iOld>=nNew
65653       || pNew->pgno!=aPgno[iOld]
65654       || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
65655      ){
65656        if( !leafCorrection ){
65657          ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
65658        }
65659        if( cachedCellSize(&b,i)>pNew->minLocal ){
65660          ptrmapPutOvflPtr(pNew, pCell, &rc);
65661        }
65662        if( rc ) goto balance_cleanup;
65663      }
65664    }
65665  }
65666
65667  /* Insert new divider cells into pParent. */
65668  for(i=0; i<nNew-1; i++){
65669    u8 *pCell;
65670    u8 *pTemp;
65671    int sz;
65672    MemPage *pNew = apNew[i];
65673    j = cntNew[i];
65674
65675    assert( j<nMaxCells );
65676    assert( b.apCell[j]!=0 );
65677    pCell = b.apCell[j];
65678    sz = b.szCell[j] + leafCorrection;
65679    pTemp = &aOvflSpace[iOvflSpace];
65680    if( !pNew->leaf ){
65681      memcpy(&pNew->aData[8], pCell, 4);
65682    }else if( leafData ){
65683      /* If the tree is a leaf-data tree, and the siblings are leaves,
65684      ** then there is no divider cell in b.apCell[]. Instead, the divider
65685      ** cell consists of the integer key for the right-most cell of
65686      ** the sibling-page assembled above only.
65687      */
65688      CellInfo info;
65689      j--;
65690      pNew->xParseCell(pNew, b.apCell[j], &info);
65691      pCell = pTemp;
65692      sz = 4 + putVarint(&pCell[4], info.nKey);
65693      pTemp = 0;
65694    }else{
65695      pCell -= 4;
65696      /* Obscure case for non-leaf-data trees: If the cell at pCell was
65697      ** previously stored on a leaf node, and its reported size was 4
65698      ** bytes, then it may actually be smaller than this
65699      ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
65700      ** any cell). But it is important to pass the correct size to
65701      ** insertCell(), so reparse the cell now.
65702      **
65703      ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
65704      ** and WITHOUT ROWID tables with exactly one column which is the
65705      ** primary key.
65706      */
65707      if( b.szCell[j]==4 ){
65708        assert(leafCorrection==4);
65709        sz = pParent->xCellSize(pParent, pCell);
65710      }
65711    }
65712    iOvflSpace += sz;
65713    assert( sz<=pBt->maxLocal+23 );
65714    assert( iOvflSpace <= (int)pBt->pageSize );
65715    insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
65716    if( rc!=SQLITE_OK ) goto balance_cleanup;
65717    assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65718  }
65719
65720  /* Now update the actual sibling pages. The order in which they are updated
65721  ** is important, as this code needs to avoid disrupting any page from which
65722  ** cells may still to be read. In practice, this means:
65723  **
65724  **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
65725  **      then it is not safe to update page apNew[iPg] until after
65726  **      the left-hand sibling apNew[iPg-1] has been updated.
65727  **
65728  **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
65729  **      then it is not safe to update page apNew[iPg] until after
65730  **      the right-hand sibling apNew[iPg+1] has been updated.
65731  **
65732  ** If neither of the above apply, the page is safe to update.
65733  **
65734  ** The iPg value in the following loop starts at nNew-1 goes down
65735  ** to 0, then back up to nNew-1 again, thus making two passes over
65736  ** the pages.  On the initial downward pass, only condition (1) above
65737  ** needs to be tested because (2) will always be true from the previous
65738  ** step.  On the upward pass, both conditions are always true, so the
65739  ** upwards pass simply processes pages that were missed on the downward
65740  ** pass.
65741  */
65742  for(i=1-nNew; i<nNew; i++){
65743    int iPg = i<0 ? -i : i;
65744    assert( iPg>=0 && iPg<nNew );
65745    if( abDone[iPg] ) continue;         /* Skip pages already processed */
65746    if( i>=0                            /* On the upwards pass, or... */
65747     || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
65748    ){
65749      int iNew;
65750      int iOld;
65751      int nNewCell;
65752
65753      /* Verify condition (1):  If cells are moving left, update iPg
65754      ** only after iPg-1 has already been updated. */
65755      assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
65756
65757      /* Verify condition (2):  If cells are moving right, update iPg
65758      ** only after iPg+1 has already been updated. */
65759      assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
65760
65761      if( iPg==0 ){
65762        iNew = iOld = 0;
65763        nNewCell = cntNew[0];
65764      }else{
65765        iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
65766        iNew = cntNew[iPg-1] + !leafData;
65767        nNewCell = cntNew[iPg] - iNew;
65768      }
65769
65770      rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
65771      if( rc ) goto balance_cleanup;
65772      abDone[iPg]++;
65773      apNew[iPg]->nFree = usableSpace-szNew[iPg];
65774      assert( apNew[iPg]->nOverflow==0 );
65775      assert( apNew[iPg]->nCell==nNewCell );
65776    }
65777  }
65778
65779  /* All pages have been processed exactly once */
65780  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
65781
65782  assert( nOld>0 );
65783  assert( nNew>0 );
65784
65785  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
65786    /* The root page of the b-tree now contains no cells. The only sibling
65787    ** page is the right-child of the parent. Copy the contents of the
65788    ** child page into the parent, decreasing the overall height of the
65789    ** b-tree structure by one. This is described as the "balance-shallower"
65790    ** sub-algorithm in some documentation.
65791    **
65792    ** If this is an auto-vacuum database, the call to copyNodeContent()
65793    ** sets all pointer-map entries corresponding to database image pages
65794    ** for which the pointer is stored within the content being copied.
65795    **
65796    ** It is critical that the child page be defragmented before being
65797    ** copied into the parent, because if the parent is page 1 then it will
65798    ** by smaller than the child due to the database header, and so all the
65799    ** free space needs to be up front.
65800    */
65801    assert( nNew==1 || CORRUPT_DB );
65802    rc = defragmentPage(apNew[0]);
65803    testcase( rc!=SQLITE_OK );
65804    assert( apNew[0]->nFree ==
65805        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
65806      || rc!=SQLITE_OK
65807    );
65808    copyNodeContent(apNew[0], pParent, &rc);
65809    freePage(apNew[0], &rc);
65810  }else if( ISAUTOVACUUM && !leafCorrection ){
65811    /* Fix the pointer map entries associated with the right-child of each
65812    ** sibling page. All other pointer map entries have already been taken
65813    ** care of.  */
65814    for(i=0; i<nNew; i++){
65815      u32 key = get4byte(&apNew[i]->aData[8]);
65816      ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
65817    }
65818  }
65819
65820  assert( pParent->isInit );
65821  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
65822          nOld, nNew, b.nCell));
65823
65824  /* Free any old pages that were not reused as new pages.
65825  */
65826  for(i=nNew; i<nOld; i++){
65827    freePage(apOld[i], &rc);
65828  }
65829
65830#if 0
65831  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
65832    /* The ptrmapCheckPages() contains assert() statements that verify that
65833    ** all pointer map pages are set correctly. This is helpful while
65834    ** debugging. This is usually disabled because a corrupt database may
65835    ** cause an assert() statement to fail.  */
65836    ptrmapCheckPages(apNew, nNew);
65837    ptrmapCheckPages(&pParent, 1);
65838  }
65839#endif
65840
65841  /*
65842  ** Cleanup before returning.
65843  */
65844balance_cleanup:
65845  sqlite3ScratchFree(b.apCell);
65846  for(i=0; i<nOld; i++){
65847    releasePage(apOld[i]);
65848  }
65849  for(i=0; i<nNew; i++){
65850    releasePage(apNew[i]);
65851  }
65852
65853  return rc;
65854}
65855
65856
65857/*
65858** This function is called when the root page of a b-tree structure is
65859** overfull (has one or more overflow pages).
65860**
65861** A new child page is allocated and the contents of the current root
65862** page, including overflow cells, are copied into the child. The root
65863** page is then overwritten to make it an empty page with the right-child
65864** pointer pointing to the new page.
65865**
65866** Before returning, all pointer-map entries corresponding to pages
65867** that the new child-page now contains pointers to are updated. The
65868** entry corresponding to the new right-child pointer of the root
65869** page is also updated.
65870**
65871** If successful, *ppChild is set to contain a reference to the child
65872** page and SQLITE_OK is returned. In this case the caller is required
65873** to call releasePage() on *ppChild exactly once. If an error occurs,
65874** an error code is returned and *ppChild is set to 0.
65875*/
65876static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
65877  int rc;                        /* Return value from subprocedures */
65878  MemPage *pChild = 0;           /* Pointer to a new child page */
65879  Pgno pgnoChild = 0;            /* Page number of the new child page */
65880  BtShared *pBt = pRoot->pBt;    /* The BTree */
65881
65882  assert( pRoot->nOverflow>0 );
65883  assert( sqlite3_mutex_held(pBt->mutex) );
65884
65885  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
65886  ** page that will become the new right-child of pPage. Copy the contents
65887  ** of the node stored on pRoot into the new child page.
65888  */
65889  rc = sqlite3PagerWrite(pRoot->pDbPage);
65890  if( rc==SQLITE_OK ){
65891    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
65892    copyNodeContent(pRoot, pChild, &rc);
65893    if( ISAUTOVACUUM ){
65894      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
65895    }
65896  }
65897  if( rc ){
65898    *ppChild = 0;
65899    releasePage(pChild);
65900    return rc;
65901  }
65902  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
65903  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
65904  assert( pChild->nCell==pRoot->nCell );
65905
65906  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
65907
65908  /* Copy the overflow cells from pRoot to pChild */
65909  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
65910         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
65911  memcpy(pChild->apOvfl, pRoot->apOvfl,
65912         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
65913  pChild->nOverflow = pRoot->nOverflow;
65914
65915  /* Zero the contents of pRoot. Then install pChild as the right-child. */
65916  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
65917  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
65918
65919  *ppChild = pChild;
65920  return SQLITE_OK;
65921}
65922
65923/*
65924** The page that pCur currently points to has just been modified in
65925** some way. This function figures out if this modification means the
65926** tree needs to be balanced, and if so calls the appropriate balancing
65927** routine. Balancing routines are:
65928**
65929**   balance_quick()
65930**   balance_deeper()
65931**   balance_nonroot()
65932*/
65933static int balance(BtCursor *pCur){
65934  int rc = SQLITE_OK;
65935  const int nMin = pCur->pBt->usableSize * 2 / 3;
65936  u8 aBalanceQuickSpace[13];
65937  u8 *pFree = 0;
65938
65939  VVA_ONLY( int balance_quick_called = 0 );
65940  VVA_ONLY( int balance_deeper_called = 0 );
65941
65942  do {
65943    int iPage = pCur->iPage;
65944    MemPage *pPage = pCur->apPage[iPage];
65945
65946    if( iPage==0 ){
65947      if( pPage->nOverflow ){
65948        /* The root page of the b-tree is overfull. In this case call the
65949        ** balance_deeper() function to create a new child for the root-page
65950        ** and copy the current contents of the root-page to it. The
65951        ** next iteration of the do-loop will balance the child page.
65952        */
65953        assert( balance_deeper_called==0 );
65954        VVA_ONLY( balance_deeper_called++ );
65955        rc = balance_deeper(pPage, &pCur->apPage[1]);
65956        if( rc==SQLITE_OK ){
65957          pCur->iPage = 1;
65958          pCur->aiIdx[0] = 0;
65959          pCur->aiIdx[1] = 0;
65960          assert( pCur->apPage[1]->nOverflow );
65961        }
65962      }else{
65963        break;
65964      }
65965    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
65966      break;
65967    }else{
65968      MemPage * const pParent = pCur->apPage[iPage-1];
65969      int const iIdx = pCur->aiIdx[iPage-1];
65970
65971      rc = sqlite3PagerWrite(pParent->pDbPage);
65972      if( rc==SQLITE_OK ){
65973#ifndef SQLITE_OMIT_QUICKBALANCE
65974        if( pPage->intKeyLeaf
65975         && pPage->nOverflow==1
65976         && pPage->aiOvfl[0]==pPage->nCell
65977         && pParent->pgno!=1
65978         && pParent->nCell==iIdx
65979        ){
65980          /* Call balance_quick() to create a new sibling of pPage on which
65981          ** to store the overflow cell. balance_quick() inserts a new cell
65982          ** into pParent, which may cause pParent overflow. If this
65983          ** happens, the next iteration of the do-loop will balance pParent
65984          ** use either balance_nonroot() or balance_deeper(). Until this
65985          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
65986          ** buffer.
65987          **
65988          ** The purpose of the following assert() is to check that only a
65989          ** single call to balance_quick() is made for each call to this
65990          ** function. If this were not verified, a subtle bug involving reuse
65991          ** of the aBalanceQuickSpace[] might sneak in.
65992          */
65993          assert( balance_quick_called==0 );
65994          VVA_ONLY( balance_quick_called++ );
65995          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
65996        }else
65997#endif
65998        {
65999          /* In this case, call balance_nonroot() to redistribute cells
66000          ** between pPage and up to 2 of its sibling pages. This involves
66001          ** modifying the contents of pParent, which may cause pParent to
66002          ** become overfull or underfull. The next iteration of the do-loop
66003          ** will balance the parent page to correct this.
66004          **
66005          ** If the parent page becomes overfull, the overflow cell or cells
66006          ** are stored in the pSpace buffer allocated immediately below.
66007          ** A subsequent iteration of the do-loop will deal with this by
66008          ** calling balance_nonroot() (balance_deeper() may be called first,
66009          ** but it doesn't deal with overflow cells - just moves them to a
66010          ** different page). Once this subsequent call to balance_nonroot()
66011          ** has completed, it is safe to release the pSpace buffer used by
66012          ** the previous call, as the overflow cell data will have been
66013          ** copied either into the body of a database page or into the new
66014          ** pSpace buffer passed to the latter call to balance_nonroot().
66015          */
66016          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
66017          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
66018                               pCur->hints&BTREE_BULKLOAD);
66019          if( pFree ){
66020            /* If pFree is not NULL, it points to the pSpace buffer used
66021            ** by a previous call to balance_nonroot(). Its contents are
66022            ** now stored either on real database pages or within the
66023            ** new pSpace buffer, so it may be safely freed here. */
66024            sqlite3PageFree(pFree);
66025          }
66026
66027          /* The pSpace buffer will be freed after the next call to
66028          ** balance_nonroot(), or just before this function returns, whichever
66029          ** comes first. */
66030          pFree = pSpace;
66031        }
66032      }
66033
66034      pPage->nOverflow = 0;
66035
66036      /* The next iteration of the do-loop balances the parent page. */
66037      releasePage(pPage);
66038      pCur->iPage--;
66039      assert( pCur->iPage>=0 );
66040    }
66041  }while( rc==SQLITE_OK );
66042
66043  if( pFree ){
66044    sqlite3PageFree(pFree);
66045  }
66046  return rc;
66047}
66048
66049
66050/*
66051** Insert a new record into the BTree.  The content of the new record
66052** is described by the pX object.  The pCur cursor is used only to
66053** define what table the record should be inserted into, and is left
66054** pointing at a random location.
66055**
66056** For a table btree (used for rowid tables), only the pX.nKey value of
66057** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
66058** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
66059** hold the content of the row.
66060**
66061** For an index btree (used for indexes and WITHOUT ROWID tables), the
66062** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
66063** pX.pData,nData,nZero fields must be zero.
66064**
66065** If the seekResult parameter is non-zero, then a successful call to
66066** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
66067** been performed. seekResult is the search result returned (a negative
66068** number if pCur points at an entry that is smaller than (pKey, nKey), or
66069** a positive value if pCur points at an entry that is larger than
66070** (pKey, nKey)).
66071**
66072** If the seekResult parameter is non-zero, then the caller guarantees that
66073** cursor pCur is pointing at the existing copy of a row that is to be
66074** overwritten.  If the seekResult parameter is 0, then cursor pCur may
66075** point to any entry or to no entry at all and so this function has to seek
66076** the cursor before the new key can be inserted.
66077*/
66078SQLITE_PRIVATE int sqlite3BtreeInsert(
66079  BtCursor *pCur,                /* Insert data into the table of this cursor */
66080  const BtreePayload *pX,        /* Content of the row to be inserted */
66081  int appendBias,                /* True if this is likely an append */
66082  int seekResult                 /* Result of prior MovetoUnpacked() call */
66083){
66084  int rc;
66085  int loc = seekResult;          /* -1: before desired location  +1: after */
66086  int szNew = 0;
66087  int idx;
66088  MemPage *pPage;
66089  Btree *p = pCur->pBtree;
66090  BtShared *pBt = p->pBt;
66091  unsigned char *oldCell;
66092  unsigned char *newCell = 0;
66093
66094  if( pCur->eState==CURSOR_FAULT ){
66095    assert( pCur->skipNext!=SQLITE_OK );
66096    return pCur->skipNext;
66097  }
66098
66099  assert( cursorOwnsBtShared(pCur) );
66100  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
66101              && pBt->inTransaction==TRANS_WRITE
66102              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
66103  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66104
66105  /* Assert that the caller has been consistent. If this cursor was opened
66106  ** expecting an index b-tree, then the caller should be inserting blob
66107  ** keys with no associated data. If the cursor was opened expecting an
66108  ** intkey table, the caller should be inserting integer keys with a
66109  ** blob of associated data.  */
66110  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
66111
66112  /* Save the positions of any other cursors open on this table.
66113  **
66114  ** In some cases, the call to btreeMoveto() below is a no-op. For
66115  ** example, when inserting data into a table with auto-generated integer
66116  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
66117  ** integer key to use. It then calls this function to actually insert the
66118  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
66119  ** that the cursor is already where it needs to be and returns without
66120  ** doing any work. To avoid thwarting these optimizations, it is important
66121  ** not to clear the cursor here.
66122  */
66123  if( pCur->curFlags & BTCF_Multiple ){
66124    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66125    if( rc ) return rc;
66126  }
66127
66128  if( pCur->pKeyInfo==0 ){
66129    assert( pX->pKey==0 );
66130    /* If this is an insert into a table b-tree, invalidate any incrblob
66131    ** cursors open on the row being replaced */
66132    invalidateIncrblobCursors(p, pX->nKey, 0);
66133
66134    /* If the cursor is currently on the last row and we are appending a
66135    ** new row onto the end, set the "loc" to avoid an unnecessary
66136    ** btreeMoveto() call */
66137    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0
66138      && pCur->info.nKey==pX->nKey-1 ){
66139       loc = -1;
66140    }else if( loc==0 ){
66141      rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc);
66142      if( rc ) return rc;
66143    }
66144  }else if( loc==0 ){
66145    rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc);
66146    if( rc ) return rc;
66147  }
66148  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
66149
66150  pPage = pCur->apPage[pCur->iPage];
66151  assert( pPage->intKey || pX->nKey>=0 );
66152  assert( pPage->leaf || !pPage->intKey );
66153
66154  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
66155          pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
66156          loc==0 ? "overwrite" : "new entry"));
66157  assert( pPage->isInit );
66158  newCell = pBt->pTmpSpace;
66159  assert( newCell!=0 );
66160  rc = fillInCell(pPage, newCell, pX, &szNew);
66161  if( rc ) goto end_insert;
66162  assert( szNew==pPage->xCellSize(pPage, newCell) );
66163  assert( szNew <= MX_CELL_SIZE(pBt) );
66164  idx = pCur->aiIdx[pCur->iPage];
66165  if( loc==0 ){
66166    u16 szOld;
66167    assert( idx<pPage->nCell );
66168    rc = sqlite3PagerWrite(pPage->pDbPage);
66169    if( rc ){
66170      goto end_insert;
66171    }
66172    oldCell = findCell(pPage, idx);
66173    if( !pPage->leaf ){
66174      memcpy(newCell, oldCell, 4);
66175    }
66176    rc = clearCell(pPage, oldCell, &szOld);
66177    dropCell(pPage, idx, szOld, &rc);
66178    if( rc ) goto end_insert;
66179  }else if( loc<0 && pPage->nCell>0 ){
66180    assert( pPage->leaf );
66181    idx = ++pCur->aiIdx[pCur->iPage];
66182  }else{
66183    assert( pPage->leaf );
66184  }
66185  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
66186  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
66187  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
66188
66189  /* If no error has occurred and pPage has an overflow cell, call balance()
66190  ** to redistribute the cells within the tree. Since balance() may move
66191  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
66192  ** variables.
66193  **
66194  ** Previous versions of SQLite called moveToRoot() to move the cursor
66195  ** back to the root page as balance() used to invalidate the contents
66196  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
66197  ** set the cursor state to "invalid". This makes common insert operations
66198  ** slightly faster.
66199  **
66200  ** There is a subtle but important optimization here too. When inserting
66201  ** multiple records into an intkey b-tree using a single cursor (as can
66202  ** happen while processing an "INSERT INTO ... SELECT" statement), it
66203  ** is advantageous to leave the cursor pointing to the last entry in
66204  ** the b-tree if possible. If the cursor is left pointing to the last
66205  ** entry in the table, and the next row inserted has an integer key
66206  ** larger than the largest existing key, it is possible to insert the
66207  ** row without seeking the cursor. This can be a big performance boost.
66208  */
66209  pCur->info.nSize = 0;
66210  if( pPage->nOverflow ){
66211    assert( rc==SQLITE_OK );
66212    pCur->curFlags &= ~(BTCF_ValidNKey);
66213    rc = balance(pCur);
66214
66215    /* Must make sure nOverflow is reset to zero even if the balance()
66216    ** fails. Internal data structure corruption will result otherwise.
66217    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
66218    ** from trying to save the current position of the cursor.  */
66219    pCur->apPage[pCur->iPage]->nOverflow = 0;
66220    pCur->eState = CURSOR_INVALID;
66221  }
66222  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
66223
66224end_insert:
66225  return rc;
66226}
66227
66228/*
66229** Delete the entry that the cursor is pointing to.
66230**
66231** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
66232** the cursor is left pointing at an arbitrary location after the delete.
66233** But if that bit is set, then the cursor is left in a state such that
66234** the next call to BtreeNext() or BtreePrev() moves it to the same row
66235** as it would have been on if the call to BtreeDelete() had been omitted.
66236**
66237** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
66238** associated with a single table entry and its indexes.  Only one of those
66239** deletes is considered the "primary" delete.  The primary delete occurs
66240** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
66241** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
66242** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
66243** but which might be used by alternative storage engines.
66244*/
66245SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
66246  Btree *p = pCur->pBtree;
66247  BtShared *pBt = p->pBt;
66248  int rc;                              /* Return code */
66249  MemPage *pPage;                      /* Page to delete cell from */
66250  unsigned char *pCell;                /* Pointer to cell to delete */
66251  int iCellIdx;                        /* Index of cell to delete */
66252  int iCellDepth;                      /* Depth of node containing pCell */
66253  u16 szCell;                          /* Size of the cell being deleted */
66254  int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
66255  u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
66256
66257  assert( cursorOwnsBtShared(pCur) );
66258  assert( pBt->inTransaction==TRANS_WRITE );
66259  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66260  assert( pCur->curFlags & BTCF_WriteFlag );
66261  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66262  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
66263  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
66264  assert( pCur->eState==CURSOR_VALID );
66265  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
66266
66267  iCellDepth = pCur->iPage;
66268  iCellIdx = pCur->aiIdx[iCellDepth];
66269  pPage = pCur->apPage[iCellDepth];
66270  pCell = findCell(pPage, iCellIdx);
66271
66272  /* If the bPreserve flag is set to true, then the cursor position must
66273  ** be preserved following this delete operation. If the current delete
66274  ** will cause a b-tree rebalance, then this is done by saving the cursor
66275  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
66276  ** returning.
66277  **
66278  ** Or, if the current delete will not cause a rebalance, then the cursor
66279  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
66280  ** before or after the deleted entry. In this case set bSkipnext to true.  */
66281  if( bPreserve ){
66282    if( !pPage->leaf
66283     || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
66284    ){
66285      /* A b-tree rebalance will be required after deleting this entry.
66286      ** Save the cursor key.  */
66287      rc = saveCursorKey(pCur);
66288      if( rc ) return rc;
66289    }else{
66290      bSkipnext = 1;
66291    }
66292  }
66293
66294  /* If the page containing the entry to delete is not a leaf page, move
66295  ** the cursor to the largest entry in the tree that is smaller than
66296  ** the entry being deleted. This cell will replace the cell being deleted
66297  ** from the internal node. The 'previous' entry is used for this instead
66298  ** of the 'next' entry, as the previous entry is always a part of the
66299  ** sub-tree headed by the child page of the cell being deleted. This makes
66300  ** balancing the tree following the delete operation easier.  */
66301  if( !pPage->leaf ){
66302    int notUsed = 0;
66303    rc = sqlite3BtreePrevious(pCur, &notUsed);
66304    if( rc ) return rc;
66305  }
66306
66307  /* Save the positions of any other cursors open on this table before
66308  ** making any modifications.  */
66309  if( pCur->curFlags & BTCF_Multiple ){
66310    rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66311    if( rc ) return rc;
66312  }
66313
66314  /* If this is a delete operation to remove a row from a table b-tree,
66315  ** invalidate any incrblob cursors open on the row being deleted.  */
66316  if( pCur->pKeyInfo==0 ){
66317    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
66318  }
66319
66320  /* Make the page containing the entry to be deleted writable. Then free any
66321  ** overflow pages associated with the entry and finally remove the cell
66322  ** itself from within the page.  */
66323  rc = sqlite3PagerWrite(pPage->pDbPage);
66324  if( rc ) return rc;
66325  rc = clearCell(pPage, pCell, &szCell);
66326  dropCell(pPage, iCellIdx, szCell, &rc);
66327  if( rc ) return rc;
66328
66329  /* If the cell deleted was not located on a leaf page, then the cursor
66330  ** is currently pointing to the largest entry in the sub-tree headed
66331  ** by the child-page of the cell that was just deleted from an internal
66332  ** node. The cell from the leaf node needs to be moved to the internal
66333  ** node to replace the deleted cell.  */
66334  if( !pPage->leaf ){
66335    MemPage *pLeaf = pCur->apPage[pCur->iPage];
66336    int nCell;
66337    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
66338    unsigned char *pTmp;
66339
66340    pCell = findCell(pLeaf, pLeaf->nCell-1);
66341    if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
66342    nCell = pLeaf->xCellSize(pLeaf, pCell);
66343    assert( MX_CELL_SIZE(pBt) >= nCell );
66344    pTmp = pBt->pTmpSpace;
66345    assert( pTmp!=0 );
66346    rc = sqlite3PagerWrite(pLeaf->pDbPage);
66347    if( rc==SQLITE_OK ){
66348      insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
66349    }
66350    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
66351    if( rc ) return rc;
66352  }
66353
66354  /* Balance the tree. If the entry deleted was located on a leaf page,
66355  ** then the cursor still points to that page. In this case the first
66356  ** call to balance() repairs the tree, and the if(...) condition is
66357  ** never true.
66358  **
66359  ** Otherwise, if the entry deleted was on an internal node page, then
66360  ** pCur is pointing to the leaf page from which a cell was removed to
66361  ** replace the cell deleted from the internal node. This is slightly
66362  ** tricky as the leaf node may be underfull, and the internal node may
66363  ** be either under or overfull. In this case run the balancing algorithm
66364  ** on the leaf node first. If the balance proceeds far enough up the
66365  ** tree that we can be sure that any problem in the internal node has
66366  ** been corrected, so be it. Otherwise, after balancing the leaf node,
66367  ** walk the cursor up the tree to the internal node and balance it as
66368  ** well.  */
66369  rc = balance(pCur);
66370  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
66371    while( pCur->iPage>iCellDepth ){
66372      releasePage(pCur->apPage[pCur->iPage--]);
66373    }
66374    rc = balance(pCur);
66375  }
66376
66377  if( rc==SQLITE_OK ){
66378    if( bSkipnext ){
66379      assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
66380      assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
66381      assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
66382      pCur->eState = CURSOR_SKIPNEXT;
66383      if( iCellIdx>=pPage->nCell ){
66384        pCur->skipNext = -1;
66385        pCur->aiIdx[iCellDepth] = pPage->nCell-1;
66386      }else{
66387        pCur->skipNext = 1;
66388      }
66389    }else{
66390      rc = moveToRoot(pCur);
66391      if( bPreserve ){
66392        pCur->eState = CURSOR_REQUIRESEEK;
66393      }
66394    }
66395  }
66396  return rc;
66397}
66398
66399/*
66400** Create a new BTree table.  Write into *piTable the page
66401** number for the root page of the new table.
66402**
66403** The type of type is determined by the flags parameter.  Only the
66404** following values of flags are currently in use.  Other values for
66405** flags might not work:
66406**
66407**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
66408**     BTREE_ZERODATA                  Used for SQL indices
66409*/
66410static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
66411  BtShared *pBt = p->pBt;
66412  MemPage *pRoot;
66413  Pgno pgnoRoot;
66414  int rc;
66415  int ptfFlags;          /* Page-type flage for the root page of new table */
66416
66417  assert( sqlite3BtreeHoldsMutex(p) );
66418  assert( pBt->inTransaction==TRANS_WRITE );
66419  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66420
66421#ifdef SQLITE_OMIT_AUTOVACUUM
66422  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66423  if( rc ){
66424    return rc;
66425  }
66426#else
66427  if( pBt->autoVacuum ){
66428    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
66429    MemPage *pPageMove; /* The page to move to. */
66430
66431    /* Creating a new table may probably require moving an existing database
66432    ** to make room for the new tables root page. In case this page turns
66433    ** out to be an overflow page, delete all overflow page-map caches
66434    ** held by open cursors.
66435    */
66436    invalidateAllOverflowCache(pBt);
66437
66438    /* Read the value of meta[3] from the database to determine where the
66439    ** root page of the new table should go. meta[3] is the largest root-page
66440    ** created so far, so the new root-page is (meta[3]+1).
66441    */
66442    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
66443    pgnoRoot++;
66444
66445    /* The new root-page may not be allocated on a pointer-map page, or the
66446    ** PENDING_BYTE page.
66447    */
66448    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
66449        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
66450      pgnoRoot++;
66451    }
66452    assert( pgnoRoot>=3 || CORRUPT_DB );
66453    testcase( pgnoRoot<3 );
66454
66455    /* Allocate a page. The page that currently resides at pgnoRoot will
66456    ** be moved to the allocated page (unless the allocated page happens
66457    ** to reside at pgnoRoot).
66458    */
66459    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
66460    if( rc!=SQLITE_OK ){
66461      return rc;
66462    }
66463
66464    if( pgnoMove!=pgnoRoot ){
66465      /* pgnoRoot is the page that will be used for the root-page of
66466      ** the new table (assuming an error did not occur). But we were
66467      ** allocated pgnoMove. If required (i.e. if it was not allocated
66468      ** by extending the file), the current page at position pgnoMove
66469      ** is already journaled.
66470      */
66471      u8 eType = 0;
66472      Pgno iPtrPage = 0;
66473
66474      /* Save the positions of any open cursors. This is required in
66475      ** case they are holding a reference to an xFetch reference
66476      ** corresponding to page pgnoRoot.  */
66477      rc = saveAllCursors(pBt, 0, 0);
66478      releasePage(pPageMove);
66479      if( rc!=SQLITE_OK ){
66480        return rc;
66481      }
66482
66483      /* Move the page currently at pgnoRoot to pgnoMove. */
66484      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66485      if( rc!=SQLITE_OK ){
66486        return rc;
66487      }
66488      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
66489      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
66490        rc = SQLITE_CORRUPT_BKPT;
66491      }
66492      if( rc!=SQLITE_OK ){
66493        releasePage(pRoot);
66494        return rc;
66495      }
66496      assert( eType!=PTRMAP_ROOTPAGE );
66497      assert( eType!=PTRMAP_FREEPAGE );
66498      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
66499      releasePage(pRoot);
66500
66501      /* Obtain the page at pgnoRoot */
66502      if( rc!=SQLITE_OK ){
66503        return rc;
66504      }
66505      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66506      if( rc!=SQLITE_OK ){
66507        return rc;
66508      }
66509      rc = sqlite3PagerWrite(pRoot->pDbPage);
66510      if( rc!=SQLITE_OK ){
66511        releasePage(pRoot);
66512        return rc;
66513      }
66514    }else{
66515      pRoot = pPageMove;
66516    }
66517
66518    /* Update the pointer-map and meta-data with the new root-page number. */
66519    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
66520    if( rc ){
66521      releasePage(pRoot);
66522      return rc;
66523    }
66524
66525    /* When the new root page was allocated, page 1 was made writable in
66526    ** order either to increase the database filesize, or to decrement the
66527    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
66528    */
66529    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
66530    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
66531    if( NEVER(rc) ){
66532      releasePage(pRoot);
66533      return rc;
66534    }
66535
66536  }else{
66537    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66538    if( rc ) return rc;
66539  }
66540#endif
66541  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66542  if( createTabFlags & BTREE_INTKEY ){
66543    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
66544  }else{
66545    ptfFlags = PTF_ZERODATA | PTF_LEAF;
66546  }
66547  zeroPage(pRoot, ptfFlags);
66548  sqlite3PagerUnref(pRoot->pDbPage);
66549  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
66550  *piTable = (int)pgnoRoot;
66551  return SQLITE_OK;
66552}
66553SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
66554  int rc;
66555  sqlite3BtreeEnter(p);
66556  rc = btreeCreateTable(p, piTable, flags);
66557  sqlite3BtreeLeave(p);
66558  return rc;
66559}
66560
66561/*
66562** Erase the given database page and all its children.  Return
66563** the page to the freelist.
66564*/
66565static int clearDatabasePage(
66566  BtShared *pBt,           /* The BTree that contains the table */
66567  Pgno pgno,               /* Page number to clear */
66568  int freePageFlag,        /* Deallocate page if true */
66569  int *pnChange            /* Add number of Cells freed to this counter */
66570){
66571  MemPage *pPage;
66572  int rc;
66573  unsigned char *pCell;
66574  int i;
66575  int hdr;
66576  u16 szCell;
66577
66578  assert( sqlite3_mutex_held(pBt->mutex) );
66579  if( pgno>btreePagecount(pBt) ){
66580    return SQLITE_CORRUPT_BKPT;
66581  }
66582  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
66583  if( rc ) return rc;
66584  if( pPage->bBusy ){
66585    rc = SQLITE_CORRUPT_BKPT;
66586    goto cleardatabasepage_out;
66587  }
66588  pPage->bBusy = 1;
66589  hdr = pPage->hdrOffset;
66590  for(i=0; i<pPage->nCell; i++){
66591    pCell = findCell(pPage, i);
66592    if( !pPage->leaf ){
66593      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
66594      if( rc ) goto cleardatabasepage_out;
66595    }
66596    rc = clearCell(pPage, pCell, &szCell);
66597    if( rc ) goto cleardatabasepage_out;
66598  }
66599  if( !pPage->leaf ){
66600    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
66601    if( rc ) goto cleardatabasepage_out;
66602  }else if( pnChange ){
66603    assert( pPage->intKey || CORRUPT_DB );
66604    testcase( !pPage->intKey );
66605    *pnChange += pPage->nCell;
66606  }
66607  if( freePageFlag ){
66608    freePage(pPage, &rc);
66609  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
66610    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
66611  }
66612
66613cleardatabasepage_out:
66614  pPage->bBusy = 0;
66615  releasePage(pPage);
66616  return rc;
66617}
66618
66619/*
66620** Delete all information from a single table in the database.  iTable is
66621** the page number of the root of the table.  After this routine returns,
66622** the root page is empty, but still exists.
66623**
66624** This routine will fail with SQLITE_LOCKED if there are any open
66625** read cursors on the table.  Open write cursors are moved to the
66626** root of the table.
66627**
66628** If pnChange is not NULL, then table iTable must be an intkey table. The
66629** integer value pointed to by pnChange is incremented by the number of
66630** entries in the table.
66631*/
66632SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
66633  int rc;
66634  BtShared *pBt = p->pBt;
66635  sqlite3BtreeEnter(p);
66636  assert( p->inTrans==TRANS_WRITE );
66637
66638  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
66639
66640  if( SQLITE_OK==rc ){
66641    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
66642    ** is the root of a table b-tree - if it is not, the following call is
66643    ** a no-op).  */
66644    invalidateIncrblobCursors(p, 0, 1);
66645    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
66646  }
66647  sqlite3BtreeLeave(p);
66648  return rc;
66649}
66650
66651/*
66652** Delete all information from the single table that pCur is open on.
66653**
66654** This routine only work for pCur on an ephemeral table.
66655*/
66656SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
66657  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
66658}
66659
66660/*
66661** Erase all information in a table and add the root of the table to
66662** the freelist.  Except, the root of the principle table (the one on
66663** page 1) is never added to the freelist.
66664**
66665** This routine will fail with SQLITE_LOCKED if there are any open
66666** cursors on the table.
66667**
66668** If AUTOVACUUM is enabled and the page at iTable is not the last
66669** root page in the database file, then the last root page
66670** in the database file is moved into the slot formerly occupied by
66671** iTable and that last slot formerly occupied by the last root page
66672** is added to the freelist instead of iTable.  In this say, all
66673** root pages are kept at the beginning of the database file, which
66674** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
66675** page number that used to be the last root page in the file before
66676** the move.  If no page gets moved, *piMoved is set to 0.
66677** The last root page is recorded in meta[3] and the value of
66678** meta[3] is updated by this procedure.
66679*/
66680static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
66681  int rc;
66682  MemPage *pPage = 0;
66683  BtShared *pBt = p->pBt;
66684
66685  assert( sqlite3BtreeHoldsMutex(p) );
66686  assert( p->inTrans==TRANS_WRITE );
66687
66688  /* It is illegal to drop a table if any cursors are open on the
66689  ** database. This is because in auto-vacuum mode the backend may
66690  ** need to move another root-page to fill a gap left by the deleted
66691  ** root page. If an open cursor was using this page a problem would
66692  ** occur.
66693  **
66694  ** This error is caught long before control reaches this point.
66695  */
66696  if( NEVER(pBt->pCursor) ){
66697    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
66698    return SQLITE_LOCKED_SHAREDCACHE;
66699  }
66700
66701  /*
66702  ** It is illegal to drop the sqlite_master table on page 1.  But again,
66703  ** this error is caught long before reaching this point.
66704  */
66705  if( NEVER(iTable<2) ){
66706    return SQLITE_CORRUPT_BKPT;
66707  }
66708
66709  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
66710  if( rc ) return rc;
66711  rc = sqlite3BtreeClearTable(p, iTable, 0);
66712  if( rc ){
66713    releasePage(pPage);
66714    return rc;
66715  }
66716
66717  *piMoved = 0;
66718
66719#ifdef SQLITE_OMIT_AUTOVACUUM
66720  freePage(pPage, &rc);
66721  releasePage(pPage);
66722#else
66723  if( pBt->autoVacuum ){
66724    Pgno maxRootPgno;
66725    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
66726
66727    if( iTable==maxRootPgno ){
66728      /* If the table being dropped is the table with the largest root-page
66729      ** number in the database, put the root page on the free list.
66730      */
66731      freePage(pPage, &rc);
66732      releasePage(pPage);
66733      if( rc!=SQLITE_OK ){
66734        return rc;
66735      }
66736    }else{
66737      /* The table being dropped does not have the largest root-page
66738      ** number in the database. So move the page that does into the
66739      ** gap left by the deleted root-page.
66740      */
66741      MemPage *pMove;
66742      releasePage(pPage);
66743      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66744      if( rc!=SQLITE_OK ){
66745        return rc;
66746      }
66747      rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
66748      releasePage(pMove);
66749      if( rc!=SQLITE_OK ){
66750        return rc;
66751      }
66752      pMove = 0;
66753      rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66754      freePage(pMove, &rc);
66755      releasePage(pMove);
66756      if( rc!=SQLITE_OK ){
66757        return rc;
66758      }
66759      *piMoved = maxRootPgno;
66760    }
66761
66762    /* Set the new 'max-root-page' value in the database header. This
66763    ** is the old value less one, less one more if that happens to
66764    ** be a root-page number, less one again if that is the
66765    ** PENDING_BYTE_PAGE.
66766    */
66767    maxRootPgno--;
66768    while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
66769           || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
66770      maxRootPgno--;
66771    }
66772    assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
66773
66774    rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
66775  }else{
66776    freePage(pPage, &rc);
66777    releasePage(pPage);
66778  }
66779#endif
66780  return rc;
66781}
66782SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
66783  int rc;
66784  sqlite3BtreeEnter(p);
66785  rc = btreeDropTable(p, iTable, piMoved);
66786  sqlite3BtreeLeave(p);
66787  return rc;
66788}
66789
66790
66791/*
66792** This function may only be called if the b-tree connection already
66793** has a read or write transaction open on the database.
66794**
66795** Read the meta-information out of a database file.  Meta[0]
66796** is the number of free pages currently in the database.  Meta[1]
66797** through meta[15] are available for use by higher layers.  Meta[0]
66798** is read-only, the others are read/write.
66799**
66800** The schema layer numbers meta values differently.  At the schema
66801** layer (and the SetCookie and ReadCookie opcodes) the number of
66802** free pages is not visible.  So Cookie[0] is the same as Meta[1].
66803**
66804** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
66805** of reading the value out of the header, it instead loads the "DataVersion"
66806** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
66807** database file.  It is a number computed by the pager.  But its access
66808** pattern is the same as header meta values, and so it is convenient to
66809** read it from this routine.
66810*/
66811SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
66812  BtShared *pBt = p->pBt;
66813
66814  sqlite3BtreeEnter(p);
66815  assert( p->inTrans>TRANS_NONE );
66816  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
66817  assert( pBt->pPage1 );
66818  assert( idx>=0 && idx<=15 );
66819
66820  if( idx==BTREE_DATA_VERSION ){
66821    *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
66822  }else{
66823    *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
66824  }
66825
66826  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
66827  ** database, mark the database as read-only.  */
66828#ifdef SQLITE_OMIT_AUTOVACUUM
66829  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
66830    pBt->btsFlags |= BTS_READ_ONLY;
66831  }
66832#endif
66833
66834  sqlite3BtreeLeave(p);
66835}
66836
66837/*
66838** Write meta-information back into the database.  Meta[0] is
66839** read-only and may not be written.
66840*/
66841SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
66842  BtShared *pBt = p->pBt;
66843  unsigned char *pP1;
66844  int rc;
66845  assert( idx>=1 && idx<=15 );
66846  sqlite3BtreeEnter(p);
66847  assert( p->inTrans==TRANS_WRITE );
66848  assert( pBt->pPage1!=0 );
66849  pP1 = pBt->pPage1->aData;
66850  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
66851  if( rc==SQLITE_OK ){
66852    put4byte(&pP1[36 + idx*4], iMeta);
66853#ifndef SQLITE_OMIT_AUTOVACUUM
66854    if( idx==BTREE_INCR_VACUUM ){
66855      assert( pBt->autoVacuum || iMeta==0 );
66856      assert( iMeta==0 || iMeta==1 );
66857      pBt->incrVacuum = (u8)iMeta;
66858    }
66859#endif
66860  }
66861  sqlite3BtreeLeave(p);
66862  return rc;
66863}
66864
66865#ifndef SQLITE_OMIT_BTREECOUNT
66866/*
66867** The first argument, pCur, is a cursor opened on some b-tree. Count the
66868** number of entries in the b-tree and write the result to *pnEntry.
66869**
66870** SQLITE_OK is returned if the operation is successfully executed.
66871** Otherwise, if an error is encountered (i.e. an IO error or database
66872** corruption) an SQLite error code is returned.
66873*/
66874SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
66875  i64 nEntry = 0;                      /* Value to return in *pnEntry */
66876  int rc;                              /* Return code */
66877
66878  if( pCur->pgnoRoot==0 ){
66879    *pnEntry = 0;
66880    return SQLITE_OK;
66881  }
66882  rc = moveToRoot(pCur);
66883
66884  /* Unless an error occurs, the following loop runs one iteration for each
66885  ** page in the B-Tree structure (not including overflow pages).
66886  */
66887  while( rc==SQLITE_OK ){
66888    int iIdx;                          /* Index of child node in parent */
66889    MemPage *pPage;                    /* Current page of the b-tree */
66890
66891    /* If this is a leaf page or the tree is not an int-key tree, then
66892    ** this page contains countable entries. Increment the entry counter
66893    ** accordingly.
66894    */
66895    pPage = pCur->apPage[pCur->iPage];
66896    if( pPage->leaf || !pPage->intKey ){
66897      nEntry += pPage->nCell;
66898    }
66899
66900    /* pPage is a leaf node. This loop navigates the cursor so that it
66901    ** points to the first interior cell that it points to the parent of
66902    ** the next page in the tree that has not yet been visited. The
66903    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
66904    ** of the page, or to the number of cells in the page if the next page
66905    ** to visit is the right-child of its parent.
66906    **
66907    ** If all pages in the tree have been visited, return SQLITE_OK to the
66908    ** caller.
66909    */
66910    if( pPage->leaf ){
66911      do {
66912        if( pCur->iPage==0 ){
66913          /* All pages of the b-tree have been visited. Return successfully. */
66914          *pnEntry = nEntry;
66915          return moveToRoot(pCur);
66916        }
66917        moveToParent(pCur);
66918      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
66919
66920      pCur->aiIdx[pCur->iPage]++;
66921      pPage = pCur->apPage[pCur->iPage];
66922    }
66923
66924    /* Descend to the child node of the cell that the cursor currently
66925    ** points at. This is the right-child if (iIdx==pPage->nCell).
66926    */
66927    iIdx = pCur->aiIdx[pCur->iPage];
66928    if( iIdx==pPage->nCell ){
66929      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
66930    }else{
66931      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
66932    }
66933  }
66934
66935  /* An error has occurred. Return an error code. */
66936  return rc;
66937}
66938#endif
66939
66940/*
66941** Return the pager associated with a BTree.  This routine is used for
66942** testing and debugging only.
66943*/
66944SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
66945  return p->pBt->pPager;
66946}
66947
66948#ifndef SQLITE_OMIT_INTEGRITY_CHECK
66949/*
66950** Append a message to the error message string.
66951*/
66952static void checkAppendMsg(
66953  IntegrityCk *pCheck,
66954  const char *zFormat,
66955  ...
66956){
66957  va_list ap;
66958  if( !pCheck->mxErr ) return;
66959  pCheck->mxErr--;
66960  pCheck->nErr++;
66961  va_start(ap, zFormat);
66962  if( pCheck->errMsg.nChar ){
66963    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
66964  }
66965  if( pCheck->zPfx ){
66966    sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
66967  }
66968  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
66969  va_end(ap);
66970  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
66971    pCheck->mallocFailed = 1;
66972  }
66973}
66974#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
66975
66976#ifndef SQLITE_OMIT_INTEGRITY_CHECK
66977
66978/*
66979** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
66980** corresponds to page iPg is already set.
66981*/
66982static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66983  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66984  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
66985}
66986
66987/*
66988** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
66989*/
66990static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66991  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66992  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
66993}
66994
66995
66996/*
66997** Add 1 to the reference count for page iPage.  If this is the second
66998** reference to the page, add an error message to pCheck->zErrMsg.
66999** Return 1 if there are 2 or more references to the page and 0 if
67000** if this is the first reference to the page.
67001**
67002** Also check that the page number is in bounds.
67003*/
67004static int checkRef(IntegrityCk *pCheck, Pgno iPage){
67005  if( iPage==0 ) return 1;
67006  if( iPage>pCheck->nPage ){
67007    checkAppendMsg(pCheck, "invalid page number %d", iPage);
67008    return 1;
67009  }
67010  if( getPageReferenced(pCheck, iPage) ){
67011    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
67012    return 1;
67013  }
67014  setPageReferenced(pCheck, iPage);
67015  return 0;
67016}
67017
67018#ifndef SQLITE_OMIT_AUTOVACUUM
67019/*
67020** Check that the entry in the pointer-map for page iChild maps to
67021** page iParent, pointer type ptrType. If not, append an error message
67022** to pCheck.
67023*/
67024static void checkPtrmap(
67025  IntegrityCk *pCheck,   /* Integrity check context */
67026  Pgno iChild,           /* Child page number */
67027  u8 eType,              /* Expected pointer map type */
67028  Pgno iParent           /* Expected pointer map parent page number */
67029){
67030  int rc;
67031  u8 ePtrmapType;
67032  Pgno iPtrmapParent;
67033
67034  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
67035  if( rc!=SQLITE_OK ){
67036    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
67037    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
67038    return;
67039  }
67040
67041  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
67042    checkAppendMsg(pCheck,
67043      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
67044      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
67045  }
67046}
67047#endif
67048
67049/*
67050** Check the integrity of the freelist or of an overflow page list.
67051** Verify that the number of pages on the list is N.
67052*/
67053static void checkList(
67054  IntegrityCk *pCheck,  /* Integrity checking context */
67055  int isFreeList,       /* True for a freelist.  False for overflow page list */
67056  int iPage,            /* Page number for first page in the list */
67057  int N                 /* Expected number of pages in the list */
67058){
67059  int i;
67060  int expected = N;
67061  int iFirst = iPage;
67062  while( N-- > 0 && pCheck->mxErr ){
67063    DbPage *pOvflPage;
67064    unsigned char *pOvflData;
67065    if( iPage<1 ){
67066      checkAppendMsg(pCheck,
67067         "%d of %d pages missing from overflow list starting at %d",
67068          N+1, expected, iFirst);
67069      break;
67070    }
67071    if( checkRef(pCheck, iPage) ) break;
67072    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
67073      checkAppendMsg(pCheck, "failed to get page %d", iPage);
67074      break;
67075    }
67076    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
67077    if( isFreeList ){
67078      int n = get4byte(&pOvflData[4]);
67079#ifndef SQLITE_OMIT_AUTOVACUUM
67080      if( pCheck->pBt->autoVacuum ){
67081        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
67082      }
67083#endif
67084      if( n>(int)pCheck->pBt->usableSize/4-2 ){
67085        checkAppendMsg(pCheck,
67086           "freelist leaf count too big on page %d", iPage);
67087        N--;
67088      }else{
67089        for(i=0; i<n; i++){
67090          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
67091#ifndef SQLITE_OMIT_AUTOVACUUM
67092          if( pCheck->pBt->autoVacuum ){
67093            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
67094          }
67095#endif
67096          checkRef(pCheck, iFreePage);
67097        }
67098        N -= n;
67099      }
67100    }
67101#ifndef SQLITE_OMIT_AUTOVACUUM
67102    else{
67103      /* If this database supports auto-vacuum and iPage is not the last
67104      ** page in this overflow list, check that the pointer-map entry for
67105      ** the following page matches iPage.
67106      */
67107      if( pCheck->pBt->autoVacuum && N>0 ){
67108        i = get4byte(pOvflData);
67109        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
67110      }
67111    }
67112#endif
67113    iPage = get4byte(pOvflData);
67114    sqlite3PagerUnref(pOvflPage);
67115
67116    if( isFreeList && N<(iPage!=0) ){
67117      checkAppendMsg(pCheck, "free-page count in header is too small");
67118    }
67119  }
67120}
67121#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67122
67123/*
67124** An implementation of a min-heap.
67125**
67126** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
67127** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
67128** and aHeap[N*2+1].
67129**
67130** The heap property is this:  Every node is less than or equal to both
67131** of its daughter nodes.  A consequence of the heap property is that the
67132** root node aHeap[1] is always the minimum value currently in the heap.
67133**
67134** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
67135** the heap, preserving the heap property.  The btreeHeapPull() routine
67136** removes the root element from the heap (the minimum value in the heap)
67137** and then moves other nodes around as necessary to preserve the heap
67138** property.
67139**
67140** This heap is used for cell overlap and coverage testing.  Each u32
67141** entry represents the span of a cell or freeblock on a btree page.
67142** The upper 16 bits are the index of the first byte of a range and the
67143** lower 16 bits are the index of the last byte of that range.
67144*/
67145static void btreeHeapInsert(u32 *aHeap, u32 x){
67146  u32 j, i = ++aHeap[0];
67147  aHeap[i] = x;
67148  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
67149    x = aHeap[j];
67150    aHeap[j] = aHeap[i];
67151    aHeap[i] = x;
67152    i = j;
67153  }
67154}
67155static int btreeHeapPull(u32 *aHeap, u32 *pOut){
67156  u32 j, i, x;
67157  if( (x = aHeap[0])==0 ) return 0;
67158  *pOut = aHeap[1];
67159  aHeap[1] = aHeap[x];
67160  aHeap[x] = 0xffffffff;
67161  aHeap[0]--;
67162  i = 1;
67163  while( (j = i*2)<=aHeap[0] ){
67164    if( aHeap[j]>aHeap[j+1] ) j++;
67165    if( aHeap[i]<aHeap[j] ) break;
67166    x = aHeap[i];
67167    aHeap[i] = aHeap[j];
67168    aHeap[j] = x;
67169    i = j;
67170  }
67171  return 1;
67172}
67173
67174#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67175/*
67176** Do various sanity checks on a single page of a tree.  Return
67177** the tree depth.  Root pages return 0.  Parents of root pages
67178** return 1, and so forth.
67179**
67180** These checks are done:
67181**
67182**      1.  Make sure that cells and freeblocks do not overlap
67183**          but combine to completely cover the page.
67184**      2.  Make sure integer cell keys are in order.
67185**      3.  Check the integrity of overflow pages.
67186**      4.  Recursively call checkTreePage on all children.
67187**      5.  Verify that the depth of all children is the same.
67188*/
67189static int checkTreePage(
67190  IntegrityCk *pCheck,  /* Context for the sanity check */
67191  int iPage,            /* Page number of the page to check */
67192  i64 *piMinKey,        /* Write minimum integer primary key here */
67193  i64 maxKey            /* Error if integer primary key greater than this */
67194){
67195  MemPage *pPage = 0;      /* The page being analyzed */
67196  int i;                   /* Loop counter */
67197  int rc;                  /* Result code from subroutine call */
67198  int depth = -1, d2;      /* Depth of a subtree */
67199  int pgno;                /* Page number */
67200  int nFrag;               /* Number of fragmented bytes on the page */
67201  int hdr;                 /* Offset to the page header */
67202  int cellStart;           /* Offset to the start of the cell pointer array */
67203  int nCell;               /* Number of cells */
67204  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
67205  int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
67206                           ** False if IPK must be strictly less than maxKey */
67207  u8 *data;                /* Page content */
67208  u8 *pCell;               /* Cell content */
67209  u8 *pCellIdx;            /* Next element of the cell pointer array */
67210  BtShared *pBt;           /* The BtShared object that owns pPage */
67211  u32 pc;                  /* Address of a cell */
67212  u32 usableSize;          /* Usable size of the page */
67213  u32 contentOffset;       /* Offset to the start of the cell content area */
67214  u32 *heap = 0;           /* Min-heap used for checking cell coverage */
67215  u32 x, prev = 0;         /* Next and previous entry on the min-heap */
67216  const char *saved_zPfx = pCheck->zPfx;
67217  int saved_v1 = pCheck->v1;
67218  int saved_v2 = pCheck->v2;
67219  u8 savedIsInit = 0;
67220
67221  /* Check that the page exists
67222  */
67223  pBt = pCheck->pBt;
67224  usableSize = pBt->usableSize;
67225  if( iPage==0 ) return 0;
67226  if( checkRef(pCheck, iPage) ) return 0;
67227  pCheck->zPfx = "Page %d: ";
67228  pCheck->v1 = iPage;
67229  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
67230    checkAppendMsg(pCheck,
67231       "unable to get the page. error code=%d", rc);
67232    goto end_of_check;
67233  }
67234
67235  /* Clear MemPage.isInit to make sure the corruption detection code in
67236  ** btreeInitPage() is executed.  */
67237  savedIsInit = pPage->isInit;
67238  pPage->isInit = 0;
67239  if( (rc = btreeInitPage(pPage))!=0 ){
67240    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
67241    checkAppendMsg(pCheck,
67242                   "btreeInitPage() returns error code %d", rc);
67243    goto end_of_check;
67244  }
67245  data = pPage->aData;
67246  hdr = pPage->hdrOffset;
67247
67248  /* Set up for cell analysis */
67249  pCheck->zPfx = "On tree page %d cell %d: ";
67250  contentOffset = get2byteNotZero(&data[hdr+5]);
67251  assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
67252
67253  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
67254  ** number of cells on the page. */
67255  nCell = get2byte(&data[hdr+3]);
67256  assert( pPage->nCell==nCell );
67257
67258  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
67259  ** immediately follows the b-tree page header. */
67260  cellStart = hdr + 12 - 4*pPage->leaf;
67261  assert( pPage->aCellIdx==&data[cellStart] );
67262  pCellIdx = &data[cellStart + 2*(nCell-1)];
67263
67264  if( !pPage->leaf ){
67265    /* Analyze the right-child page of internal pages */
67266    pgno = get4byte(&data[hdr+8]);
67267#ifndef SQLITE_OMIT_AUTOVACUUM
67268    if( pBt->autoVacuum ){
67269      pCheck->zPfx = "On page %d at right child: ";
67270      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67271    }
67272#endif
67273    depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67274    keyCanBeEqual = 0;
67275  }else{
67276    /* For leaf pages, the coverage check will occur in the same loop
67277    ** as the other cell checks, so initialize the heap.  */
67278    heap = pCheck->heap;
67279    heap[0] = 0;
67280  }
67281
67282  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
67283  ** integer offsets to the cell contents. */
67284  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
67285    CellInfo info;
67286
67287    /* Check cell size */
67288    pCheck->v2 = i;
67289    assert( pCellIdx==&data[cellStart + i*2] );
67290    pc = get2byteAligned(pCellIdx);
67291    pCellIdx -= 2;
67292    if( pc<contentOffset || pc>usableSize-4 ){
67293      checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
67294                             pc, contentOffset, usableSize-4);
67295      doCoverageCheck = 0;
67296      continue;
67297    }
67298    pCell = &data[pc];
67299    pPage->xParseCell(pPage, pCell, &info);
67300    if( pc+info.nSize>usableSize ){
67301      checkAppendMsg(pCheck, "Extends off end of page");
67302      doCoverageCheck = 0;
67303      continue;
67304    }
67305
67306    /* Check for integer primary key out of range */
67307    if( pPage->intKey ){
67308      if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
67309        checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
67310      }
67311      maxKey = info.nKey;
67312    }
67313
67314    /* Check the content overflow list */
67315    if( info.nPayload>info.nLocal ){
67316      int nPage;       /* Number of pages on the overflow chain */
67317      Pgno pgnoOvfl;   /* First page of the overflow chain */
67318      assert( pc + info.nSize - 4 <= usableSize );
67319      nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
67320      pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
67321#ifndef SQLITE_OMIT_AUTOVACUUM
67322      if( pBt->autoVacuum ){
67323        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
67324      }
67325#endif
67326      checkList(pCheck, 0, pgnoOvfl, nPage);
67327    }
67328
67329    if( !pPage->leaf ){
67330      /* Check sanity of left child page for internal pages */
67331      pgno = get4byte(pCell);
67332#ifndef SQLITE_OMIT_AUTOVACUUM
67333      if( pBt->autoVacuum ){
67334        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67335      }
67336#endif
67337      d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67338      keyCanBeEqual = 0;
67339      if( d2!=depth ){
67340        checkAppendMsg(pCheck, "Child page depth differs");
67341        depth = d2;
67342      }
67343    }else{
67344      /* Populate the coverage-checking heap for leaf pages */
67345      btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
67346    }
67347  }
67348  *piMinKey = maxKey;
67349
67350  /* Check for complete coverage of the page
67351  */
67352  pCheck->zPfx = 0;
67353  if( doCoverageCheck && pCheck->mxErr>0 ){
67354    /* For leaf pages, the min-heap has already been initialized and the
67355    ** cells have already been inserted.  But for internal pages, that has
67356    ** not yet been done, so do it now */
67357    if( !pPage->leaf ){
67358      heap = pCheck->heap;
67359      heap[0] = 0;
67360      for(i=nCell-1; i>=0; i--){
67361        u32 size;
67362        pc = get2byteAligned(&data[cellStart+i*2]);
67363        size = pPage->xCellSize(pPage, &data[pc]);
67364        btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
67365      }
67366    }
67367    /* Add the freeblocks to the min-heap
67368    **
67369    ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
67370    ** is the offset of the first freeblock, or zero if there are no
67371    ** freeblocks on the page.
67372    */
67373    i = get2byte(&data[hdr+1]);
67374    while( i>0 ){
67375      int size, j;
67376      assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
67377      size = get2byte(&data[i+2]);
67378      assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
67379      btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
67380      /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
67381      ** big-endian integer which is the offset in the b-tree page of the next
67382      ** freeblock in the chain, or zero if the freeblock is the last on the
67383      ** chain. */
67384      j = get2byte(&data[i]);
67385      /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
67386      ** increasing offset. */
67387      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
67388      assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
67389      i = j;
67390    }
67391    /* Analyze the min-heap looking for overlap between cells and/or
67392    ** freeblocks, and counting the number of untracked bytes in nFrag.
67393    **
67394    ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
67395    ** There is an implied first entry the covers the page header, the cell
67396    ** pointer index, and the gap between the cell pointer index and the start
67397    ** of cell content.
67398    **
67399    ** The loop below pulls entries from the min-heap in order and compares
67400    ** the start_address against the previous end_address.  If there is an
67401    ** overlap, that means bytes are used multiple times.  If there is a gap,
67402    ** that gap is added to the fragmentation count.
67403    */
67404    nFrag = 0;
67405    prev = contentOffset - 1;   /* Implied first min-heap entry */
67406    while( btreeHeapPull(heap,&x) ){
67407      if( (prev&0xffff)>=(x>>16) ){
67408        checkAppendMsg(pCheck,
67409          "Multiple uses for byte %u of page %d", x>>16, iPage);
67410        break;
67411      }else{
67412        nFrag += (x>>16) - (prev&0xffff) - 1;
67413        prev = x;
67414      }
67415    }
67416    nFrag += usableSize - (prev&0xffff) - 1;
67417    /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
67418    ** is stored in the fifth field of the b-tree page header.
67419    ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
67420    ** number of fragmented free bytes within the cell content area.
67421    */
67422    if( heap[0]==0 && nFrag!=data[hdr+7] ){
67423      checkAppendMsg(pCheck,
67424          "Fragmentation of %d bytes reported as %d on page %d",
67425          nFrag, data[hdr+7], iPage);
67426    }
67427  }
67428
67429end_of_check:
67430  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
67431  releasePage(pPage);
67432  pCheck->zPfx = saved_zPfx;
67433  pCheck->v1 = saved_v1;
67434  pCheck->v2 = saved_v2;
67435  return depth+1;
67436}
67437#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67438
67439#ifndef SQLITE_OMIT_INTEGRITY_CHECK
67440/*
67441** This routine does a complete check of the given BTree file.  aRoot[] is
67442** an array of pages numbers were each page number is the root page of
67443** a table.  nRoot is the number of entries in aRoot.
67444**
67445** A read-only or read-write transaction must be opened before calling
67446** this function.
67447**
67448** Write the number of error seen in *pnErr.  Except for some memory
67449** allocation errors,  an error message held in memory obtained from
67450** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
67451** returned.  If a memory allocation error occurs, NULL is returned.
67452*/
67453SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
67454  Btree *p,     /* The btree to be checked */
67455  int *aRoot,   /* An array of root pages numbers for individual trees */
67456  int nRoot,    /* Number of entries in aRoot[] */
67457  int mxErr,    /* Stop reporting errors after this many */
67458  int *pnErr    /* Write number of errors seen to this variable */
67459){
67460  Pgno i;
67461  IntegrityCk sCheck;
67462  BtShared *pBt = p->pBt;
67463  int savedDbFlags = pBt->db->flags;
67464  char zErr[100];
67465  VVA_ONLY( int nRef );
67466
67467  sqlite3BtreeEnter(p);
67468  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
67469  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
67470  assert( nRef>=0 );
67471  sCheck.pBt = pBt;
67472  sCheck.pPager = pBt->pPager;
67473  sCheck.nPage = btreePagecount(sCheck.pBt);
67474  sCheck.mxErr = mxErr;
67475  sCheck.nErr = 0;
67476  sCheck.mallocFailed = 0;
67477  sCheck.zPfx = 0;
67478  sCheck.v1 = 0;
67479  sCheck.v2 = 0;
67480  sCheck.aPgRef = 0;
67481  sCheck.heap = 0;
67482  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
67483  sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
67484  if( sCheck.nPage==0 ){
67485    goto integrity_ck_cleanup;
67486  }
67487
67488  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
67489  if( !sCheck.aPgRef ){
67490    sCheck.mallocFailed = 1;
67491    goto integrity_ck_cleanup;
67492  }
67493  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
67494  if( sCheck.heap==0 ){
67495    sCheck.mallocFailed = 1;
67496    goto integrity_ck_cleanup;
67497  }
67498
67499  i = PENDING_BYTE_PAGE(pBt);
67500  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
67501
67502  /* Check the integrity of the freelist
67503  */
67504  sCheck.zPfx = "Main freelist: ";
67505  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
67506            get4byte(&pBt->pPage1->aData[36]));
67507  sCheck.zPfx = 0;
67508
67509  /* Check all the tables.
67510  */
67511  testcase( pBt->db->flags & SQLITE_CellSizeCk );
67512  pBt->db->flags &= ~SQLITE_CellSizeCk;
67513  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
67514    i64 notUsed;
67515    if( aRoot[i]==0 ) continue;
67516#ifndef SQLITE_OMIT_AUTOVACUUM
67517    if( pBt->autoVacuum && aRoot[i]>1 ){
67518      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
67519    }
67520#endif
67521    checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
67522  }
67523  pBt->db->flags = savedDbFlags;
67524
67525  /* Make sure every page in the file is referenced
67526  */
67527  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
67528#ifdef SQLITE_OMIT_AUTOVACUUM
67529    if( getPageReferenced(&sCheck, i)==0 ){
67530      checkAppendMsg(&sCheck, "Page %d is never used", i);
67531    }
67532#else
67533    /* If the database supports auto-vacuum, make sure no tables contain
67534    ** references to pointer-map pages.
67535    */
67536    if( getPageReferenced(&sCheck, i)==0 &&
67537       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
67538      checkAppendMsg(&sCheck, "Page %d is never used", i);
67539    }
67540    if( getPageReferenced(&sCheck, i)!=0 &&
67541       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
67542      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
67543    }
67544#endif
67545  }
67546
67547  /* Clean  up and report errors.
67548  */
67549integrity_ck_cleanup:
67550  sqlite3PageFree(sCheck.heap);
67551  sqlite3_free(sCheck.aPgRef);
67552  if( sCheck.mallocFailed ){
67553    sqlite3StrAccumReset(&sCheck.errMsg);
67554    sCheck.nErr++;
67555  }
67556  *pnErr = sCheck.nErr;
67557  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
67558  /* Make sure this analysis did not leave any unref() pages. */
67559  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
67560  sqlite3BtreeLeave(p);
67561  return sqlite3StrAccumFinish(&sCheck.errMsg);
67562}
67563#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67564
67565/*
67566** Return the full pathname of the underlying database file.  Return
67567** an empty string if the database is in-memory or a TEMP database.
67568**
67569** The pager filename is invariant as long as the pager is
67570** open so it is safe to access without the BtShared mutex.
67571*/
67572SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
67573  assert( p->pBt->pPager!=0 );
67574  return sqlite3PagerFilename(p->pBt->pPager, 1);
67575}
67576
67577/*
67578** Return the pathname of the journal file for this database. The return
67579** value of this routine is the same regardless of whether the journal file
67580** has been created or not.
67581**
67582** The pager journal filename is invariant as long as the pager is
67583** open so it is safe to access without the BtShared mutex.
67584*/
67585SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
67586  assert( p->pBt->pPager!=0 );
67587  return sqlite3PagerJournalname(p->pBt->pPager);
67588}
67589
67590/*
67591** Return non-zero if a transaction is active.
67592*/
67593SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
67594  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
67595  return (p && (p->inTrans==TRANS_WRITE));
67596}
67597
67598#ifndef SQLITE_OMIT_WAL
67599/*
67600** Run a checkpoint on the Btree passed as the first argument.
67601**
67602** Return SQLITE_LOCKED if this or any other connection has an open
67603** transaction on the shared-cache the argument Btree is connected to.
67604**
67605** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
67606*/
67607SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
67608  int rc = SQLITE_OK;
67609  if( p ){
67610    BtShared *pBt = p->pBt;
67611    sqlite3BtreeEnter(p);
67612    if( pBt->inTransaction!=TRANS_NONE ){
67613      rc = SQLITE_LOCKED;
67614    }else{
67615      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
67616    }
67617    sqlite3BtreeLeave(p);
67618  }
67619  return rc;
67620}
67621#endif
67622
67623/*
67624** Return non-zero if a read (or write) transaction is active.
67625*/
67626SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
67627  assert( p );
67628  assert( sqlite3_mutex_held(p->db->mutex) );
67629  return p->inTrans!=TRANS_NONE;
67630}
67631
67632SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
67633  assert( p );
67634  assert( sqlite3_mutex_held(p->db->mutex) );
67635  return p->nBackup!=0;
67636}
67637
67638/*
67639** This function returns a pointer to a blob of memory associated with
67640** a single shared-btree. The memory is used by client code for its own
67641** purposes (for example, to store a high-level schema associated with
67642** the shared-btree). The btree layer manages reference counting issues.
67643**
67644** The first time this is called on a shared-btree, nBytes bytes of memory
67645** are allocated, zeroed, and returned to the caller. For each subsequent
67646** call the nBytes parameter is ignored and a pointer to the same blob
67647** of memory returned.
67648**
67649** If the nBytes parameter is 0 and the blob of memory has not yet been
67650** allocated, a null pointer is returned. If the blob has already been
67651** allocated, it is returned as normal.
67652**
67653** Just before the shared-btree is closed, the function passed as the
67654** xFree argument when the memory allocation was made is invoked on the
67655** blob of allocated memory. The xFree function should not call sqlite3_free()
67656** on the memory, the btree layer does that.
67657*/
67658SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
67659  BtShared *pBt = p->pBt;
67660  sqlite3BtreeEnter(p);
67661  if( !pBt->pSchema && nBytes ){
67662    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
67663    pBt->xFreeSchema = xFree;
67664  }
67665  sqlite3BtreeLeave(p);
67666  return pBt->pSchema;
67667}
67668
67669/*
67670** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
67671** btree as the argument handle holds an exclusive lock on the
67672** sqlite_master table. Otherwise SQLITE_OK.
67673*/
67674SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
67675  int rc;
67676  assert( sqlite3_mutex_held(p->db->mutex) );
67677  sqlite3BtreeEnter(p);
67678  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
67679  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
67680  sqlite3BtreeLeave(p);
67681  return rc;
67682}
67683
67684
67685#ifndef SQLITE_OMIT_SHARED_CACHE
67686/*
67687** Obtain a lock on the table whose root page is iTab.  The
67688** lock is a write lock if isWritelock is true or a read lock
67689** if it is false.
67690*/
67691SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
67692  int rc = SQLITE_OK;
67693  assert( p->inTrans!=TRANS_NONE );
67694  if( p->sharable ){
67695    u8 lockType = READ_LOCK + isWriteLock;
67696    assert( READ_LOCK+1==WRITE_LOCK );
67697    assert( isWriteLock==0 || isWriteLock==1 );
67698
67699    sqlite3BtreeEnter(p);
67700    rc = querySharedCacheTableLock(p, iTab, lockType);
67701    if( rc==SQLITE_OK ){
67702      rc = setSharedCacheTableLock(p, iTab, lockType);
67703    }
67704    sqlite3BtreeLeave(p);
67705  }
67706  return rc;
67707}
67708#endif
67709
67710#ifndef SQLITE_OMIT_INCRBLOB
67711/*
67712** Argument pCsr must be a cursor opened for writing on an
67713** INTKEY table currently pointing at a valid table entry.
67714** This function modifies the data stored as part of that entry.
67715**
67716** Only the data content may only be modified, it is not possible to
67717** change the length of the data stored. If this function is called with
67718** parameters that attempt to write past the end of the existing data,
67719** no modifications are made and SQLITE_CORRUPT is returned.
67720*/
67721SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
67722  int rc;
67723  assert( cursorOwnsBtShared(pCsr) );
67724  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
67725  assert( pCsr->curFlags & BTCF_Incrblob );
67726
67727  rc = restoreCursorPosition(pCsr);
67728  if( rc!=SQLITE_OK ){
67729    return rc;
67730  }
67731  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
67732  if( pCsr->eState!=CURSOR_VALID ){
67733    return SQLITE_ABORT;
67734  }
67735
67736  /* Save the positions of all other cursors open on this table. This is
67737  ** required in case any of them are holding references to an xFetch
67738  ** version of the b-tree page modified by the accessPayload call below.
67739  **
67740  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
67741  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
67742  ** saveAllCursors can only return SQLITE_OK.
67743  */
67744  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
67745  assert( rc==SQLITE_OK );
67746
67747  /* Check some assumptions:
67748  **   (a) the cursor is open for writing,
67749  **   (b) there is a read/write transaction open,
67750  **   (c) the connection holds a write-lock on the table (if required),
67751  **   (d) there are no conflicting read-locks, and
67752  **   (e) the cursor points at a valid row of an intKey table.
67753  */
67754  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
67755    return SQLITE_READONLY;
67756  }
67757  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
67758              && pCsr->pBt->inTransaction==TRANS_WRITE );
67759  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
67760  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
67761  assert( pCsr->apPage[pCsr->iPage]->intKey );
67762
67763  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
67764}
67765
67766/*
67767** Mark this cursor as an incremental blob cursor.
67768*/
67769SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
67770  pCur->curFlags |= BTCF_Incrblob;
67771  pCur->pBtree->hasIncrblobCur = 1;
67772}
67773#endif
67774
67775/*
67776** Set both the "read version" (single byte at byte offset 18) and
67777** "write version" (single byte at byte offset 19) fields in the database
67778** header to iVersion.
67779*/
67780SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
67781  BtShared *pBt = pBtree->pBt;
67782  int rc;                         /* Return code */
67783
67784  assert( iVersion==1 || iVersion==2 );
67785
67786  /* If setting the version fields to 1, do not automatically open the
67787  ** WAL connection, even if the version fields are currently set to 2.
67788  */
67789  pBt->btsFlags &= ~BTS_NO_WAL;
67790  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
67791
67792  rc = sqlite3BtreeBeginTrans(pBtree, 0);
67793  if( rc==SQLITE_OK ){
67794    u8 *aData = pBt->pPage1->aData;
67795    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
67796      rc = sqlite3BtreeBeginTrans(pBtree, 2);
67797      if( rc==SQLITE_OK ){
67798        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67799        if( rc==SQLITE_OK ){
67800          aData[18] = (u8)iVersion;
67801          aData[19] = (u8)iVersion;
67802        }
67803      }
67804    }
67805  }
67806
67807  pBt->btsFlags &= ~BTS_NO_WAL;
67808  return rc;
67809}
67810
67811/*
67812** Return true if the cursor has a hint specified.  This routine is
67813** only used from within assert() statements
67814*/
67815SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
67816  return (pCsr->hints & mask)!=0;
67817}
67818
67819/*
67820** Return true if the given Btree is read-only.
67821*/
67822SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
67823  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
67824}
67825
67826/*
67827** Return the size of the header added to each page by this module.
67828*/
67829SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
67830
67831#if !defined(SQLITE_OMIT_SHARED_CACHE)
67832/*
67833** Return true if the Btree passed as the only argument is sharable.
67834*/
67835SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
67836  return p->sharable;
67837}
67838
67839/*
67840** Return the number of connections to the BtShared object accessed by
67841** the Btree handle passed as the only argument. For private caches
67842** this is always 1. For shared caches it may be 1 or greater.
67843*/
67844SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
67845  testcase( p->sharable );
67846  return p->pBt->nRef;
67847}
67848#endif
67849
67850/************** End of btree.c ***********************************************/
67851/************** Begin file backup.c ******************************************/
67852/*
67853** 2009 January 28
67854**
67855** The author disclaims copyright to this source code.  In place of
67856** a legal notice, here is a blessing:
67857**
67858**    May you do good and not evil.
67859**    May you find forgiveness for yourself and forgive others.
67860**    May you share freely, never taking more than you give.
67861**
67862*************************************************************************
67863** This file contains the implementation of the sqlite3_backup_XXX()
67864** API functions and the related features.
67865*/
67866/* #include "sqliteInt.h" */
67867/* #include "btreeInt.h" */
67868
67869/*
67870** Structure allocated for each backup operation.
67871*/
67872struct sqlite3_backup {
67873  sqlite3* pDestDb;        /* Destination database handle */
67874  Btree *pDest;            /* Destination b-tree file */
67875  u32 iDestSchema;         /* Original schema cookie in destination */
67876  int bDestLocked;         /* True once a write-transaction is open on pDest */
67877
67878  Pgno iNext;              /* Page number of the next source page to copy */
67879  sqlite3* pSrcDb;         /* Source database handle */
67880  Btree *pSrc;             /* Source b-tree file */
67881
67882  int rc;                  /* Backup process error code */
67883
67884  /* These two variables are set by every call to backup_step(). They are
67885  ** read by calls to backup_remaining() and backup_pagecount().
67886  */
67887  Pgno nRemaining;         /* Number of pages left to copy */
67888  Pgno nPagecount;         /* Total number of pages to copy */
67889
67890  int isAttached;          /* True once backup has been registered with pager */
67891  sqlite3_backup *pNext;   /* Next backup associated with source pager */
67892};
67893
67894/*
67895** THREAD SAFETY NOTES:
67896**
67897**   Once it has been created using backup_init(), a single sqlite3_backup
67898**   structure may be accessed via two groups of thread-safe entry points:
67899**
67900**     * Via the sqlite3_backup_XXX() API function backup_step() and
67901**       backup_finish(). Both these functions obtain the source database
67902**       handle mutex and the mutex associated with the source BtShared
67903**       structure, in that order.
67904**
67905**     * Via the BackupUpdate() and BackupRestart() functions, which are
67906**       invoked by the pager layer to report various state changes in
67907**       the page cache associated with the source database. The mutex
67908**       associated with the source database BtShared structure will always
67909**       be held when either of these functions are invoked.
67910**
67911**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
67912**   backup_pagecount() are not thread-safe functions. If they are called
67913**   while some other thread is calling backup_step() or backup_finish(),
67914**   the values returned may be invalid. There is no way for a call to
67915**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
67916**   or backup_pagecount().
67917**
67918**   Depending on the SQLite configuration, the database handles and/or
67919**   the Btree objects may have their own mutexes that require locking.
67920**   Non-sharable Btrees (in-memory databases for example), do not have
67921**   associated mutexes.
67922*/
67923
67924/*
67925** Return a pointer corresponding to database zDb (i.e. "main", "temp")
67926** in connection handle pDb. If such a database cannot be found, return
67927** a NULL pointer and write an error message to pErrorDb.
67928**
67929** If the "temp" database is requested, it may need to be opened by this
67930** function. If an error occurs while doing so, return 0 and write an
67931** error message to pErrorDb.
67932*/
67933static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
67934  int i = sqlite3FindDbName(pDb, zDb);
67935
67936  if( i==1 ){
67937    Parse *pParse;
67938    int rc = 0;
67939    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
67940    if( pParse==0 ){
67941      sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
67942      rc = SQLITE_NOMEM_BKPT;
67943    }else{
67944      pParse->db = pDb;
67945      if( sqlite3OpenTempDatabase(pParse) ){
67946        sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
67947        rc = SQLITE_ERROR;
67948      }
67949      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
67950      sqlite3ParserReset(pParse);
67951      sqlite3StackFree(pErrorDb, pParse);
67952    }
67953    if( rc ){
67954      return 0;
67955    }
67956  }
67957
67958  if( i<0 ){
67959    sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
67960    return 0;
67961  }
67962
67963  return pDb->aDb[i].pBt;
67964}
67965
67966/*
67967** Attempt to set the page size of the destination to match the page size
67968** of the source.
67969*/
67970static int setDestPgsz(sqlite3_backup *p){
67971  int rc;
67972  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
67973  return rc;
67974}
67975
67976/*
67977** Check that there is no open read-transaction on the b-tree passed as the
67978** second argument. If there is not, return SQLITE_OK. Otherwise, if there
67979** is an open read-transaction, return SQLITE_ERROR and leave an error
67980** message in database handle db.
67981*/
67982static int checkReadTransaction(sqlite3 *db, Btree *p){
67983  if( sqlite3BtreeIsInReadTrans(p) ){
67984    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
67985    return SQLITE_ERROR;
67986  }
67987  return SQLITE_OK;
67988}
67989
67990/*
67991** Create an sqlite3_backup process to copy the contents of zSrcDb from
67992** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
67993** a pointer to the new sqlite3_backup object.
67994**
67995** If an error occurs, NULL is returned and an error code and error message
67996** stored in database handle pDestDb.
67997*/
67998SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
67999  sqlite3* pDestDb,                     /* Database to write to */
68000  const char *zDestDb,                  /* Name of database within pDestDb */
68001  sqlite3* pSrcDb,                      /* Database connection to read from */
68002  const char *zSrcDb                    /* Name of database within pSrcDb */
68003){
68004  sqlite3_backup *p;                    /* Value to return */
68005
68006#ifdef SQLITE_ENABLE_API_ARMOR
68007  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
68008    (void)SQLITE_MISUSE_BKPT;
68009    return 0;
68010  }
68011#endif
68012
68013  /* Lock the source database handle. The destination database
68014  ** handle is not locked in this routine, but it is locked in
68015  ** sqlite3_backup_step(). The user is required to ensure that no
68016  ** other thread accesses the destination handle for the duration
68017  ** of the backup operation.  Any attempt to use the destination
68018  ** database connection while a backup is in progress may cause
68019  ** a malfunction or a deadlock.
68020  */
68021  sqlite3_mutex_enter(pSrcDb->mutex);
68022  sqlite3_mutex_enter(pDestDb->mutex);
68023
68024  if( pSrcDb==pDestDb ){
68025    sqlite3ErrorWithMsg(
68026        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
68027    );
68028    p = 0;
68029  }else {
68030    /* Allocate space for a new sqlite3_backup object...
68031    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68032    ** call to sqlite3_backup_init() and is destroyed by a call to
68033    ** sqlite3_backup_finish(). */
68034    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
68035    if( !p ){
68036      sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
68037    }
68038  }
68039
68040  /* If the allocation succeeded, populate the new object. */
68041  if( p ){
68042    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
68043    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
68044    p->pDestDb = pDestDb;
68045    p->pSrcDb = pSrcDb;
68046    p->iNext = 1;
68047    p->isAttached = 0;
68048
68049    if( 0==p->pSrc || 0==p->pDest
68050     || setDestPgsz(p)==SQLITE_NOMEM
68051     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
68052     ){
68053      /* One (or both) of the named databases did not exist or an OOM
68054      ** error was hit. Or there is a transaction open on the destination
68055      ** database. The error has already been written into the pDestDb
68056      ** handle. All that is left to do here is free the sqlite3_backup
68057      ** structure.  */
68058      sqlite3_free(p);
68059      p = 0;
68060    }
68061  }
68062  if( p ){
68063    p->pSrc->nBackup++;
68064  }
68065
68066  sqlite3_mutex_leave(pDestDb->mutex);
68067  sqlite3_mutex_leave(pSrcDb->mutex);
68068  return p;
68069}
68070
68071/*
68072** Argument rc is an SQLite error code. Return true if this error is
68073** considered fatal if encountered during a backup operation. All errors
68074** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
68075*/
68076static int isFatalError(int rc){
68077  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
68078}
68079
68080/*
68081** Parameter zSrcData points to a buffer containing the data for
68082** page iSrcPg from the source database. Copy this data into the
68083** destination database.
68084*/
68085static int backupOnePage(
68086  sqlite3_backup *p,              /* Backup handle */
68087  Pgno iSrcPg,                    /* Source database page to backup */
68088  const u8 *zSrcData,             /* Source database page data */
68089  int bUpdate                     /* True for an update, false otherwise */
68090){
68091  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
68092  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
68093  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
68094  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
68095  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
68096#ifdef SQLITE_HAS_CODEC
68097  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
68098  ** guaranteed that the shared-mutex is held by this thread, handle
68099  ** p->pSrc may not actually be the owner.  */
68100  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
68101  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
68102#endif
68103  int rc = SQLITE_OK;
68104  i64 iOff;
68105
68106  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
68107  assert( p->bDestLocked );
68108  assert( !isFatalError(p->rc) );
68109  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
68110  assert( zSrcData );
68111
68112  /* Catch the case where the destination is an in-memory database and the
68113  ** page sizes of the source and destination differ.
68114  */
68115  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
68116    rc = SQLITE_READONLY;
68117  }
68118
68119#ifdef SQLITE_HAS_CODEC
68120  /* Backup is not possible if the page size of the destination is changing
68121  ** and a codec is in use.
68122  */
68123  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
68124    rc = SQLITE_READONLY;
68125  }
68126
68127  /* Backup is not possible if the number of bytes of reserve space differ
68128  ** between source and destination.  If there is a difference, try to
68129  ** fix the destination to agree with the source.  If that is not possible,
68130  ** then the backup cannot proceed.
68131  */
68132  if( nSrcReserve!=nDestReserve ){
68133    u32 newPgsz = nSrcPgsz;
68134    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
68135    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
68136  }
68137#endif
68138
68139  /* This loop runs once for each destination page spanned by the source
68140  ** page. For each iteration, variable iOff is set to the byte offset
68141  ** of the destination page.
68142  */
68143  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
68144    DbPage *pDestPg = 0;
68145    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
68146    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
68147    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
68148     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
68149    ){
68150      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
68151      u8 *zDestData = sqlite3PagerGetData(pDestPg);
68152      u8 *zOut = &zDestData[iOff%nDestPgsz];
68153
68154      /* Copy the data from the source page into the destination page.
68155      ** Then clear the Btree layer MemPage.isInit flag. Both this module
68156      ** and the pager code use this trick (clearing the first byte
68157      ** of the page 'extra' space to invalidate the Btree layers
68158      ** cached parse of the page). MemPage.isInit is marked
68159      ** "MUST BE FIRST" for this purpose.
68160      */
68161      memcpy(zOut, zIn, nCopy);
68162      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
68163      if( iOff==0 && bUpdate==0 ){
68164        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
68165      }
68166    }
68167    sqlite3PagerUnref(pDestPg);
68168  }
68169
68170  return rc;
68171}
68172
68173/*
68174** If pFile is currently larger than iSize bytes, then truncate it to
68175** exactly iSize bytes. If pFile is not larger than iSize bytes, then
68176** this function is a no-op.
68177**
68178** Return SQLITE_OK if everything is successful, or an SQLite error
68179** code if an error occurs.
68180*/
68181static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
68182  i64 iCurrent;
68183  int rc = sqlite3OsFileSize(pFile, &iCurrent);
68184  if( rc==SQLITE_OK && iCurrent>iSize ){
68185    rc = sqlite3OsTruncate(pFile, iSize);
68186  }
68187  return rc;
68188}
68189
68190/*
68191** Register this backup object with the associated source pager for
68192** callbacks when pages are changed or the cache invalidated.
68193*/
68194static void attachBackupObject(sqlite3_backup *p){
68195  sqlite3_backup **pp;
68196  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
68197  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68198  p->pNext = *pp;
68199  *pp = p;
68200  p->isAttached = 1;
68201}
68202
68203/*
68204** Copy nPage pages from the source b-tree to the destination.
68205*/
68206SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
68207  int rc;
68208  int destMode;       /* Destination journal mode */
68209  int pgszSrc = 0;    /* Source page size */
68210  int pgszDest = 0;   /* Destination page size */
68211
68212#ifdef SQLITE_ENABLE_API_ARMOR
68213  if( p==0 ) return SQLITE_MISUSE_BKPT;
68214#endif
68215  sqlite3_mutex_enter(p->pSrcDb->mutex);
68216  sqlite3BtreeEnter(p->pSrc);
68217  if( p->pDestDb ){
68218    sqlite3_mutex_enter(p->pDestDb->mutex);
68219  }
68220
68221  rc = p->rc;
68222  if( !isFatalError(rc) ){
68223    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
68224    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
68225    int ii;                            /* Iterator variable */
68226    int nSrcPage = -1;                 /* Size of source db in pages */
68227    int bCloseTrans = 0;               /* True if src db requires unlocking */
68228
68229    /* If the source pager is currently in a write-transaction, return
68230    ** SQLITE_BUSY immediately.
68231    */
68232    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
68233      rc = SQLITE_BUSY;
68234    }else{
68235      rc = SQLITE_OK;
68236    }
68237
68238    /* Lock the destination database, if it is not locked already. */
68239    if( SQLITE_OK==rc && p->bDestLocked==0
68240     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
68241    ){
68242      p->bDestLocked = 1;
68243      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
68244    }
68245
68246    /* If there is no open read-transaction on the source database, open
68247    ** one now. If a transaction is opened here, then it will be closed
68248    ** before this function exits.
68249    */
68250    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
68251      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
68252      bCloseTrans = 1;
68253    }
68254
68255    /* Do not allow backup if the destination database is in WAL mode
68256    ** and the page sizes are different between source and destination */
68257    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
68258    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
68259    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
68260    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
68261      rc = SQLITE_READONLY;
68262    }
68263
68264    /* Now that there is a read-lock on the source database, query the
68265    ** source pager for the number of pages in the database.
68266    */
68267    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
68268    assert( nSrcPage>=0 );
68269    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
68270      const Pgno iSrcPg = p->iNext;                 /* Source page number */
68271      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
68272        DbPage *pSrcPg;                             /* Source page object */
68273        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
68274        if( rc==SQLITE_OK ){
68275          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
68276          sqlite3PagerUnref(pSrcPg);
68277        }
68278      }
68279      p->iNext++;
68280    }
68281    if( rc==SQLITE_OK ){
68282      p->nPagecount = nSrcPage;
68283      p->nRemaining = nSrcPage+1-p->iNext;
68284      if( p->iNext>(Pgno)nSrcPage ){
68285        rc = SQLITE_DONE;
68286      }else if( !p->isAttached ){
68287        attachBackupObject(p);
68288      }
68289    }
68290
68291    /* Update the schema version field in the destination database. This
68292    ** is to make sure that the schema-version really does change in
68293    ** the case where the source and destination databases have the
68294    ** same schema version.
68295    */
68296    if( rc==SQLITE_DONE ){
68297      if( nSrcPage==0 ){
68298        rc = sqlite3BtreeNewDb(p->pDest);
68299        nSrcPage = 1;
68300      }
68301      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
68302        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
68303      }
68304      if( rc==SQLITE_OK ){
68305        if( p->pDestDb ){
68306          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
68307        }
68308        if( destMode==PAGER_JOURNALMODE_WAL ){
68309          rc = sqlite3BtreeSetVersion(p->pDest, 2);
68310        }
68311      }
68312      if( rc==SQLITE_OK ){
68313        int nDestTruncate;
68314        /* Set nDestTruncate to the final number of pages in the destination
68315        ** database. The complication here is that the destination page
68316        ** size may be different to the source page size.
68317        **
68318        ** If the source page size is smaller than the destination page size,
68319        ** round up. In this case the call to sqlite3OsTruncate() below will
68320        ** fix the size of the file. However it is important to call
68321        ** sqlite3PagerTruncateImage() here so that any pages in the
68322        ** destination file that lie beyond the nDestTruncate page mark are
68323        ** journalled by PagerCommitPhaseOne() before they are destroyed
68324        ** by the file truncation.
68325        */
68326        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
68327        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
68328        if( pgszSrc<pgszDest ){
68329          int ratio = pgszDest/pgszSrc;
68330          nDestTruncate = (nSrcPage+ratio-1)/ratio;
68331          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
68332            nDestTruncate--;
68333          }
68334        }else{
68335          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
68336        }
68337        assert( nDestTruncate>0 );
68338
68339        if( pgszSrc<pgszDest ){
68340          /* If the source page-size is smaller than the destination page-size,
68341          ** two extra things may need to happen:
68342          **
68343          **   * The destination may need to be truncated, and
68344          **
68345          **   * Data stored on the pages immediately following the
68346          **     pending-byte page in the source database may need to be
68347          **     copied into the destination database.
68348          */
68349          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
68350          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
68351          Pgno iPg;
68352          int nDstPage;
68353          i64 iOff;
68354          i64 iEnd;
68355
68356          assert( pFile );
68357          assert( nDestTruncate==0
68358              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
68359                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
68360             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
68361          ));
68362
68363          /* This block ensures that all data required to recreate the original
68364          ** database has been stored in the journal for pDestPager and the
68365          ** journal synced to disk. So at this point we may safely modify
68366          ** the database file in any way, knowing that if a power failure
68367          ** occurs, the original database will be reconstructed from the
68368          ** journal file.  */
68369          sqlite3PagerPagecount(pDestPager, &nDstPage);
68370          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
68371            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
68372              DbPage *pPg;
68373              rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
68374              if( rc==SQLITE_OK ){
68375                rc = sqlite3PagerWrite(pPg);
68376                sqlite3PagerUnref(pPg);
68377              }
68378            }
68379          }
68380          if( rc==SQLITE_OK ){
68381            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
68382          }
68383
68384          /* Write the extra pages and truncate the database file as required */
68385          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
68386          for(
68387            iOff=PENDING_BYTE+pgszSrc;
68388            rc==SQLITE_OK && iOff<iEnd;
68389            iOff+=pgszSrc
68390          ){
68391            PgHdr *pSrcPg = 0;
68392            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
68393            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
68394            if( rc==SQLITE_OK ){
68395              u8 *zData = sqlite3PagerGetData(pSrcPg);
68396              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
68397            }
68398            sqlite3PagerUnref(pSrcPg);
68399          }
68400          if( rc==SQLITE_OK ){
68401            rc = backupTruncateFile(pFile, iSize);
68402          }
68403
68404          /* Sync the database file to disk. */
68405          if( rc==SQLITE_OK ){
68406            rc = sqlite3PagerSync(pDestPager, 0);
68407          }
68408        }else{
68409          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
68410          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
68411        }
68412
68413        /* Finish committing the transaction to the destination database. */
68414        if( SQLITE_OK==rc
68415         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
68416        ){
68417          rc = SQLITE_DONE;
68418        }
68419      }
68420    }
68421
68422    /* If bCloseTrans is true, then this function opened a read transaction
68423    ** on the source database. Close the read transaction here. There is
68424    ** no need to check the return values of the btree methods here, as
68425    ** "committing" a read-only transaction cannot fail.
68426    */
68427    if( bCloseTrans ){
68428      TESTONLY( int rc2 );
68429      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
68430      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
68431      assert( rc2==SQLITE_OK );
68432    }
68433
68434    if( rc==SQLITE_IOERR_NOMEM ){
68435      rc = SQLITE_NOMEM_BKPT;
68436    }
68437    p->rc = rc;
68438  }
68439  if( p->pDestDb ){
68440    sqlite3_mutex_leave(p->pDestDb->mutex);
68441  }
68442  sqlite3BtreeLeave(p->pSrc);
68443  sqlite3_mutex_leave(p->pSrcDb->mutex);
68444  return rc;
68445}
68446
68447/*
68448** Release all resources associated with an sqlite3_backup* handle.
68449*/
68450SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
68451  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
68452  sqlite3 *pSrcDb;                     /* Source database connection */
68453  int rc;                              /* Value to return */
68454
68455  /* Enter the mutexes */
68456  if( p==0 ) return SQLITE_OK;
68457  pSrcDb = p->pSrcDb;
68458  sqlite3_mutex_enter(pSrcDb->mutex);
68459  sqlite3BtreeEnter(p->pSrc);
68460  if( p->pDestDb ){
68461    sqlite3_mutex_enter(p->pDestDb->mutex);
68462  }
68463
68464  /* Detach this backup from the source pager. */
68465  if( p->pDestDb ){
68466    p->pSrc->nBackup--;
68467  }
68468  if( p->isAttached ){
68469    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68470    while( *pp!=p ){
68471      pp = &(*pp)->pNext;
68472    }
68473    *pp = p->pNext;
68474  }
68475
68476  /* If a transaction is still open on the Btree, roll it back. */
68477  sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
68478
68479  /* Set the error code of the destination database handle. */
68480  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
68481  if( p->pDestDb ){
68482    sqlite3Error(p->pDestDb, rc);
68483
68484    /* Exit the mutexes and free the backup context structure. */
68485    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
68486  }
68487  sqlite3BtreeLeave(p->pSrc);
68488  if( p->pDestDb ){
68489    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68490    ** call to sqlite3_backup_init() and is destroyed by a call to
68491    ** sqlite3_backup_finish(). */
68492    sqlite3_free(p);
68493  }
68494  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
68495  return rc;
68496}
68497
68498/*
68499** Return the number of pages still to be backed up as of the most recent
68500** call to sqlite3_backup_step().
68501*/
68502SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
68503#ifdef SQLITE_ENABLE_API_ARMOR
68504  if( p==0 ){
68505    (void)SQLITE_MISUSE_BKPT;
68506    return 0;
68507  }
68508#endif
68509  return p->nRemaining;
68510}
68511
68512/*
68513** Return the total number of pages in the source database as of the most
68514** recent call to sqlite3_backup_step().
68515*/
68516SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
68517#ifdef SQLITE_ENABLE_API_ARMOR
68518  if( p==0 ){
68519    (void)SQLITE_MISUSE_BKPT;
68520    return 0;
68521  }
68522#endif
68523  return p->nPagecount;
68524}
68525
68526/*
68527** This function is called after the contents of page iPage of the
68528** source database have been modified. If page iPage has already been
68529** copied into the destination database, then the data written to the
68530** destination is now invalidated. The destination copy of iPage needs
68531** to be updated with the new data before the backup operation is
68532** complete.
68533**
68534** It is assumed that the mutex associated with the BtShared object
68535** corresponding to the source database is held when this function is
68536** called.
68537*/
68538static SQLITE_NOINLINE void backupUpdate(
68539  sqlite3_backup *p,
68540  Pgno iPage,
68541  const u8 *aData
68542){
68543  assert( p!=0 );
68544  do{
68545    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68546    if( !isFatalError(p->rc) && iPage<p->iNext ){
68547      /* The backup process p has already copied page iPage. But now it
68548      ** has been modified by a transaction on the source pager. Copy
68549      ** the new data into the backup.
68550      */
68551      int rc;
68552      assert( p->pDestDb );
68553      sqlite3_mutex_enter(p->pDestDb->mutex);
68554      rc = backupOnePage(p, iPage, aData, 1);
68555      sqlite3_mutex_leave(p->pDestDb->mutex);
68556      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
68557      if( rc!=SQLITE_OK ){
68558        p->rc = rc;
68559      }
68560    }
68561  }while( (p = p->pNext)!=0 );
68562}
68563SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
68564  if( pBackup ) backupUpdate(pBackup, iPage, aData);
68565}
68566
68567/*
68568** Restart the backup process. This is called when the pager layer
68569** detects that the database has been modified by an external database
68570** connection. In this case there is no way of knowing which of the
68571** pages that have been copied into the destination database are still
68572** valid and which are not, so the entire process needs to be restarted.
68573**
68574** It is assumed that the mutex associated with the BtShared object
68575** corresponding to the source database is held when this function is
68576** called.
68577*/
68578SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
68579  sqlite3_backup *p;                   /* Iterator variable */
68580  for(p=pBackup; p; p=p->pNext){
68581    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68582    p->iNext = 1;
68583  }
68584}
68585
68586#ifndef SQLITE_OMIT_VACUUM
68587/*
68588** Copy the complete content of pBtFrom into pBtTo.  A transaction
68589** must be active for both files.
68590**
68591** The size of file pTo may be reduced by this operation. If anything
68592** goes wrong, the transaction on pTo is rolled back. If successful, the
68593** transaction is committed before returning.
68594*/
68595SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
68596  int rc;
68597  sqlite3_file *pFd;              /* File descriptor for database pTo */
68598  sqlite3_backup b;
68599  sqlite3BtreeEnter(pTo);
68600  sqlite3BtreeEnter(pFrom);
68601
68602  assert( sqlite3BtreeIsInTrans(pTo) );
68603  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
68604  if( pFd->pMethods ){
68605    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
68606    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
68607    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
68608    if( rc ) goto copy_finished;
68609  }
68610
68611  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
68612  ** to 0. This is used by the implementations of sqlite3_backup_step()
68613  ** and sqlite3_backup_finish() to detect that they are being called
68614  ** from this function, not directly by the user.
68615  */
68616  memset(&b, 0, sizeof(b));
68617  b.pSrcDb = pFrom->db;
68618  b.pSrc = pFrom;
68619  b.pDest = pTo;
68620  b.iNext = 1;
68621
68622#ifdef SQLITE_HAS_CODEC
68623  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
68624#endif
68625
68626  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
68627  ** file. By passing this as the number of pages to copy to
68628  ** sqlite3_backup_step(), we can guarantee that the copy finishes
68629  ** within a single call (unless an error occurs). The assert() statement
68630  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
68631  ** or an error code.  */
68632  sqlite3_backup_step(&b, 0x7FFFFFFF);
68633  assert( b.rc!=SQLITE_OK );
68634
68635  rc = sqlite3_backup_finish(&b);
68636  if( rc==SQLITE_OK ){
68637    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
68638  }else{
68639    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
68640  }
68641
68642  assert( sqlite3BtreeIsInTrans(pTo)==0 );
68643copy_finished:
68644  sqlite3BtreeLeave(pFrom);
68645  sqlite3BtreeLeave(pTo);
68646  return rc;
68647}
68648#endif /* SQLITE_OMIT_VACUUM */
68649
68650/************** End of backup.c **********************************************/
68651/************** Begin file vdbemem.c *****************************************/
68652/*
68653** 2004 May 26
68654**
68655** The author disclaims copyright to this source code.  In place of
68656** a legal notice, here is a blessing:
68657**
68658**    May you do good and not evil.
68659**    May you find forgiveness for yourself and forgive others.
68660**    May you share freely, never taking more than you give.
68661**
68662*************************************************************************
68663**
68664** This file contains code use to manipulate "Mem" structure.  A "Mem"
68665** stores a single value in the VDBE.  Mem is an opaque structure visible
68666** only within the VDBE.  Interface routines refer to a Mem using the
68667** name sqlite_value
68668*/
68669/* #include "sqliteInt.h" */
68670/* #include "vdbeInt.h" */
68671
68672#ifdef SQLITE_DEBUG
68673/*
68674** Check invariants on a Mem object.
68675**
68676** This routine is intended for use inside of assert() statements, like
68677** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
68678*/
68679SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
68680  /* If MEM_Dyn is set then Mem.xDel!=0.
68681  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
68682  */
68683  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
68684
68685  /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
68686  ** ensure that if Mem.szMalloc>0 then it is safe to do
68687  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
68688  ** That saves a few cycles in inner loops. */
68689  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
68690
68691  /* Cannot be both MEM_Int and MEM_Real at the same time */
68692  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
68693
68694  /* The szMalloc field holds the correct memory allocation size */
68695  assert( p->szMalloc==0
68696       || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
68697
68698  /* If p holds a string or blob, the Mem.z must point to exactly
68699  ** one of the following:
68700  **
68701  **   (1) Memory in Mem.zMalloc and managed by the Mem object
68702  **   (2) Memory to be freed using Mem.xDel
68703  **   (3) An ephemeral string or blob
68704  **   (4) A static string or blob
68705  */
68706  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
68707    assert(
68708      ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
68709      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
68710      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
68711      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
68712    );
68713  }
68714  return 1;
68715}
68716#endif
68717
68718
68719/*
68720** If pMem is an object with a valid string representation, this routine
68721** ensures the internal encoding for the string representation is
68722** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
68723**
68724** If pMem is not a string object, or the encoding of the string
68725** representation is already stored using the requested encoding, then this
68726** routine is a no-op.
68727**
68728** SQLITE_OK is returned if the conversion is successful (or not required).
68729** SQLITE_NOMEM may be returned if a malloc() fails during conversion
68730** between formats.
68731*/
68732SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
68733#ifndef SQLITE_OMIT_UTF16
68734  int rc;
68735#endif
68736  assert( (pMem->flags&MEM_RowSet)==0 );
68737  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
68738           || desiredEnc==SQLITE_UTF16BE );
68739  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
68740    return SQLITE_OK;
68741  }
68742  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68743#ifdef SQLITE_OMIT_UTF16
68744  return SQLITE_ERROR;
68745#else
68746
68747  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
68748  ** then the encoding of the value may not have changed.
68749  */
68750  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
68751  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
68752  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
68753  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
68754  return rc;
68755#endif
68756}
68757
68758/*
68759** Make sure pMem->z points to a writable allocation of at least
68760** min(n,32) bytes.
68761**
68762** If the bPreserve argument is true, then copy of the content of
68763** pMem->z into the new allocation.  pMem must be either a string or
68764** blob if bPreserve is true.  If bPreserve is false, any prior content
68765** in pMem->z is discarded.
68766*/
68767SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
68768  assert( sqlite3VdbeCheckMemInvariants(pMem) );
68769  assert( (pMem->flags&MEM_RowSet)==0 );
68770  testcase( pMem->db==0 );
68771
68772  /* If the bPreserve flag is set to true, then the memory cell must already
68773  ** contain a valid string or blob value.  */
68774  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
68775  testcase( bPreserve && pMem->z==0 );
68776
68777  assert( pMem->szMalloc==0
68778       || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
68779  if( pMem->szMalloc<n ){
68780    if( n<32 ) n = 32;
68781    if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
68782      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
68783      bPreserve = 0;
68784    }else{
68785      if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68786      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
68787    }
68788    if( pMem->zMalloc==0 ){
68789      sqlite3VdbeMemSetNull(pMem);
68790      pMem->z = 0;
68791      pMem->szMalloc = 0;
68792      return SQLITE_NOMEM_BKPT;
68793    }else{
68794      pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
68795    }
68796  }
68797
68798  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
68799    memcpy(pMem->zMalloc, pMem->z, pMem->n);
68800  }
68801  if( (pMem->flags&MEM_Dyn)!=0 ){
68802    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
68803    pMem->xDel((void *)(pMem->z));
68804  }
68805
68806  pMem->z = pMem->zMalloc;
68807  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
68808  return SQLITE_OK;
68809}
68810
68811/*
68812** Change the pMem->zMalloc allocation to be at least szNew bytes.
68813** If pMem->zMalloc already meets or exceeds the requested size, this
68814** routine is a no-op.
68815**
68816** Any prior string or blob content in the pMem object may be discarded.
68817** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
68818** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
68819** values are preserved.
68820**
68821** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
68822** if unable to complete the resizing.
68823*/
68824SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
68825  assert( szNew>0 );
68826  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
68827  if( pMem->szMalloc<szNew ){
68828    return sqlite3VdbeMemGrow(pMem, szNew, 0);
68829  }
68830  assert( (pMem->flags & MEM_Dyn)==0 );
68831  pMem->z = pMem->zMalloc;
68832  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
68833  return SQLITE_OK;
68834}
68835
68836/*
68837** Change pMem so that its MEM_Str or MEM_Blob value is stored in
68838** MEM.zMalloc, where it can be safely written.
68839**
68840** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
68841*/
68842SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
68843  int f;
68844  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68845  assert( (pMem->flags&MEM_RowSet)==0 );
68846  ExpandBlob(pMem);
68847  f = pMem->flags;
68848  if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
68849    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
68850      return SQLITE_NOMEM_BKPT;
68851    }
68852    pMem->z[pMem->n] = 0;
68853    pMem->z[pMem->n+1] = 0;
68854    pMem->flags |= MEM_Term;
68855  }
68856  pMem->flags &= ~MEM_Ephem;
68857#ifdef SQLITE_DEBUG
68858  pMem->pScopyFrom = 0;
68859#endif
68860
68861  return SQLITE_OK;
68862}
68863
68864/*
68865** If the given Mem* has a zero-filled tail, turn it into an ordinary
68866** blob stored in dynamically allocated space.
68867*/
68868#ifndef SQLITE_OMIT_INCRBLOB
68869SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
68870  if( pMem->flags & MEM_Zero ){
68871    int nByte;
68872    assert( pMem->flags&MEM_Blob );
68873    assert( (pMem->flags&MEM_RowSet)==0 );
68874    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68875
68876    /* Set nByte to the number of bytes required to store the expanded blob. */
68877    nByte = pMem->n + pMem->u.nZero;
68878    if( nByte<=0 ){
68879      nByte = 1;
68880    }
68881    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
68882      return SQLITE_NOMEM_BKPT;
68883    }
68884
68885    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
68886    pMem->n += pMem->u.nZero;
68887    pMem->flags &= ~(MEM_Zero|MEM_Term);
68888  }
68889  return SQLITE_OK;
68890}
68891#endif
68892
68893/*
68894** It is already known that pMem contains an unterminated string.
68895** Add the zero terminator.
68896*/
68897static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
68898  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
68899    return SQLITE_NOMEM_BKPT;
68900  }
68901  pMem->z[pMem->n] = 0;
68902  pMem->z[pMem->n+1] = 0;
68903  pMem->flags |= MEM_Term;
68904  return SQLITE_OK;
68905}
68906
68907/*
68908** Make sure the given Mem is \u0000 terminated.
68909*/
68910SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
68911  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68912  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
68913  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
68914  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
68915    return SQLITE_OK;   /* Nothing to do */
68916  }else{
68917    return vdbeMemAddTerminator(pMem);
68918  }
68919}
68920
68921/*
68922** Add MEM_Str to the set of representations for the given Mem.  Numbers
68923** are converted using sqlite3_snprintf().  Converting a BLOB to a string
68924** is a no-op.
68925**
68926** Existing representations MEM_Int and MEM_Real are invalidated if
68927** bForce is true but are retained if bForce is false.
68928**
68929** A MEM_Null value will never be passed to this function. This function is
68930** used for converting values to text for returning to the user (i.e. via
68931** sqlite3_value_text()), or for ensuring that values to be used as btree
68932** keys are strings. In the former case a NULL pointer is returned the
68933** user and the latter is an internal programming error.
68934*/
68935SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
68936  int fg = pMem->flags;
68937  const int nByte = 32;
68938
68939  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68940  assert( !(fg&MEM_Zero) );
68941  assert( !(fg&(MEM_Str|MEM_Blob)) );
68942  assert( fg&(MEM_Int|MEM_Real) );
68943  assert( (pMem->flags&MEM_RowSet)==0 );
68944  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68945
68946
68947  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
68948    return SQLITE_NOMEM_BKPT;
68949  }
68950
68951  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
68952  ** string representation of the value. Then, if the required encoding
68953  ** is UTF-16le or UTF-16be do a translation.
68954  **
68955  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
68956  */
68957  if( fg & MEM_Int ){
68958    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
68959  }else{
68960    assert( fg & MEM_Real );
68961    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
68962  }
68963  pMem->n = sqlite3Strlen30(pMem->z);
68964  pMem->enc = SQLITE_UTF8;
68965  pMem->flags |= MEM_Str|MEM_Term;
68966  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
68967  sqlite3VdbeChangeEncoding(pMem, enc);
68968  return SQLITE_OK;
68969}
68970
68971/*
68972** Memory cell pMem contains the context of an aggregate function.
68973** This routine calls the finalize method for that function.  The
68974** result of the aggregate is stored back into pMem.
68975**
68976** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
68977** otherwise.
68978*/
68979SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
68980  int rc = SQLITE_OK;
68981  if( ALWAYS(pFunc && pFunc->xFinalize) ){
68982    sqlite3_context ctx;
68983    Mem t;
68984    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
68985    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68986    memset(&ctx, 0, sizeof(ctx));
68987    memset(&t, 0, sizeof(t));
68988    t.flags = MEM_Null;
68989    t.db = pMem->db;
68990    ctx.pOut = &t;
68991    ctx.pMem = pMem;
68992    ctx.pFunc = pFunc;
68993    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
68994    assert( (pMem->flags & MEM_Dyn)==0 );
68995    if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68996    memcpy(pMem, &t, sizeof(t));
68997    rc = ctx.isError;
68998  }
68999  return rc;
69000}
69001
69002/*
69003** If the memory cell contains a value that must be freed by
69004** invoking the external callback in Mem.xDel, then this routine
69005** will free that value.  It also sets Mem.flags to MEM_Null.
69006**
69007** This is a helper routine for sqlite3VdbeMemSetNull() and
69008** for sqlite3VdbeMemRelease().  Use those other routines as the
69009** entry point for releasing Mem resources.
69010*/
69011static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
69012  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
69013  assert( VdbeMemDynamic(p) );
69014  if( p->flags&MEM_Agg ){
69015    sqlite3VdbeMemFinalize(p, p->u.pDef);
69016    assert( (p->flags & MEM_Agg)==0 );
69017    testcase( p->flags & MEM_Dyn );
69018  }
69019  if( p->flags&MEM_Dyn ){
69020    assert( (p->flags&MEM_RowSet)==0 );
69021    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
69022    p->xDel((void *)p->z);
69023  }else if( p->flags&MEM_RowSet ){
69024    sqlite3RowSetClear(p->u.pRowSet);
69025  }else if( p->flags&MEM_Frame ){
69026    VdbeFrame *pFrame = p->u.pFrame;
69027    pFrame->pParent = pFrame->v->pDelFrame;
69028    pFrame->v->pDelFrame = pFrame;
69029  }
69030  p->flags = MEM_Null;
69031}
69032
69033/*
69034** Release memory held by the Mem p, both external memory cleared
69035** by p->xDel and memory in p->zMalloc.
69036**
69037** This is a helper routine invoked by sqlite3VdbeMemRelease() in
69038** the unusual case where there really is memory in p that needs
69039** to be freed.
69040*/
69041static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
69042  if( VdbeMemDynamic(p) ){
69043    vdbeMemClearExternAndSetNull(p);
69044  }
69045  if( p->szMalloc ){
69046    sqlite3DbFree(p->db, p->zMalloc);
69047    p->szMalloc = 0;
69048  }
69049  p->z = 0;
69050}
69051
69052/*
69053** Release any memory resources held by the Mem.  Both the memory that is
69054** free by Mem.xDel and the Mem.zMalloc allocation are freed.
69055**
69056** Use this routine prior to clean up prior to abandoning a Mem, or to
69057** reset a Mem back to its minimum memory utilization.
69058**
69059** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
69060** prior to inserting new content into the Mem.
69061*/
69062SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
69063  assert( sqlite3VdbeCheckMemInvariants(p) );
69064  if( VdbeMemDynamic(p) || p->szMalloc ){
69065    vdbeMemClear(p);
69066  }
69067}
69068
69069/*
69070** Convert a 64-bit IEEE double into a 64-bit signed integer.
69071** If the double is out of range of a 64-bit signed integer then
69072** return the closest available 64-bit signed integer.
69073*/
69074static i64 doubleToInt64(double r){
69075#ifdef SQLITE_OMIT_FLOATING_POINT
69076  /* When floating-point is omitted, double and int64 are the same thing */
69077  return r;
69078#else
69079  /*
69080  ** Many compilers we encounter do not define constants for the
69081  ** minimum and maximum 64-bit integers, or they define them
69082  ** inconsistently.  And many do not understand the "LL" notation.
69083  ** So we define our own static constants here using nothing
69084  ** larger than a 32-bit integer constant.
69085  */
69086  static const i64 maxInt = LARGEST_INT64;
69087  static const i64 minInt = SMALLEST_INT64;
69088
69089  if( r<=(double)minInt ){
69090    return minInt;
69091  }else if( r>=(double)maxInt ){
69092    return maxInt;
69093  }else{
69094    return (i64)r;
69095  }
69096#endif
69097}
69098
69099/*
69100** Return some kind of integer value which is the best we can do
69101** at representing the value that *pMem describes as an integer.
69102** If pMem is an integer, then the value is exact.  If pMem is
69103** a floating-point then the value returned is the integer part.
69104** If pMem is a string or blob, then we make an attempt to convert
69105** it into an integer and return that.  If pMem represents an
69106** an SQL-NULL value, return 0.
69107**
69108** If pMem represents a string value, its encoding might be changed.
69109*/
69110SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
69111  int flags;
69112  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69113  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69114  flags = pMem->flags;
69115  if( flags & MEM_Int ){
69116    return pMem->u.i;
69117  }else if( flags & MEM_Real ){
69118    return doubleToInt64(pMem->u.r);
69119  }else if( flags & (MEM_Str|MEM_Blob) ){
69120    i64 value = 0;
69121    assert( pMem->z || pMem->n==0 );
69122    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
69123    return value;
69124  }else{
69125    return 0;
69126  }
69127}
69128
69129/*
69130** Return the best representation of pMem that we can get into a
69131** double.  If pMem is already a double or an integer, return its
69132** value.  If it is a string or blob, try to convert it to a double.
69133** If it is a NULL, return 0.0.
69134*/
69135SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
69136  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69137  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69138  if( pMem->flags & MEM_Real ){
69139    return pMem->u.r;
69140  }else if( pMem->flags & MEM_Int ){
69141    return (double)pMem->u.i;
69142  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
69143    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69144    double val = (double)0;
69145    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
69146    return val;
69147  }else{
69148    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69149    return (double)0;
69150  }
69151}
69152
69153/*
69154** The MEM structure is already a MEM_Real.  Try to also make it a
69155** MEM_Int if we can.
69156*/
69157SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
69158  i64 ix;
69159  assert( pMem->flags & MEM_Real );
69160  assert( (pMem->flags & MEM_RowSet)==0 );
69161  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69162  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69163
69164  ix = doubleToInt64(pMem->u.r);
69165
69166  /* Only mark the value as an integer if
69167  **
69168  **    (1) the round-trip conversion real->int->real is a no-op, and
69169  **    (2) The integer is neither the largest nor the smallest
69170  **        possible integer (ticket #3922)
69171  **
69172  ** The second and third terms in the following conditional enforces
69173  ** the second condition under the assumption that addition overflow causes
69174  ** values to wrap around.
69175  */
69176  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
69177    pMem->u.i = ix;
69178    MemSetTypeFlag(pMem, MEM_Int);
69179  }
69180}
69181
69182/*
69183** Convert pMem to type integer.  Invalidate any prior representations.
69184*/
69185SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
69186  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69187  assert( (pMem->flags & MEM_RowSet)==0 );
69188  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69189
69190  pMem->u.i = sqlite3VdbeIntValue(pMem);
69191  MemSetTypeFlag(pMem, MEM_Int);
69192  return SQLITE_OK;
69193}
69194
69195/*
69196** Convert pMem so that it is of type MEM_Real.
69197** Invalidate any prior representations.
69198*/
69199SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
69200  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69201  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69202
69203  pMem->u.r = sqlite3VdbeRealValue(pMem);
69204  MemSetTypeFlag(pMem, MEM_Real);
69205  return SQLITE_OK;
69206}
69207
69208/*
69209** Convert pMem so that it has types MEM_Real or MEM_Int or both.
69210** Invalidate any prior representations.
69211**
69212** Every effort is made to force the conversion, even if the input
69213** is a string that does not look completely like a number.  Convert
69214** as much of the string as we can and ignore the rest.
69215*/
69216SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
69217  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
69218    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
69219    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69220    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
69221      MemSetTypeFlag(pMem, MEM_Int);
69222    }else{
69223      pMem->u.r = sqlite3VdbeRealValue(pMem);
69224      MemSetTypeFlag(pMem, MEM_Real);
69225      sqlite3VdbeIntegerAffinity(pMem);
69226    }
69227  }
69228  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
69229  pMem->flags &= ~(MEM_Str|MEM_Blob);
69230  return SQLITE_OK;
69231}
69232
69233/*
69234** Cast the datatype of the value in pMem according to the affinity
69235** "aff".  Casting is different from applying affinity in that a cast
69236** is forced.  In other words, the value is converted into the desired
69237** affinity even if that results in loss of data.  This routine is
69238** used (for example) to implement the SQL "cast()" operator.
69239*/
69240SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
69241  if( pMem->flags & MEM_Null ) return;
69242  switch( aff ){
69243    case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
69244      if( (pMem->flags & MEM_Blob)==0 ){
69245        sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69246        assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69247        MemSetTypeFlag(pMem, MEM_Blob);
69248      }else{
69249        pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
69250      }
69251      break;
69252    }
69253    case SQLITE_AFF_NUMERIC: {
69254      sqlite3VdbeMemNumerify(pMem);
69255      break;
69256    }
69257    case SQLITE_AFF_INTEGER: {
69258      sqlite3VdbeMemIntegerify(pMem);
69259      break;
69260    }
69261    case SQLITE_AFF_REAL: {
69262      sqlite3VdbeMemRealify(pMem);
69263      break;
69264    }
69265    default: {
69266      assert( aff==SQLITE_AFF_TEXT );
69267      assert( MEM_Str==(MEM_Blob>>3) );
69268      pMem->flags |= (pMem->flags&MEM_Blob)>>3;
69269      sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69270      assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69271      pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
69272      break;
69273    }
69274  }
69275}
69276
69277/*
69278** Initialize bulk memory to be a consistent Mem object.
69279**
69280** The minimum amount of initialization feasible is performed.
69281*/
69282SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
69283  assert( (flags & ~MEM_TypeMask)==0 );
69284  pMem->flags = flags;
69285  pMem->db = db;
69286  pMem->szMalloc = 0;
69287}
69288
69289
69290/*
69291** Delete any previous value and set the value stored in *pMem to NULL.
69292**
69293** This routine calls the Mem.xDel destructor to dispose of values that
69294** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
69295** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
69296** routine to invoke the destructor and deallocates Mem.zMalloc.
69297**
69298** Use this routine to reset the Mem prior to insert a new value.
69299**
69300** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
69301*/
69302SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
69303  if( VdbeMemDynamic(pMem) ){
69304    vdbeMemClearExternAndSetNull(pMem);
69305  }else{
69306    pMem->flags = MEM_Null;
69307  }
69308}
69309SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
69310  sqlite3VdbeMemSetNull((Mem*)p);
69311}
69312
69313/*
69314** Delete any previous value and set the value to be a BLOB of length
69315** n containing all zeros.
69316*/
69317SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
69318  sqlite3VdbeMemRelease(pMem);
69319  pMem->flags = MEM_Blob|MEM_Zero;
69320  pMem->n = 0;
69321  if( n<0 ) n = 0;
69322  pMem->u.nZero = n;
69323  pMem->enc = SQLITE_UTF8;
69324  pMem->z = 0;
69325}
69326
69327/*
69328** The pMem is known to contain content that needs to be destroyed prior
69329** to a value change.  So invoke the destructor, then set the value to
69330** a 64-bit integer.
69331*/
69332static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
69333  sqlite3VdbeMemSetNull(pMem);
69334  pMem->u.i = val;
69335  pMem->flags = MEM_Int;
69336}
69337
69338/*
69339** Delete any previous value and set the value stored in *pMem to val,
69340** manifest type INTEGER.
69341*/
69342SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
69343  if( VdbeMemDynamic(pMem) ){
69344    vdbeReleaseAndSetInt64(pMem, val);
69345  }else{
69346    pMem->u.i = val;
69347    pMem->flags = MEM_Int;
69348  }
69349}
69350
69351#ifndef SQLITE_OMIT_FLOATING_POINT
69352/*
69353** Delete any previous value and set the value stored in *pMem to val,
69354** manifest type REAL.
69355*/
69356SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
69357  sqlite3VdbeMemSetNull(pMem);
69358  if( !sqlite3IsNaN(val) ){
69359    pMem->u.r = val;
69360    pMem->flags = MEM_Real;
69361  }
69362}
69363#endif
69364
69365/*
69366** Delete any previous value and set the value of pMem to be an
69367** empty boolean index.
69368*/
69369SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
69370  sqlite3 *db = pMem->db;
69371  assert( db!=0 );
69372  assert( (pMem->flags & MEM_RowSet)==0 );
69373  sqlite3VdbeMemRelease(pMem);
69374  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
69375  if( db->mallocFailed ){
69376    pMem->flags = MEM_Null;
69377    pMem->szMalloc = 0;
69378  }else{
69379    assert( pMem->zMalloc );
69380    pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
69381    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
69382    assert( pMem->u.pRowSet!=0 );
69383    pMem->flags = MEM_RowSet;
69384  }
69385}
69386
69387/*
69388** Return true if the Mem object contains a TEXT or BLOB that is
69389** too large - whose size exceeds SQLITE_MAX_LENGTH.
69390*/
69391SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
69392  assert( p->db!=0 );
69393  if( p->flags & (MEM_Str|MEM_Blob) ){
69394    int n = p->n;
69395    if( p->flags & MEM_Zero ){
69396      n += p->u.nZero;
69397    }
69398    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
69399  }
69400  return 0;
69401}
69402
69403#ifdef SQLITE_DEBUG
69404/*
69405** This routine prepares a memory cell for modification by breaking
69406** its link to a shallow copy and by marking any current shallow
69407** copies of this cell as invalid.
69408**
69409** This is used for testing and debugging only - to make sure shallow
69410** copies are not misused.
69411*/
69412SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
69413  int i;
69414  Mem *pX;
69415  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
69416    if( pX->pScopyFrom==pMem ){
69417      pX->flags |= MEM_Undefined;
69418      pX->pScopyFrom = 0;
69419    }
69420  }
69421  pMem->pScopyFrom = 0;
69422}
69423#endif /* SQLITE_DEBUG */
69424
69425
69426/*
69427** Make an shallow copy of pFrom into pTo.  Prior contents of
69428** pTo are freed.  The pFrom->z field is not duplicated.  If
69429** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
69430** and flags gets srcType (either MEM_Ephem or MEM_Static).
69431*/
69432static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
69433  vdbeMemClearExternAndSetNull(pTo);
69434  assert( !VdbeMemDynamic(pTo) );
69435  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
69436}
69437SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
69438  assert( (pFrom->flags & MEM_RowSet)==0 );
69439  assert( pTo->db==pFrom->db );
69440  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
69441  memcpy(pTo, pFrom, MEMCELLSIZE);
69442  if( (pFrom->flags&MEM_Static)==0 ){
69443    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
69444    assert( srcType==MEM_Ephem || srcType==MEM_Static );
69445    pTo->flags |= srcType;
69446  }
69447}
69448
69449/*
69450** Make a full copy of pFrom into pTo.  Prior contents of pTo are
69451** freed before the copy is made.
69452*/
69453SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
69454  int rc = SQLITE_OK;
69455
69456  assert( (pFrom->flags & MEM_RowSet)==0 );
69457  if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
69458  memcpy(pTo, pFrom, MEMCELLSIZE);
69459  pTo->flags &= ~MEM_Dyn;
69460  if( pTo->flags&(MEM_Str|MEM_Blob) ){
69461    if( 0==(pFrom->flags&MEM_Static) ){
69462      pTo->flags |= MEM_Ephem;
69463      rc = sqlite3VdbeMemMakeWriteable(pTo);
69464    }
69465  }
69466
69467  return rc;
69468}
69469
69470/*
69471** Transfer the contents of pFrom to pTo. Any existing value in pTo is
69472** freed. If pFrom contains ephemeral data, a copy is made.
69473**
69474** pFrom contains an SQL NULL when this routine returns.
69475*/
69476SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
69477  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
69478  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
69479  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
69480
69481  sqlite3VdbeMemRelease(pTo);
69482  memcpy(pTo, pFrom, sizeof(Mem));
69483  pFrom->flags = MEM_Null;
69484  pFrom->szMalloc = 0;
69485}
69486
69487/*
69488** Change the value of a Mem to be a string or a BLOB.
69489**
69490** The memory management strategy depends on the value of the xDel
69491** parameter. If the value passed is SQLITE_TRANSIENT, then the
69492** string is copied into a (possibly existing) buffer managed by the
69493** Mem structure. Otherwise, any existing buffer is freed and the
69494** pointer copied.
69495**
69496** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
69497** size limit) then no memory allocation occurs.  If the string can be
69498** stored without allocating memory, then it is.  If a memory allocation
69499** is required to store the string, then value of pMem is unchanged.  In
69500** either case, SQLITE_TOOBIG is returned.
69501*/
69502SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
69503  Mem *pMem,          /* Memory cell to set to string value */
69504  const char *z,      /* String pointer */
69505  int n,              /* Bytes in string, or negative */
69506  u8 enc,             /* Encoding of z.  0 for BLOBs */
69507  void (*xDel)(void*) /* Destructor function */
69508){
69509  int nByte = n;      /* New value for pMem->n */
69510  int iLimit;         /* Maximum allowed string or blob size */
69511  u16 flags = 0;      /* New value for pMem->flags */
69512
69513  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69514  assert( (pMem->flags & MEM_RowSet)==0 );
69515
69516  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
69517  if( !z ){
69518    sqlite3VdbeMemSetNull(pMem);
69519    return SQLITE_OK;
69520  }
69521
69522  if( pMem->db ){
69523    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
69524  }else{
69525    iLimit = SQLITE_MAX_LENGTH;
69526  }
69527  flags = (enc==0?MEM_Blob:MEM_Str);
69528  if( nByte<0 ){
69529    assert( enc!=0 );
69530    if( enc==SQLITE_UTF8 ){
69531      nByte = sqlite3Strlen30(z);
69532      if( nByte>iLimit ) nByte = iLimit+1;
69533    }else{
69534      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
69535    }
69536    flags |= MEM_Term;
69537  }
69538
69539  /* The following block sets the new values of Mem.z and Mem.xDel. It
69540  ** also sets a flag in local variable "flags" to indicate the memory
69541  ** management (one of MEM_Dyn or MEM_Static).
69542  */
69543  if( xDel==SQLITE_TRANSIENT ){
69544    int nAlloc = nByte;
69545    if( flags&MEM_Term ){
69546      nAlloc += (enc==SQLITE_UTF8?1:2);
69547    }
69548    if( nByte>iLimit ){
69549      return SQLITE_TOOBIG;
69550    }
69551    testcase( nAlloc==0 );
69552    testcase( nAlloc==31 );
69553    testcase( nAlloc==32 );
69554    if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
69555      return SQLITE_NOMEM_BKPT;
69556    }
69557    memcpy(pMem->z, z, nAlloc);
69558  }else if( xDel==SQLITE_DYNAMIC ){
69559    sqlite3VdbeMemRelease(pMem);
69560    pMem->zMalloc = pMem->z = (char *)z;
69561    pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69562  }else{
69563    sqlite3VdbeMemRelease(pMem);
69564    pMem->z = (char *)z;
69565    pMem->xDel = xDel;
69566    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
69567  }
69568
69569  pMem->n = nByte;
69570  pMem->flags = flags;
69571  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
69572
69573#ifndef SQLITE_OMIT_UTF16
69574  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
69575    return SQLITE_NOMEM_BKPT;
69576  }
69577#endif
69578
69579  if( nByte>iLimit ){
69580    return SQLITE_TOOBIG;
69581  }
69582
69583  return SQLITE_OK;
69584}
69585
69586/*
69587** Move data out of a btree key or data field and into a Mem structure.
69588** The data or key is taken from the entry that pCur is currently pointing
69589** to.  offset and amt determine what portion of the data or key to retrieve.
69590** key is true to get the key or false to get data.  The result is written
69591** into the pMem element.
69592**
69593** The pMem object must have been initialized.  This routine will use
69594** pMem->zMalloc to hold the content from the btree, if possible.  New
69595** pMem->zMalloc space will be allocated if necessary.  The calling routine
69596** is responsible for making sure that the pMem object is eventually
69597** destroyed.
69598**
69599** If this routine fails for any reason (malloc returns NULL or unable
69600** to read from the disk) then the pMem is left in an inconsistent state.
69601*/
69602static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
69603  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
69604  u32 offset,       /* Offset from the start of data to return bytes from. */
69605  u32 amt,          /* Number of bytes to return. */
69606  int key,          /* If true, retrieve from the btree key, not data. */
69607  Mem *pMem         /* OUT: Return data in this Mem structure. */
69608){
69609  int rc;
69610  pMem->flags = MEM_Null;
69611  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
69612    if( key ){
69613      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
69614    }else{
69615      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
69616    }
69617    if( rc==SQLITE_OK ){
69618      pMem->z[amt] = 0;
69619      pMem->z[amt+1] = 0;
69620      pMem->flags = MEM_Blob|MEM_Term;
69621      pMem->n = (int)amt;
69622    }else{
69623      sqlite3VdbeMemRelease(pMem);
69624    }
69625  }
69626  return rc;
69627}
69628SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
69629  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
69630  u32 offset,       /* Offset from the start of data to return bytes from. */
69631  u32 amt,          /* Number of bytes to return. */
69632  int key,          /* If true, retrieve from the btree key, not data. */
69633  Mem *pMem         /* OUT: Return data in this Mem structure. */
69634){
69635  char *zData;        /* Data from the btree layer */
69636  u32 available = 0;  /* Number of bytes available on the local btree page */
69637  int rc = SQLITE_OK; /* Return code */
69638
69639  assert( sqlite3BtreeCursorIsValid(pCur) );
69640  assert( !VdbeMemDynamic(pMem) );
69641
69642  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
69643  ** that both the BtShared and database handle mutexes are held. */
69644  assert( (pMem->flags & MEM_RowSet)==0 );
69645  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
69646  assert( zData!=0 );
69647
69648  if( offset+amt<=available ){
69649    pMem->z = &zData[offset];
69650    pMem->flags = MEM_Blob|MEM_Ephem;
69651    pMem->n = (int)amt;
69652  }else{
69653    rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
69654  }
69655
69656  return rc;
69657}
69658
69659/*
69660** The pVal argument is known to be a value other than NULL.
69661** Convert it into a string with encoding enc and return a pointer
69662** to a zero-terminated version of that string.
69663*/
69664static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
69665  assert( pVal!=0 );
69666  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69667  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69668  assert( (pVal->flags & MEM_RowSet)==0 );
69669  assert( (pVal->flags & (MEM_Null))==0 );
69670  if( pVal->flags & (MEM_Blob|MEM_Str) ){
69671    pVal->flags |= MEM_Str;
69672    if( pVal->flags & MEM_Zero ){
69673      sqlite3VdbeMemExpandBlob(pVal);
69674    }
69675    if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
69676      sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
69677    }
69678    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
69679      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
69680      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
69681        return 0;
69682      }
69683    }
69684    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
69685  }else{
69686    sqlite3VdbeMemStringify(pVal, enc, 0);
69687    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
69688  }
69689  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
69690              || pVal->db->mallocFailed );
69691  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
69692    return pVal->z;
69693  }else{
69694    return 0;
69695  }
69696}
69697
69698/* This function is only available internally, it is not part of the
69699** external API. It works in a similar way to sqlite3_value_text(),
69700** except the data returned is in the encoding specified by the second
69701** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
69702** SQLITE_UTF8.
69703**
69704** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
69705** If that is the case, then the result must be aligned on an even byte
69706** boundary.
69707*/
69708SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
69709  if( !pVal ) return 0;
69710  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69711  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69712  assert( (pVal->flags & MEM_RowSet)==0 );
69713  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
69714    return pVal->z;
69715  }
69716  if( pVal->flags&MEM_Null ){
69717    return 0;
69718  }
69719  return valueToText(pVal, enc);
69720}
69721
69722/*
69723** Create a new sqlite3_value object.
69724*/
69725SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
69726  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
69727  if( p ){
69728    p->flags = MEM_Null;
69729    p->db = db;
69730  }
69731  return p;
69732}
69733
69734/*
69735** Context object passed by sqlite3Stat4ProbeSetValue() through to
69736** valueNew(). See comments above valueNew() for details.
69737*/
69738struct ValueNewStat4Ctx {
69739  Parse *pParse;
69740  Index *pIdx;
69741  UnpackedRecord **ppRec;
69742  int iVal;
69743};
69744
69745/*
69746** Allocate and return a pointer to a new sqlite3_value object. If
69747** the second argument to this function is NULL, the object is allocated
69748** by calling sqlite3ValueNew().
69749**
69750** Otherwise, if the second argument is non-zero, then this function is
69751** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
69752** already been allocated, allocate the UnpackedRecord structure that
69753** that function will return to its caller here. Then return a pointer to
69754** an sqlite3_value within the UnpackedRecord.a[] array.
69755*/
69756static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
69757#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69758  if( p ){
69759    UnpackedRecord *pRec = p->ppRec[0];
69760
69761    if( pRec==0 ){
69762      Index *pIdx = p->pIdx;      /* Index being probed */
69763      int nByte;                  /* Bytes of space to allocate */
69764      int i;                      /* Counter variable */
69765      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
69766
69767      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
69768      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
69769      if( pRec ){
69770        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
69771        if( pRec->pKeyInfo ){
69772          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
69773          assert( pRec->pKeyInfo->enc==ENC(db) );
69774          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
69775          for(i=0; i<nCol; i++){
69776            pRec->aMem[i].flags = MEM_Null;
69777            pRec->aMem[i].db = db;
69778          }
69779        }else{
69780          sqlite3DbFree(db, pRec);
69781          pRec = 0;
69782        }
69783      }
69784      if( pRec==0 ) return 0;
69785      p->ppRec[0] = pRec;
69786    }
69787
69788    pRec->nField = p->iVal+1;
69789    return &pRec->aMem[p->iVal];
69790  }
69791#else
69792  UNUSED_PARAMETER(p);
69793#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69794  return sqlite3ValueNew(db);
69795}
69796
69797/*
69798** The expression object indicated by the second argument is guaranteed
69799** to be a scalar SQL function. If
69800**
69801**   * all function arguments are SQL literals,
69802**   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
69803**   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
69804**
69805** then this routine attempts to invoke the SQL function. Assuming no
69806** error occurs, output parameter (*ppVal) is set to point to a value
69807** object containing the result before returning SQLITE_OK.
69808**
69809** Affinity aff is applied to the result of the function before returning.
69810** If the result is a text value, the sqlite3_value object uses encoding
69811** enc.
69812**
69813** If the conditions above are not met, this function returns SQLITE_OK
69814** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
69815** NULL and an SQLite error code returned.
69816*/
69817#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69818static int valueFromFunction(
69819  sqlite3 *db,                    /* The database connection */
69820  Expr *p,                        /* The expression to evaluate */
69821  u8 enc,                         /* Encoding to use */
69822  u8 aff,                         /* Affinity to use */
69823  sqlite3_value **ppVal,          /* Write the new value here */
69824  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
69825){
69826  sqlite3_context ctx;            /* Context object for function invocation */
69827  sqlite3_value **apVal = 0;      /* Function arguments */
69828  int nVal = 0;                   /* Size of apVal[] array */
69829  FuncDef *pFunc = 0;             /* Function definition */
69830  sqlite3_value *pVal = 0;        /* New value */
69831  int rc = SQLITE_OK;             /* Return code */
69832  ExprList *pList = 0;            /* Function arguments */
69833  int i;                          /* Iterator variable */
69834
69835  assert( pCtx!=0 );
69836  assert( (p->flags & EP_TokenOnly)==0 );
69837  pList = p->x.pList;
69838  if( pList ) nVal = pList->nExpr;
69839  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
69840  assert( pFunc );
69841  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
69842   || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
69843  ){
69844    return SQLITE_OK;
69845  }
69846
69847  if( pList ){
69848    apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
69849    if( apVal==0 ){
69850      rc = SQLITE_NOMEM_BKPT;
69851      goto value_from_function_out;
69852    }
69853    for(i=0; i<nVal; i++){
69854      rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
69855      if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
69856    }
69857  }
69858
69859  pVal = valueNew(db, pCtx);
69860  if( pVal==0 ){
69861    rc = SQLITE_NOMEM_BKPT;
69862    goto value_from_function_out;
69863  }
69864
69865  assert( pCtx->pParse->rc==SQLITE_OK );
69866  memset(&ctx, 0, sizeof(ctx));
69867  ctx.pOut = pVal;
69868  ctx.pFunc = pFunc;
69869  pFunc->xSFunc(&ctx, nVal, apVal);
69870  if( ctx.isError ){
69871    rc = ctx.isError;
69872    sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
69873  }else{
69874    sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
69875    assert( rc==SQLITE_OK );
69876    rc = sqlite3VdbeChangeEncoding(pVal, enc);
69877    if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
69878      rc = SQLITE_TOOBIG;
69879      pCtx->pParse->nErr++;
69880    }
69881  }
69882  pCtx->pParse->rc = rc;
69883
69884 value_from_function_out:
69885  if( rc!=SQLITE_OK ){
69886    pVal = 0;
69887  }
69888  if( apVal ){
69889    for(i=0; i<nVal; i++){
69890      sqlite3ValueFree(apVal[i]);
69891    }
69892    sqlite3DbFree(db, apVal);
69893  }
69894
69895  *ppVal = pVal;
69896  return rc;
69897}
69898#else
69899# define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
69900#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69901
69902/*
69903** Extract a value from the supplied expression in the manner described
69904** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
69905** using valueNew().
69906**
69907** If pCtx is NULL and an error occurs after the sqlite3_value object
69908** has been allocated, it is freed before returning. Or, if pCtx is not
69909** NULL, it is assumed that the caller will free any allocated object
69910** in all cases.
69911*/
69912static int valueFromExpr(
69913  sqlite3 *db,                    /* The database connection */
69914  Expr *pExpr,                    /* The expression to evaluate */
69915  u8 enc,                         /* Encoding to use */
69916  u8 affinity,                    /* Affinity to use */
69917  sqlite3_value **ppVal,          /* Write the new value here */
69918  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
69919){
69920  int op;
69921  char *zVal = 0;
69922  sqlite3_value *pVal = 0;
69923  int negInt = 1;
69924  const char *zNeg = "";
69925  int rc = SQLITE_OK;
69926
69927  if( !pExpr ){
69928    *ppVal = 0;
69929    return SQLITE_OK;
69930  }
69931  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
69932  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
69933
69934  /* Compressed expressions only appear when parsing the DEFAULT clause
69935  ** on a table column definition, and hence only when pCtx==0.  This
69936  ** check ensures that an EP_TokenOnly expression is never passed down
69937  ** into valueFromFunction(). */
69938  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
69939
69940  if( op==TK_CAST ){
69941    u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
69942    rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
69943    testcase( rc!=SQLITE_OK );
69944    if( *ppVal ){
69945      sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
69946      sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
69947    }
69948    return rc;
69949  }
69950
69951  /* Handle negative integers in a single step.  This is needed in the
69952  ** case when the value is -9223372036854775808.
69953  */
69954  if( op==TK_UMINUS
69955   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
69956    pExpr = pExpr->pLeft;
69957    op = pExpr->op;
69958    negInt = -1;
69959    zNeg = "-";
69960  }
69961
69962  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
69963    pVal = valueNew(db, pCtx);
69964    if( pVal==0 ) goto no_mem;
69965    if( ExprHasProperty(pExpr, EP_IntValue) ){
69966      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
69967    }else{
69968      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
69969      if( zVal==0 ) goto no_mem;
69970      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
69971    }
69972    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
69973      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
69974    }else{
69975      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
69976    }
69977    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
69978    if( enc!=SQLITE_UTF8 ){
69979      rc = sqlite3VdbeChangeEncoding(pVal, enc);
69980    }
69981  }else if( op==TK_UMINUS ) {
69982    /* This branch happens for multiple negative signs.  Ex: -(-5) */
69983    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
69984     && pVal!=0
69985    ){
69986      sqlite3VdbeMemNumerify(pVal);
69987      if( pVal->flags & MEM_Real ){
69988        pVal->u.r = -pVal->u.r;
69989      }else if( pVal->u.i==SMALLEST_INT64 ){
69990        pVal->u.r = -(double)SMALLEST_INT64;
69991        MemSetTypeFlag(pVal, MEM_Real);
69992      }else{
69993        pVal->u.i = -pVal->u.i;
69994      }
69995      sqlite3ValueApplyAffinity(pVal, affinity, enc);
69996    }
69997  }else if( op==TK_NULL ){
69998    pVal = valueNew(db, pCtx);
69999    if( pVal==0 ) goto no_mem;
70000  }
70001#ifndef SQLITE_OMIT_BLOB_LITERAL
70002  else if( op==TK_BLOB ){
70003    int nVal;
70004    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70005    assert( pExpr->u.zToken[1]=='\'' );
70006    pVal = valueNew(db, pCtx);
70007    if( !pVal ) goto no_mem;
70008    zVal = &pExpr->u.zToken[2];
70009    nVal = sqlite3Strlen30(zVal)-1;
70010    assert( zVal[nVal]=='\'' );
70011    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
70012                         0, SQLITE_DYNAMIC);
70013  }
70014#endif
70015
70016#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70017  else if( op==TK_FUNCTION && pCtx!=0 ){
70018    rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
70019  }
70020#endif
70021
70022  *ppVal = pVal;
70023  return rc;
70024
70025no_mem:
70026  sqlite3OomFault(db);
70027  sqlite3DbFree(db, zVal);
70028  assert( *ppVal==0 );
70029#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70030  if( pCtx==0 ) sqlite3ValueFree(pVal);
70031#else
70032  assert( pCtx==0 ); sqlite3ValueFree(pVal);
70033#endif
70034  return SQLITE_NOMEM_BKPT;
70035}
70036
70037/*
70038** Create a new sqlite3_value object, containing the value of pExpr.
70039**
70040** This only works for very simple expressions that consist of one constant
70041** token (i.e. "5", "5.1", "'a string'"). If the expression can
70042** be converted directly into a value, then the value is allocated and
70043** a pointer written to *ppVal. The caller is responsible for deallocating
70044** the value by passing it to sqlite3ValueFree() later on. If the expression
70045** cannot be converted to a value, then *ppVal is set to NULL.
70046*/
70047SQLITE_PRIVATE int sqlite3ValueFromExpr(
70048  sqlite3 *db,              /* The database connection */
70049  Expr *pExpr,              /* The expression to evaluate */
70050  u8 enc,                   /* Encoding to use */
70051  u8 affinity,              /* Affinity to use */
70052  sqlite3_value **ppVal     /* Write the new value here */
70053){
70054  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
70055}
70056
70057#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70058/*
70059** The implementation of the sqlite_record() function. This function accepts
70060** a single argument of any type. The return value is a formatted database
70061** record (a blob) containing the argument value.
70062**
70063** This is used to convert the value stored in the 'sample' column of the
70064** sqlite_stat3 table to the record format SQLite uses internally.
70065*/
70066static void recordFunc(
70067  sqlite3_context *context,
70068  int argc,
70069  sqlite3_value **argv
70070){
70071  const int file_format = 1;
70072  u32 iSerial;                    /* Serial type */
70073  int nSerial;                    /* Bytes of space for iSerial as varint */
70074  u32 nVal;                       /* Bytes of space required for argv[0] */
70075  int nRet;
70076  sqlite3 *db;
70077  u8 *aRet;
70078
70079  UNUSED_PARAMETER( argc );
70080  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
70081  nSerial = sqlite3VarintLen(iSerial);
70082  db = sqlite3_context_db_handle(context);
70083
70084  nRet = 1 + nSerial + nVal;
70085  aRet = sqlite3DbMallocRawNN(db, nRet);
70086  if( aRet==0 ){
70087    sqlite3_result_error_nomem(context);
70088  }else{
70089    aRet[0] = nSerial+1;
70090    putVarint32(&aRet[1], iSerial);
70091    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
70092    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
70093    sqlite3DbFree(db, aRet);
70094  }
70095}
70096
70097/*
70098** Register built-in functions used to help read ANALYZE data.
70099*/
70100SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
70101  static FuncDef aAnalyzeTableFuncs[] = {
70102    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
70103  };
70104  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
70105}
70106
70107/*
70108** Attempt to extract a value from pExpr and use it to construct *ppVal.
70109**
70110** If pAlloc is not NULL, then an UnpackedRecord object is created for
70111** pAlloc if one does not exist and the new value is added to the
70112** UnpackedRecord object.
70113**
70114** A value is extracted in the following cases:
70115**
70116**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70117**
70118**  * The expression is a bound variable, and this is a reprepare, or
70119**
70120**  * The expression is a literal value.
70121**
70122** On success, *ppVal is made to point to the extracted value.  The caller
70123** is responsible for ensuring that the value is eventually freed.
70124*/
70125static int stat4ValueFromExpr(
70126  Parse *pParse,                  /* Parse context */
70127  Expr *pExpr,                    /* The expression to extract a value from */
70128  u8 affinity,                    /* Affinity to use */
70129  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
70130  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
70131){
70132  int rc = SQLITE_OK;
70133  sqlite3_value *pVal = 0;
70134  sqlite3 *db = pParse->db;
70135
70136  /* Skip over any TK_COLLATE nodes */
70137  pExpr = sqlite3ExprSkipCollate(pExpr);
70138
70139  if( !pExpr ){
70140    pVal = valueNew(db, pAlloc);
70141    if( pVal ){
70142      sqlite3VdbeMemSetNull((Mem*)pVal);
70143    }
70144  }else if( pExpr->op==TK_VARIABLE
70145        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
70146  ){
70147    Vdbe *v;
70148    int iBindVar = pExpr->iColumn;
70149    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
70150    if( (v = pParse->pReprepare)!=0 ){
70151      pVal = valueNew(db, pAlloc);
70152      if( pVal ){
70153        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
70154        if( rc==SQLITE_OK ){
70155          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
70156        }
70157        pVal->db = pParse->db;
70158      }
70159    }
70160  }else{
70161    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
70162  }
70163
70164  assert( pVal==0 || pVal->db==db );
70165  *ppVal = pVal;
70166  return rc;
70167}
70168
70169/*
70170** This function is used to allocate and populate UnpackedRecord
70171** structures intended to be compared against sample index keys stored
70172** in the sqlite_stat4 table.
70173**
70174** A single call to this function attempts to populates field iVal (leftmost
70175** is 0 etc.) of the unpacked record with a value extracted from expression
70176** pExpr. Extraction of values is possible if:
70177**
70178**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70179**
70180**  * The expression is a bound variable, and this is a reprepare, or
70181**
70182**  * The sqlite3ValueFromExpr() function is able to extract a value
70183**    from the expression (i.e. the expression is a literal value).
70184**
70185** If a value can be extracted, the affinity passed as the 5th argument
70186** is applied to it before it is copied into the UnpackedRecord. Output
70187** parameter *pbOk is set to true if a value is extracted, or false
70188** otherwise.
70189**
70190** When this function is called, *ppRec must either point to an object
70191** allocated by an earlier call to this function, or must be NULL. If it
70192** is NULL and a value can be successfully extracted, a new UnpackedRecord
70193** is allocated (and *ppRec set to point to it) before returning.
70194**
70195** Unless an error is encountered, SQLITE_OK is returned. It is not an
70196** error if a value cannot be extracted from pExpr. If an error does
70197** occur, an SQLite error code is returned.
70198*/
70199SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
70200  Parse *pParse,                  /* Parse context */
70201  Index *pIdx,                    /* Index being probed */
70202  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
70203  Expr *pExpr,                    /* The expression to extract a value from */
70204  u8 affinity,                    /* Affinity to use */
70205  int iVal,                       /* Array element to populate */
70206  int *pbOk                       /* OUT: True if value was extracted */
70207){
70208  int rc;
70209  sqlite3_value *pVal = 0;
70210  struct ValueNewStat4Ctx alloc;
70211
70212  alloc.pParse = pParse;
70213  alloc.pIdx = pIdx;
70214  alloc.ppRec = ppRec;
70215  alloc.iVal = iVal;
70216
70217  rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
70218  assert( pVal==0 || pVal->db==pParse->db );
70219  *pbOk = (pVal!=0);
70220  return rc;
70221}
70222
70223/*
70224** Attempt to extract a value from expression pExpr using the methods
70225** as described for sqlite3Stat4ProbeSetValue() above.
70226**
70227** If successful, set *ppVal to point to a new value object and return
70228** SQLITE_OK. If no value can be extracted, but no other error occurs
70229** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
70230** does occur, return an SQLite error code. The final value of *ppVal
70231** is undefined in this case.
70232*/
70233SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
70234  Parse *pParse,                  /* Parse context */
70235  Expr *pExpr,                    /* The expression to extract a value from */
70236  u8 affinity,                    /* Affinity to use */
70237  sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
70238){
70239  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
70240}
70241
70242/*
70243** Extract the iCol-th column from the nRec-byte record in pRec.  Write
70244** the column value into *ppVal.  If *ppVal is initially NULL then a new
70245** sqlite3_value object is allocated.
70246**
70247** If *ppVal is initially NULL then the caller is responsible for
70248** ensuring that the value written into *ppVal is eventually freed.
70249*/
70250SQLITE_PRIVATE int sqlite3Stat4Column(
70251  sqlite3 *db,                    /* Database handle */
70252  const void *pRec,               /* Pointer to buffer containing record */
70253  int nRec,                       /* Size of buffer pRec in bytes */
70254  int iCol,                       /* Column to extract */
70255  sqlite3_value **ppVal           /* OUT: Extracted value */
70256){
70257  u32 t;                          /* a column type code */
70258  int nHdr;                       /* Size of the header in the record */
70259  int iHdr;                       /* Next unread header byte */
70260  int iField;                     /* Next unread data byte */
70261  int szField;                    /* Size of the current data field */
70262  int i;                          /* Column index */
70263  u8 *a = (u8*)pRec;              /* Typecast byte array */
70264  Mem *pMem = *ppVal;             /* Write result into this Mem object */
70265
70266  assert( iCol>0 );
70267  iHdr = getVarint32(a, nHdr);
70268  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
70269  iField = nHdr;
70270  for(i=0; i<=iCol; i++){
70271    iHdr += getVarint32(&a[iHdr], t);
70272    testcase( iHdr==nHdr );
70273    testcase( iHdr==nHdr+1 );
70274    if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
70275    szField = sqlite3VdbeSerialTypeLen(t);
70276    iField += szField;
70277  }
70278  testcase( iField==nRec );
70279  testcase( iField==nRec+1 );
70280  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
70281  if( pMem==0 ){
70282    pMem = *ppVal = sqlite3ValueNew(db);
70283    if( pMem==0 ) return SQLITE_NOMEM_BKPT;
70284  }
70285  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
70286  pMem->enc = ENC(db);
70287  return SQLITE_OK;
70288}
70289
70290/*
70291** Unless it is NULL, the argument must be an UnpackedRecord object returned
70292** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
70293** the object.
70294*/
70295SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
70296  if( pRec ){
70297    int i;
70298    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
70299    Mem *aMem = pRec->aMem;
70300    sqlite3 *db = aMem[0].db;
70301    for(i=0; i<nCol; i++){
70302      sqlite3VdbeMemRelease(&aMem[i]);
70303    }
70304    sqlite3KeyInfoUnref(pRec->pKeyInfo);
70305    sqlite3DbFree(db, pRec);
70306  }
70307}
70308#endif /* ifdef SQLITE_ENABLE_STAT4 */
70309
70310/*
70311** Change the string value of an sqlite3_value object
70312*/
70313SQLITE_PRIVATE void sqlite3ValueSetStr(
70314  sqlite3_value *v,     /* Value to be set */
70315  int n,                /* Length of string z */
70316  const void *z,        /* Text of the new string */
70317  u8 enc,               /* Encoding to use */
70318  void (*xDel)(void*)   /* Destructor for the string */
70319){
70320  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
70321}
70322
70323/*
70324** Free an sqlite3_value object
70325*/
70326SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
70327  if( !v ) return;
70328  sqlite3VdbeMemRelease((Mem *)v);
70329  sqlite3DbFree(((Mem*)v)->db, v);
70330}
70331
70332/*
70333** The sqlite3ValueBytes() routine returns the number of bytes in the
70334** sqlite3_value object assuming that it uses the encoding "enc".
70335** The valueBytes() routine is a helper function.
70336*/
70337static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
70338  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
70339}
70340SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
70341  Mem *p = (Mem*)pVal;
70342  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
70343  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
70344    return p->n;
70345  }
70346  if( (p->flags & MEM_Blob)!=0 ){
70347    if( p->flags & MEM_Zero ){
70348      return p->n + p->u.nZero;
70349    }else{
70350      return p->n;
70351    }
70352  }
70353  if( p->flags & MEM_Null ) return 0;
70354  return valueBytes(pVal, enc);
70355}
70356
70357/************** End of vdbemem.c *********************************************/
70358/************** Begin file vdbeaux.c *****************************************/
70359/*
70360** 2003 September 6
70361**
70362** The author disclaims copyright to this source code.  In place of
70363** a legal notice, here is a blessing:
70364**
70365**    May you do good and not evil.
70366**    May you find forgiveness for yourself and forgive others.
70367**    May you share freely, never taking more than you give.
70368**
70369*************************************************************************
70370** This file contains code used for creating, destroying, and populating
70371** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
70372*/
70373/* #include "sqliteInt.h" */
70374/* #include "vdbeInt.h" */
70375
70376/*
70377** Create a new virtual database engine.
70378*/
70379SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
70380  sqlite3 *db = pParse->db;
70381  Vdbe *p;
70382  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
70383  if( p==0 ) return 0;
70384  p->db = db;
70385  if( db->pVdbe ){
70386    db->pVdbe->pPrev = p;
70387  }
70388  p->pNext = db->pVdbe;
70389  p->pPrev = 0;
70390  db->pVdbe = p;
70391  p->magic = VDBE_MAGIC_INIT;
70392  p->pParse = pParse;
70393  assert( pParse->aLabel==0 );
70394  assert( pParse->nLabel==0 );
70395  assert( pParse->nOpAlloc==0 );
70396  assert( pParse->szOpAlloc==0 );
70397  return p;
70398}
70399
70400/*
70401** Change the error string stored in Vdbe.zErrMsg
70402*/
70403SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
70404  va_list ap;
70405  sqlite3DbFree(p->db, p->zErrMsg);
70406  va_start(ap, zFormat);
70407  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
70408  va_end(ap);
70409}
70410
70411/*
70412** Remember the SQL string for a prepared statement.
70413*/
70414SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
70415  assert( isPrepareV2==1 || isPrepareV2==0 );
70416  if( p==0 ) return;
70417#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
70418  if( !isPrepareV2 ) return;
70419#endif
70420  assert( p->zSql==0 );
70421  p->zSql = sqlite3DbStrNDup(p->db, z, n);
70422  p->isPrepareV2 = (u8)isPrepareV2;
70423}
70424
70425/*
70426** Swap all content between two VDBE structures.
70427*/
70428SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
70429  Vdbe tmp, *pTmp;
70430  char *zTmp;
70431  assert( pA->db==pB->db );
70432  tmp = *pA;
70433  *pA = *pB;
70434  *pB = tmp;
70435  pTmp = pA->pNext;
70436  pA->pNext = pB->pNext;
70437  pB->pNext = pTmp;
70438  pTmp = pA->pPrev;
70439  pA->pPrev = pB->pPrev;
70440  pB->pPrev = pTmp;
70441  zTmp = pA->zSql;
70442  pA->zSql = pB->zSql;
70443  pB->zSql = zTmp;
70444  pB->isPrepareV2 = pA->isPrepareV2;
70445}
70446
70447/*
70448** Resize the Vdbe.aOp array so that it is at least nOp elements larger
70449** than its current size. nOp is guaranteed to be less than or equal
70450** to 1024/sizeof(Op).
70451**
70452** If an out-of-memory error occurs while resizing the array, return
70453** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
70454** unchanged (this is so that any opcodes already allocated can be
70455** correctly deallocated along with the rest of the Vdbe).
70456*/
70457static int growOpArray(Vdbe *v, int nOp){
70458  VdbeOp *pNew;
70459  Parse *p = v->pParse;
70460
70461  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
70462  ** more frequent reallocs and hence provide more opportunities for
70463  ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
70464  ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
70465  ** by the minimum* amount required until the size reaches 512.  Normal
70466  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
70467  ** size of the op array or add 1KB of space, whichever is smaller. */
70468#ifdef SQLITE_TEST_REALLOC_STRESS
70469  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
70470#else
70471  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
70472  UNUSED_PARAMETER(nOp);
70473#endif
70474
70475  assert( nOp<=(1024/sizeof(Op)) );
70476  assert( nNew>=(p->nOpAlloc+nOp) );
70477  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
70478  if( pNew ){
70479    p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
70480    p->nOpAlloc = p->szOpAlloc/sizeof(Op);
70481    v->aOp = pNew;
70482  }
70483  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
70484}
70485
70486#ifdef SQLITE_DEBUG
70487/* This routine is just a convenient place to set a breakpoint that will
70488** fire after each opcode is inserted and displayed using
70489** "PRAGMA vdbe_addoptrace=on".
70490*/
70491static void test_addop_breakpoint(void){
70492  static int n = 0;
70493  n++;
70494}
70495#endif
70496
70497/*
70498** Add a new instruction to the list of instructions current in the
70499** VDBE.  Return the address of the new instruction.
70500**
70501** Parameters:
70502**
70503**    p               Pointer to the VDBE
70504**
70505**    op              The opcode for this instruction
70506**
70507**    p1, p2, p3      Operands
70508**
70509** Use the sqlite3VdbeResolveLabel() function to fix an address and
70510** the sqlite3VdbeChangeP4() function to change the value of the P4
70511** operand.
70512*/
70513static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
70514  assert( p->pParse->nOpAlloc<=p->nOp );
70515  if( growOpArray(p, 1) ) return 1;
70516  assert( p->pParse->nOpAlloc>p->nOp );
70517  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70518}
70519SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
70520  int i;
70521  VdbeOp *pOp;
70522
70523  i = p->nOp;
70524  assert( p->magic==VDBE_MAGIC_INIT );
70525  assert( op>=0 && op<0xff );
70526  if( p->pParse->nOpAlloc<=i ){
70527    return growOp3(p, op, p1, p2, p3);
70528  }
70529  p->nOp++;
70530  pOp = &p->aOp[i];
70531  pOp->opcode = (u8)op;
70532  pOp->p5 = 0;
70533  pOp->p1 = p1;
70534  pOp->p2 = p2;
70535  pOp->p3 = p3;
70536  pOp->p4.p = 0;
70537  pOp->p4type = P4_NOTUSED;
70538#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70539  pOp->zComment = 0;
70540#endif
70541#ifdef SQLITE_DEBUG
70542  if( p->db->flags & SQLITE_VdbeAddopTrace ){
70543    int jj, kk;
70544    Parse *pParse = p->pParse;
70545    for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
70546      struct yColCache *x = pParse->aColCache + jj;
70547      if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
70548      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
70549      kk++;
70550    }
70551    if( kk ) printf("\n");
70552    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
70553    test_addop_breakpoint();
70554  }
70555#endif
70556#ifdef VDBE_PROFILE
70557  pOp->cycles = 0;
70558  pOp->cnt = 0;
70559#endif
70560#ifdef SQLITE_VDBE_COVERAGE
70561  pOp->iSrcLine = 0;
70562#endif
70563  return i;
70564}
70565SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
70566  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
70567}
70568SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
70569  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
70570}
70571SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
70572  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
70573}
70574
70575/* Generate code for an unconditional jump to instruction iDest
70576*/
70577SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
70578  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
70579}
70580
70581/* Generate code to cause the string zStr to be loaded into
70582** register iDest
70583*/
70584SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
70585  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
70586}
70587
70588/*
70589** Generate code that initializes multiple registers to string or integer
70590** constants.  The registers begin with iDest and increase consecutively.
70591** One register is initialized for each characgter in zTypes[].  For each
70592** "s" character in zTypes[], the register is a string if the argument is
70593** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
70594** in zTypes[], the register is initialized to an integer.
70595*/
70596SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
70597  va_list ap;
70598  int i;
70599  char c;
70600  va_start(ap, zTypes);
70601  for(i=0; (c = zTypes[i])!=0; i++){
70602    if( c=='s' ){
70603      const char *z = va_arg(ap, const char*);
70604      sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
70605    }else{
70606      assert( c=='i' );
70607      sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
70608    }
70609  }
70610  va_end(ap);
70611}
70612
70613/*
70614** Add an opcode that includes the p4 value as a pointer.
70615*/
70616SQLITE_PRIVATE int sqlite3VdbeAddOp4(
70617  Vdbe *p,            /* Add the opcode to this VM */
70618  int op,             /* The new opcode */
70619  int p1,             /* The P1 operand */
70620  int p2,             /* The P2 operand */
70621  int p3,             /* The P3 operand */
70622  const char *zP4,    /* The P4 operand */
70623  int p4type          /* P4 operand type */
70624){
70625  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70626  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
70627  return addr;
70628}
70629
70630/*
70631** Add an opcode that includes the p4 value with a P4_INT64 or
70632** P4_REAL type.
70633*/
70634SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
70635  Vdbe *p,            /* Add the opcode to this VM */
70636  int op,             /* The new opcode */
70637  int p1,             /* The P1 operand */
70638  int p2,             /* The P2 operand */
70639  int p3,             /* The P3 operand */
70640  const u8 *zP4,      /* The P4 operand */
70641  int p4type          /* P4 operand type */
70642){
70643  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
70644  if( p4copy ) memcpy(p4copy, zP4, 8);
70645  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
70646}
70647
70648/*
70649** Add an OP_ParseSchema opcode.  This routine is broken out from
70650** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
70651** as having been used.
70652**
70653** The zWhere string must have been obtained from sqlite3_malloc().
70654** This routine will take ownership of the allocated memory.
70655*/
70656SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
70657  int j;
70658  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70659  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
70660}
70661
70662/*
70663** Add an opcode that includes the p4 value as an integer.
70664*/
70665SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
70666  Vdbe *p,            /* Add the opcode to this VM */
70667  int op,             /* The new opcode */
70668  int p1,             /* The P1 operand */
70669  int p2,             /* The P2 operand */
70670  int p3,             /* The P3 operand */
70671  int p4              /* The P4 operand as an integer */
70672){
70673  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70674  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
70675  return addr;
70676}
70677
70678/* Insert the end of a co-routine
70679*/
70680SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
70681  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
70682
70683  /* Clear the temporary register cache, thereby ensuring that each
70684  ** co-routine has its own independent set of registers, because co-routines
70685  ** might expect their registers to be preserved across an OP_Yield, and
70686  ** that could cause problems if two or more co-routines are using the same
70687  ** temporary register.
70688  */
70689  v->pParse->nTempReg = 0;
70690  v->pParse->nRangeReg = 0;
70691}
70692
70693/*
70694** Create a new symbolic label for an instruction that has yet to be
70695** coded.  The symbolic label is really just a negative number.  The
70696** label can be used as the P2 value of an operation.  Later, when
70697** the label is resolved to a specific address, the VDBE will scan
70698** through its operation list and change all values of P2 which match
70699** the label into the resolved address.
70700**
70701** The VDBE knows that a P2 value is a label because labels are
70702** always negative and P2 values are suppose to be non-negative.
70703** Hence, a negative P2 value is a label that has yet to be resolved.
70704**
70705** Zero is returned if a malloc() fails.
70706*/
70707SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
70708  Parse *p = v->pParse;
70709  int i = p->nLabel++;
70710  assert( v->magic==VDBE_MAGIC_INIT );
70711  if( (i & (i-1))==0 ){
70712    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
70713                                       (i*2+1)*sizeof(p->aLabel[0]));
70714  }
70715  if( p->aLabel ){
70716    p->aLabel[i] = -1;
70717  }
70718  return ADDR(i);
70719}
70720
70721/*
70722** Resolve label "x" to be the address of the next instruction to
70723** be inserted.  The parameter "x" must have been obtained from
70724** a prior call to sqlite3VdbeMakeLabel().
70725*/
70726SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
70727  Parse *p = v->pParse;
70728  int j = ADDR(x);
70729  assert( v->magic==VDBE_MAGIC_INIT );
70730  assert( j<p->nLabel );
70731  assert( j>=0 );
70732  if( p->aLabel ){
70733    p->aLabel[j] = v->nOp;
70734  }
70735  p->iFixedOp = v->nOp - 1;
70736}
70737
70738/*
70739** Mark the VDBE as one that can only be run one time.
70740*/
70741SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
70742  p->runOnlyOnce = 1;
70743}
70744
70745/*
70746** Mark the VDBE as one that can only be run multiple times.
70747*/
70748SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
70749  p->runOnlyOnce = 0;
70750}
70751
70752#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
70753
70754/*
70755** The following type and function are used to iterate through all opcodes
70756** in a Vdbe main program and each of the sub-programs (triggers) it may
70757** invoke directly or indirectly. It should be used as follows:
70758**
70759**   Op *pOp;
70760**   VdbeOpIter sIter;
70761**
70762**   memset(&sIter, 0, sizeof(sIter));
70763**   sIter.v = v;                            // v is of type Vdbe*
70764**   while( (pOp = opIterNext(&sIter)) ){
70765**     // Do something with pOp
70766**   }
70767**   sqlite3DbFree(v->db, sIter.apSub);
70768**
70769*/
70770typedef struct VdbeOpIter VdbeOpIter;
70771struct VdbeOpIter {
70772  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
70773  SubProgram **apSub;        /* Array of subprograms */
70774  int nSub;                  /* Number of entries in apSub */
70775  int iAddr;                 /* Address of next instruction to return */
70776  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
70777};
70778static Op *opIterNext(VdbeOpIter *p){
70779  Vdbe *v = p->v;
70780  Op *pRet = 0;
70781  Op *aOp;
70782  int nOp;
70783
70784  if( p->iSub<=p->nSub ){
70785
70786    if( p->iSub==0 ){
70787      aOp = v->aOp;
70788      nOp = v->nOp;
70789    }else{
70790      aOp = p->apSub[p->iSub-1]->aOp;
70791      nOp = p->apSub[p->iSub-1]->nOp;
70792    }
70793    assert( p->iAddr<nOp );
70794
70795    pRet = &aOp[p->iAddr];
70796    p->iAddr++;
70797    if( p->iAddr==nOp ){
70798      p->iSub++;
70799      p->iAddr = 0;
70800    }
70801
70802    if( pRet->p4type==P4_SUBPROGRAM ){
70803      int nByte = (p->nSub+1)*sizeof(SubProgram*);
70804      int j;
70805      for(j=0; j<p->nSub; j++){
70806        if( p->apSub[j]==pRet->p4.pProgram ) break;
70807      }
70808      if( j==p->nSub ){
70809        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
70810        if( !p->apSub ){
70811          pRet = 0;
70812        }else{
70813          p->apSub[p->nSub++] = pRet->p4.pProgram;
70814        }
70815      }
70816    }
70817  }
70818
70819  return pRet;
70820}
70821
70822/*
70823** Check if the program stored in the VM associated with pParse may
70824** throw an ABORT exception (causing the statement, but not entire transaction
70825** to be rolled back). This condition is true if the main program or any
70826** sub-programs contains any of the following:
70827**
70828**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70829**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70830**   *  OP_Destroy
70831**   *  OP_VUpdate
70832**   *  OP_VRename
70833**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
70834**   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
70835**
70836** Then check that the value of Parse.mayAbort is true if an
70837** ABORT may be thrown, or false otherwise. Return true if it does
70838** match, or false otherwise. This function is intended to be used as
70839** part of an assert statement in the compiler. Similar to:
70840**
70841**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
70842*/
70843SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
70844  int hasAbort = 0;
70845  int hasFkCounter = 0;
70846  int hasCreateTable = 0;
70847  int hasInitCoroutine = 0;
70848  Op *pOp;
70849  VdbeOpIter sIter;
70850  memset(&sIter, 0, sizeof(sIter));
70851  sIter.v = v;
70852
70853  while( (pOp = opIterNext(&sIter))!=0 ){
70854    int opcode = pOp->opcode;
70855    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
70856     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
70857      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
70858    ){
70859      hasAbort = 1;
70860      break;
70861    }
70862    if( opcode==OP_CreateTable ) hasCreateTable = 1;
70863    if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
70864#ifndef SQLITE_OMIT_FOREIGN_KEY
70865    if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
70866      hasFkCounter = 1;
70867    }
70868#endif
70869  }
70870  sqlite3DbFree(v->db, sIter.apSub);
70871
70872  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
70873  ** If malloc failed, then the while() loop above may not have iterated
70874  ** through all opcodes and hasAbort may be set incorrectly. Return
70875  ** true for this case to prevent the assert() in the callers frame
70876  ** from failing.  */
70877  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
70878              || (hasCreateTable && hasInitCoroutine) );
70879}
70880#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
70881
70882/*
70883** This routine is called after all opcodes have been inserted.  It loops
70884** through all the opcodes and fixes up some details.
70885**
70886** (1) For each jump instruction with a negative P2 value (a label)
70887**     resolve the P2 value to an actual address.
70888**
70889** (2) Compute the maximum number of arguments used by any SQL function
70890**     and store that value in *pMaxFuncArgs.
70891**
70892** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
70893**     indicate what the prepared statement actually does.
70894**
70895** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
70896**
70897** (5) Reclaim the memory allocated for storing labels.
70898**
70899** This routine will only function correctly if the mkopcodeh.tcl generator
70900** script numbers the opcodes correctly.  Changes to this routine must be
70901** coordinated with changes to mkopcodeh.tcl.
70902*/
70903static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
70904  int nMaxArgs = *pMaxFuncArgs;
70905  Op *pOp;
70906  Parse *pParse = p->pParse;
70907  int *aLabel = pParse->aLabel;
70908  p->readOnly = 1;
70909  p->bIsReader = 0;
70910  pOp = &p->aOp[p->nOp-1];
70911  while(1){
70912
70913    /* Only JUMP opcodes and the short list of special opcodes in the switch
70914    ** below need to be considered.  The mkopcodeh.tcl generator script groups
70915    ** all these opcodes together near the front of the opcode list.  Skip
70916    ** any opcode that does not need processing by virtual of the fact that
70917    ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
70918    */
70919    if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
70920      /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
70921      ** cases from this switch! */
70922      switch( pOp->opcode ){
70923        case OP_Transaction: {
70924          if( pOp->p2!=0 ) p->readOnly = 0;
70925          /* fall thru */
70926        }
70927        case OP_AutoCommit:
70928        case OP_Savepoint: {
70929          p->bIsReader = 1;
70930          break;
70931        }
70932#ifndef SQLITE_OMIT_WAL
70933        case OP_Checkpoint:
70934#endif
70935        case OP_Vacuum:
70936        case OP_JournalMode: {
70937          p->readOnly = 0;
70938          p->bIsReader = 1;
70939          break;
70940        }
70941#ifndef SQLITE_OMIT_VIRTUALTABLE
70942        case OP_VUpdate: {
70943          if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
70944          break;
70945        }
70946        case OP_VFilter: {
70947          int n;
70948          assert( (pOp - p->aOp) >= 3 );
70949          assert( pOp[-1].opcode==OP_Integer );
70950          n = pOp[-1].p1;
70951          if( n>nMaxArgs ) nMaxArgs = n;
70952          break;
70953        }
70954#endif
70955        case OP_Next:
70956        case OP_NextIfOpen:
70957        case OP_SorterNext: {
70958          pOp->p4.xAdvance = sqlite3BtreeNext;
70959          pOp->p4type = P4_ADVANCE;
70960          break;
70961        }
70962        case OP_Prev:
70963        case OP_PrevIfOpen: {
70964          pOp->p4.xAdvance = sqlite3BtreePrevious;
70965          pOp->p4type = P4_ADVANCE;
70966          break;
70967        }
70968      }
70969      if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
70970        assert( ADDR(pOp->p2)<pParse->nLabel );
70971        pOp->p2 = aLabel[ADDR(pOp->p2)];
70972      }
70973    }
70974    if( pOp==p->aOp ) break;
70975    pOp--;
70976  }
70977  sqlite3DbFree(p->db, pParse->aLabel);
70978  pParse->aLabel = 0;
70979  pParse->nLabel = 0;
70980  *pMaxFuncArgs = nMaxArgs;
70981  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
70982}
70983
70984/*
70985** Return the address of the next instruction to be inserted.
70986*/
70987SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
70988  assert( p->magic==VDBE_MAGIC_INIT );
70989  return p->nOp;
70990}
70991
70992/*
70993** Verify that at least N opcode slots are available in p without
70994** having to malloc for more space (except when compiled using
70995** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
70996** to verify that certain calls to sqlite3VdbeAddOpList() can never
70997** fail due to a OOM fault and hence that the return value from
70998** sqlite3VdbeAddOpList() will always be non-NULL.
70999*/
71000#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
71001SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
71002  assert( p->nOp + N <= p->pParse->nOpAlloc );
71003}
71004#endif
71005
71006/*
71007** This function returns a pointer to the array of opcodes associated with
71008** the Vdbe passed as the first argument. It is the callers responsibility
71009** to arrange for the returned array to be eventually freed using the
71010** vdbeFreeOpArray() function.
71011**
71012** Before returning, *pnOp is set to the number of entries in the returned
71013** array. Also, *pnMaxArg is set to the larger of its current value and
71014** the number of entries in the Vdbe.apArg[] array required to execute the
71015** returned program.
71016*/
71017SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
71018  VdbeOp *aOp = p->aOp;
71019  assert( aOp && !p->db->mallocFailed );
71020
71021  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
71022  assert( DbMaskAllZero(p->btreeMask) );
71023
71024  resolveP2Values(p, pnMaxArg);
71025  *pnOp = p->nOp;
71026  p->aOp = 0;
71027  return aOp;
71028}
71029
71030/*
71031** Add a whole list of operations to the operation stack.  Return a
71032** pointer to the first operation inserted.
71033**
71034** Non-zero P2 arguments to jump instructions are automatically adjusted
71035** so that the jump target is relative to the first operation inserted.
71036*/
71037SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
71038  Vdbe *p,                     /* Add opcodes to the prepared statement */
71039  int nOp,                     /* Number of opcodes to add */
71040  VdbeOpList const *aOp,       /* The opcodes to be added */
71041  int iLineno                  /* Source-file line number of first opcode */
71042){
71043  int i;
71044  VdbeOp *pOut, *pFirst;
71045  assert( nOp>0 );
71046  assert( p->magic==VDBE_MAGIC_INIT );
71047  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
71048    return 0;
71049  }
71050  pFirst = pOut = &p->aOp[p->nOp];
71051  for(i=0; i<nOp; i++, aOp++, pOut++){
71052    pOut->opcode = aOp->opcode;
71053    pOut->p1 = aOp->p1;
71054    pOut->p2 = aOp->p2;
71055    assert( aOp->p2>=0 );
71056    if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
71057      pOut->p2 += p->nOp;
71058    }
71059    pOut->p3 = aOp->p3;
71060    pOut->p4type = P4_NOTUSED;
71061    pOut->p4.p = 0;
71062    pOut->p5 = 0;
71063#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71064    pOut->zComment = 0;
71065#endif
71066#ifdef SQLITE_VDBE_COVERAGE
71067    pOut->iSrcLine = iLineno+i;
71068#else
71069    (void)iLineno;
71070#endif
71071#ifdef SQLITE_DEBUG
71072    if( p->db->flags & SQLITE_VdbeAddopTrace ){
71073      sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
71074    }
71075#endif
71076  }
71077  p->nOp += nOp;
71078  return pFirst;
71079}
71080
71081#if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
71082/*
71083** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
71084*/
71085SQLITE_PRIVATE void sqlite3VdbeScanStatus(
71086  Vdbe *p,                        /* VM to add scanstatus() to */
71087  int addrExplain,                /* Address of OP_Explain (or 0) */
71088  int addrLoop,                   /* Address of loop counter */
71089  int addrVisit,                  /* Address of rows visited counter */
71090  LogEst nEst,                    /* Estimated number of output rows */
71091  const char *zName               /* Name of table or index being scanned */
71092){
71093  int nByte = (p->nScan+1) * sizeof(ScanStatus);
71094  ScanStatus *aNew;
71095  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
71096  if( aNew ){
71097    ScanStatus *pNew = &aNew[p->nScan++];
71098    pNew->addrExplain = addrExplain;
71099    pNew->addrLoop = addrLoop;
71100    pNew->addrVisit = addrVisit;
71101    pNew->nEst = nEst;
71102    pNew->zName = sqlite3DbStrDup(p->db, zName);
71103    p->aScan = aNew;
71104  }
71105}
71106#endif
71107
71108
71109/*
71110** Change the value of the opcode, or P1, P2, P3, or P5 operands
71111** for a specific instruction.
71112*/
71113SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
71114  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
71115}
71116SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
71117  sqlite3VdbeGetOp(p,addr)->p1 = val;
71118}
71119SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
71120  sqlite3VdbeGetOp(p,addr)->p2 = val;
71121}
71122SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
71123  sqlite3VdbeGetOp(p,addr)->p3 = val;
71124}
71125SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
71126  if( !p->db->mallocFailed ) p->aOp[p->nOp-1].p5 = p5;
71127}
71128
71129/*
71130** Change the P2 operand of instruction addr so that it points to
71131** the address of the next instruction to be coded.
71132*/
71133SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
71134  p->pParse->iFixedOp = p->nOp - 1;
71135  sqlite3VdbeChangeP2(p, addr, p->nOp);
71136}
71137
71138
71139/*
71140** If the input FuncDef structure is ephemeral, then free it.  If
71141** the FuncDef is not ephermal, then do nothing.
71142*/
71143static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
71144  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
71145    sqlite3DbFree(db, pDef);
71146  }
71147}
71148
71149static void vdbeFreeOpArray(sqlite3 *, Op *, int);
71150
71151/*
71152** Delete a P4 value if necessary.
71153*/
71154static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
71155  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71156  sqlite3DbFree(db, p);
71157}
71158static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
71159  freeEphemeralFunction(db, p->pFunc);
71160  sqlite3DbFree(db, p);
71161}
71162static void freeP4(sqlite3 *db, int p4type, void *p4){
71163  assert( db );
71164  switch( p4type ){
71165    case P4_FUNCCTX: {
71166      freeP4FuncCtx(db, (sqlite3_context*)p4);
71167      break;
71168    }
71169    case P4_REAL:
71170    case P4_INT64:
71171    case P4_DYNAMIC:
71172    case P4_INTARRAY: {
71173      sqlite3DbFree(db, p4);
71174      break;
71175    }
71176    case P4_KEYINFO: {
71177      if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
71178      break;
71179    }
71180#ifdef SQLITE_ENABLE_CURSOR_HINTS
71181    case P4_EXPR: {
71182      sqlite3ExprDelete(db, (Expr*)p4);
71183      break;
71184    }
71185#endif
71186    case P4_MPRINTF: {
71187      if( db->pnBytesFreed==0 ) sqlite3_free(p4);
71188      break;
71189    }
71190    case P4_FUNCDEF: {
71191      freeEphemeralFunction(db, (FuncDef*)p4);
71192      break;
71193    }
71194    case P4_MEM: {
71195      if( db->pnBytesFreed==0 ){
71196        sqlite3ValueFree((sqlite3_value*)p4);
71197      }else{
71198        freeP4Mem(db, (Mem*)p4);
71199      }
71200      break;
71201    }
71202    case P4_VTAB : {
71203      if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
71204      break;
71205    }
71206  }
71207}
71208
71209/*
71210** Free the space allocated for aOp and any p4 values allocated for the
71211** opcodes contained within. If aOp is not NULL it is assumed to contain
71212** nOp entries.
71213*/
71214static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
71215  if( aOp ){
71216    Op *pOp;
71217    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
71218      if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
71219#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71220      sqlite3DbFree(db, pOp->zComment);
71221#endif
71222    }
71223  }
71224  sqlite3DbFree(db, aOp);
71225}
71226
71227/*
71228** Link the SubProgram object passed as the second argument into the linked
71229** list at Vdbe.pSubProgram. This list is used to delete all sub-program
71230** objects when the VM is no longer required.
71231*/
71232SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
71233  p->pNext = pVdbe->pProgram;
71234  pVdbe->pProgram = p;
71235}
71236
71237/*
71238** Change the opcode at addr into OP_Noop
71239*/
71240SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
71241  VdbeOp *pOp;
71242  if( p->db->mallocFailed ) return 0;
71243  assert( addr>=0 && addr<p->nOp );
71244  pOp = &p->aOp[addr];
71245  freeP4(p->db, pOp->p4type, pOp->p4.p);
71246  pOp->p4type = P4_NOTUSED;
71247  pOp->p4.z = 0;
71248  pOp->opcode = OP_Noop;
71249  return 1;
71250}
71251
71252/*
71253** If the last opcode is "op" and it is not a jump destination,
71254** then remove it.  Return true if and only if an opcode was removed.
71255*/
71256SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
71257  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
71258    return sqlite3VdbeChangeToNoop(p, p->nOp-1);
71259  }else{
71260    return 0;
71261  }
71262}
71263
71264/*
71265** Change the value of the P4 operand for a specific instruction.
71266** This routine is useful when a large program is loaded from a
71267** static array using sqlite3VdbeAddOpList but we want to make a
71268** few minor changes to the program.
71269**
71270** If n>=0 then the P4 operand is dynamic, meaning that a copy of
71271** the string is made into memory obtained from sqlite3_malloc().
71272** A value of n==0 means copy bytes of zP4 up to and including the
71273** first null byte.  If n>0 then copy n+1 bytes of zP4.
71274**
71275** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
71276** to a string or structure that is guaranteed to exist for the lifetime of
71277** the Vdbe. In these cases we can just copy the pointer.
71278**
71279** If addr<0 then change P4 on the most recently inserted instruction.
71280*/
71281static void SQLITE_NOINLINE vdbeChangeP4Full(
71282  Vdbe *p,
71283  Op *pOp,
71284  const char *zP4,
71285  int n
71286){
71287  if( pOp->p4type ){
71288    freeP4(p->db, pOp->p4type, pOp->p4.p);
71289    pOp->p4type = 0;
71290    pOp->p4.p = 0;
71291  }
71292  if( n<0 ){
71293    sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
71294  }else{
71295    if( n==0 ) n = sqlite3Strlen30(zP4);
71296    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
71297    pOp->p4type = P4_DYNAMIC;
71298  }
71299}
71300SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
71301  Op *pOp;
71302  sqlite3 *db;
71303  assert( p!=0 );
71304  db = p->db;
71305  assert( p->magic==VDBE_MAGIC_INIT );
71306  assert( p->aOp!=0 || db->mallocFailed );
71307  if( db->mallocFailed ){
71308    if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
71309    return;
71310  }
71311  assert( p->nOp>0 );
71312  assert( addr<p->nOp );
71313  if( addr<0 ){
71314    addr = p->nOp - 1;
71315  }
71316  pOp = &p->aOp[addr];
71317  if( n>=0 || pOp->p4type ){
71318    vdbeChangeP4Full(p, pOp, zP4, n);
71319    return;
71320  }
71321  if( n==P4_INT32 ){
71322    /* Note: this cast is safe, because the origin data point was an int
71323    ** that was cast to a (const char *). */
71324    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
71325    pOp->p4type = P4_INT32;
71326  }else if( zP4!=0 ){
71327    assert( n<0 );
71328    pOp->p4.p = (void*)zP4;
71329    pOp->p4type = (signed char)n;
71330    if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
71331  }
71332}
71333
71334/*
71335** Set the P4 on the most recently added opcode to the KeyInfo for the
71336** index given.
71337*/
71338SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
71339  Vdbe *v = pParse->pVdbe;
71340  assert( v!=0 );
71341  assert( pIdx!=0 );
71342  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
71343                      P4_KEYINFO);
71344}
71345
71346#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71347/*
71348** Change the comment on the most recently coded instruction.  Or
71349** insert a No-op and add the comment to that new instruction.  This
71350** makes the code easier to read during debugging.  None of this happens
71351** in a production build.
71352*/
71353static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
71354  assert( p->nOp>0 || p->aOp==0 );
71355  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
71356  if( p->nOp ){
71357    assert( p->aOp );
71358    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
71359    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
71360  }
71361}
71362SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
71363  va_list ap;
71364  if( p ){
71365    va_start(ap, zFormat);
71366    vdbeVComment(p, zFormat, ap);
71367    va_end(ap);
71368  }
71369}
71370SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
71371  va_list ap;
71372  if( p ){
71373    sqlite3VdbeAddOp0(p, OP_Noop);
71374    va_start(ap, zFormat);
71375    vdbeVComment(p, zFormat, ap);
71376    va_end(ap);
71377  }
71378}
71379#endif  /* NDEBUG */
71380
71381#ifdef SQLITE_VDBE_COVERAGE
71382/*
71383** Set the value if the iSrcLine field for the previously coded instruction.
71384*/
71385SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
71386  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
71387}
71388#endif /* SQLITE_VDBE_COVERAGE */
71389
71390/*
71391** Return the opcode for a given address.  If the address is -1, then
71392** return the most recently inserted opcode.
71393**
71394** If a memory allocation error has occurred prior to the calling of this
71395** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
71396** is readable but not writable, though it is cast to a writable value.
71397** The return of a dummy opcode allows the call to continue functioning
71398** after an OOM fault without having to check to see if the return from
71399** this routine is a valid pointer.  But because the dummy.opcode is 0,
71400** dummy will never be written to.  This is verified by code inspection and
71401** by running with Valgrind.
71402*/
71403SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
71404  /* C89 specifies that the constant "dummy" will be initialized to all
71405  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
71406  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
71407  assert( p->magic==VDBE_MAGIC_INIT );
71408  if( addr<0 ){
71409    addr = p->nOp - 1;
71410  }
71411  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
71412  if( p->db->mallocFailed ){
71413    return (VdbeOp*)&dummy;
71414  }else{
71415    return &p->aOp[addr];
71416  }
71417}
71418
71419#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
71420/*
71421** Return an integer value for one of the parameters to the opcode pOp
71422** determined by character c.
71423*/
71424static int translateP(char c, const Op *pOp){
71425  if( c=='1' ) return pOp->p1;
71426  if( c=='2' ) return pOp->p2;
71427  if( c=='3' ) return pOp->p3;
71428  if( c=='4' ) return pOp->p4.i;
71429  return pOp->p5;
71430}
71431
71432/*
71433** Compute a string for the "comment" field of a VDBE opcode listing.
71434**
71435** The Synopsis: field in comments in the vdbe.c source file gets converted
71436** to an extra string that is appended to the sqlite3OpcodeName().  In the
71437** absence of other comments, this synopsis becomes the comment on the opcode.
71438** Some translation occurs:
71439**
71440**       "PX"      ->  "r[X]"
71441**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
71442**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
71443**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
71444*/
71445static int displayComment(
71446  const Op *pOp,     /* The opcode to be commented */
71447  const char *zP4,   /* Previously obtained value for P4 */
71448  char *zTemp,       /* Write result here */
71449  int nTemp          /* Space available in zTemp[] */
71450){
71451  const char *zOpName;
71452  const char *zSynopsis;
71453  int nOpName;
71454  int ii, jj;
71455  zOpName = sqlite3OpcodeName(pOp->opcode);
71456  nOpName = sqlite3Strlen30(zOpName);
71457  if( zOpName[nOpName+1] ){
71458    int seenCom = 0;
71459    char c;
71460    zSynopsis = zOpName += nOpName + 1;
71461    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
71462      if( c=='P' ){
71463        c = zSynopsis[++ii];
71464        if( c=='4' ){
71465          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
71466        }else if( c=='X' ){
71467          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
71468          seenCom = 1;
71469        }else{
71470          int v1 = translateP(c, pOp);
71471          int v2;
71472          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
71473          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
71474            ii += 3;
71475            jj += sqlite3Strlen30(zTemp+jj);
71476            v2 = translateP(zSynopsis[ii], pOp);
71477            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
71478              ii += 2;
71479              v2++;
71480            }
71481            if( v2>1 ){
71482              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
71483            }
71484          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
71485            ii += 4;
71486          }
71487        }
71488        jj += sqlite3Strlen30(zTemp+jj);
71489      }else{
71490        zTemp[jj++] = c;
71491      }
71492    }
71493    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
71494      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
71495      jj += sqlite3Strlen30(zTemp+jj);
71496    }
71497    if( jj<nTemp ) zTemp[jj] = 0;
71498  }else if( pOp->zComment ){
71499    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
71500    jj = sqlite3Strlen30(zTemp);
71501  }else{
71502    zTemp[0] = 0;
71503    jj = 0;
71504  }
71505  return jj;
71506}
71507#endif /* SQLITE_DEBUG */
71508
71509#if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
71510/*
71511** Translate the P4.pExpr value for an OP_CursorHint opcode into text
71512** that can be displayed in the P4 column of EXPLAIN output.
71513*/
71514static void displayP4Expr(StrAccum *p, Expr *pExpr){
71515  const char *zOp = 0;
71516  switch( pExpr->op ){
71517    case TK_STRING:
71518      sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
71519      break;
71520    case TK_INTEGER:
71521      sqlite3XPrintf(p, "%d", pExpr->u.iValue);
71522      break;
71523    case TK_NULL:
71524      sqlite3XPrintf(p, "NULL");
71525      break;
71526    case TK_REGISTER: {
71527      sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
71528      break;
71529    }
71530    case TK_COLUMN: {
71531      if( pExpr->iColumn<0 ){
71532        sqlite3XPrintf(p, "rowid");
71533      }else{
71534        sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
71535      }
71536      break;
71537    }
71538    case TK_LT:      zOp = "LT";      break;
71539    case TK_LE:      zOp = "LE";      break;
71540    case TK_GT:      zOp = "GT";      break;
71541    case TK_GE:      zOp = "GE";      break;
71542    case TK_NE:      zOp = "NE";      break;
71543    case TK_EQ:      zOp = "EQ";      break;
71544    case TK_IS:      zOp = "IS";      break;
71545    case TK_ISNOT:   zOp = "ISNOT";   break;
71546    case TK_AND:     zOp = "AND";     break;
71547    case TK_OR:      zOp = "OR";      break;
71548    case TK_PLUS:    zOp = "ADD";     break;
71549    case TK_STAR:    zOp = "MUL";     break;
71550    case TK_MINUS:   zOp = "SUB";     break;
71551    case TK_REM:     zOp = "REM";     break;
71552    case TK_BITAND:  zOp = "BITAND";  break;
71553    case TK_BITOR:   zOp = "BITOR";   break;
71554    case TK_SLASH:   zOp = "DIV";     break;
71555    case TK_LSHIFT:  zOp = "LSHIFT";  break;
71556    case TK_RSHIFT:  zOp = "RSHIFT";  break;
71557    case TK_CONCAT:  zOp = "CONCAT";  break;
71558    case TK_UMINUS:  zOp = "MINUS";   break;
71559    case TK_UPLUS:   zOp = "PLUS";    break;
71560    case TK_BITNOT:  zOp = "BITNOT";  break;
71561    case TK_NOT:     zOp = "NOT";     break;
71562    case TK_ISNULL:  zOp = "ISNULL";  break;
71563    case TK_NOTNULL: zOp = "NOTNULL"; break;
71564
71565    default:
71566      sqlite3XPrintf(p, "%s", "expr");
71567      break;
71568  }
71569
71570  if( zOp ){
71571    sqlite3XPrintf(p, "%s(", zOp);
71572    displayP4Expr(p, pExpr->pLeft);
71573    if( pExpr->pRight ){
71574      sqlite3StrAccumAppend(p, ",", 1);
71575      displayP4Expr(p, pExpr->pRight);
71576    }
71577    sqlite3StrAccumAppend(p, ")", 1);
71578  }
71579}
71580#endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
71581
71582
71583#if VDBE_DISPLAY_P4
71584/*
71585** Compute a string that describes the P4 parameter for an opcode.
71586** Use zTemp for any required temporary buffer space.
71587*/
71588static char *displayP4(Op *pOp, char *zTemp, int nTemp){
71589  char *zP4 = zTemp;
71590  StrAccum x;
71591  assert( nTemp>=20 );
71592  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
71593  switch( pOp->p4type ){
71594    case P4_KEYINFO: {
71595      int j;
71596      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
71597      assert( pKeyInfo->aSortOrder!=0 );
71598      sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
71599      for(j=0; j<pKeyInfo->nField; j++){
71600        CollSeq *pColl = pKeyInfo->aColl[j];
71601        const char *zColl = pColl ? pColl->zName : "";
71602        if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
71603        sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
71604      }
71605      sqlite3StrAccumAppend(&x, ")", 1);
71606      break;
71607    }
71608#ifdef SQLITE_ENABLE_CURSOR_HINTS
71609    case P4_EXPR: {
71610      displayP4Expr(&x, pOp->p4.pExpr);
71611      break;
71612    }
71613#endif
71614    case P4_COLLSEQ: {
71615      CollSeq *pColl = pOp->p4.pColl;
71616      sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
71617      break;
71618    }
71619    case P4_FUNCDEF: {
71620      FuncDef *pDef = pOp->p4.pFunc;
71621      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71622      break;
71623    }
71624#ifdef SQLITE_DEBUG
71625    case P4_FUNCCTX: {
71626      FuncDef *pDef = pOp->p4.pCtx->pFunc;
71627      sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71628      break;
71629    }
71630#endif
71631    case P4_INT64: {
71632      sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
71633      break;
71634    }
71635    case P4_INT32: {
71636      sqlite3XPrintf(&x, "%d", pOp->p4.i);
71637      break;
71638    }
71639    case P4_REAL: {
71640      sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
71641      break;
71642    }
71643    case P4_MEM: {
71644      Mem *pMem = pOp->p4.pMem;
71645      if( pMem->flags & MEM_Str ){
71646        zP4 = pMem->z;
71647      }else if( pMem->flags & MEM_Int ){
71648        sqlite3XPrintf(&x, "%lld", pMem->u.i);
71649      }else if( pMem->flags & MEM_Real ){
71650        sqlite3XPrintf(&x, "%.16g", pMem->u.r);
71651      }else if( pMem->flags & MEM_Null ){
71652        zP4 = "NULL";
71653      }else{
71654        assert( pMem->flags & MEM_Blob );
71655        zP4 = "(blob)";
71656      }
71657      break;
71658    }
71659#ifndef SQLITE_OMIT_VIRTUALTABLE
71660    case P4_VTAB: {
71661      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
71662      sqlite3XPrintf(&x, "vtab:%p", pVtab);
71663      break;
71664    }
71665#endif
71666    case P4_INTARRAY: {
71667      int i;
71668      int *ai = pOp->p4.ai;
71669      int n = ai[0];   /* The first element of an INTARRAY is always the
71670                       ** count of the number of elements to follow */
71671      for(i=1; i<n; i++){
71672        sqlite3XPrintf(&x, ",%d", ai[i]);
71673      }
71674      zTemp[0] = '[';
71675      sqlite3StrAccumAppend(&x, "]", 1);
71676      break;
71677    }
71678    case P4_SUBPROGRAM: {
71679      sqlite3XPrintf(&x, "program");
71680      break;
71681    }
71682    case P4_ADVANCE: {
71683      zTemp[0] = 0;
71684      break;
71685    }
71686    case P4_TABLE: {
71687      sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71688      break;
71689    }
71690    default: {
71691      zP4 = pOp->p4.z;
71692      if( zP4==0 ){
71693        zP4 = zTemp;
71694        zTemp[0] = 0;
71695      }
71696    }
71697  }
71698  sqlite3StrAccumFinish(&x);
71699  assert( zP4!=0 );
71700  return zP4;
71701}
71702#endif /* VDBE_DISPLAY_P4 */
71703
71704/*
71705** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
71706**
71707** The prepared statements need to know in advance the complete set of
71708** attached databases that will be use.  A mask of these databases
71709** is maintained in p->btreeMask.  The p->lockMask value is the subset of
71710** p->btreeMask of databases that will require a lock.
71711*/
71712SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
71713  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
71714  assert( i<(int)sizeof(p->btreeMask)*8 );
71715  DbMaskSet(p->btreeMask, i);
71716  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
71717    DbMaskSet(p->lockMask, i);
71718  }
71719}
71720
71721#if !defined(SQLITE_OMIT_SHARED_CACHE)
71722/*
71723** If SQLite is compiled to support shared-cache mode and to be threadsafe,
71724** this routine obtains the mutex associated with each BtShared structure
71725** that may be accessed by the VM passed as an argument. In doing so it also
71726** sets the BtShared.db member of each of the BtShared structures, ensuring
71727** that the correct busy-handler callback is invoked if required.
71728**
71729** If SQLite is not threadsafe but does support shared-cache mode, then
71730** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
71731** of all of BtShared structures accessible via the database handle
71732** associated with the VM.
71733**
71734** If SQLite is not threadsafe and does not support shared-cache mode, this
71735** function is a no-op.
71736**
71737** The p->btreeMask field is a bitmask of all btrees that the prepared
71738** statement p will ever use.  Let N be the number of bits in p->btreeMask
71739** corresponding to btrees that use shared cache.  Then the runtime of
71740** this routine is N*N.  But as N is rarely more than 1, this should not
71741** be a problem.
71742*/
71743SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
71744  int i;
71745  sqlite3 *db;
71746  Db *aDb;
71747  int nDb;
71748  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
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      sqlite3BtreeEnter(aDb[i].pBt);
71755    }
71756  }
71757}
71758#endif
71759
71760#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
71761/*
71762** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
71763*/
71764static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
71765  int i;
71766  sqlite3 *db;
71767  Db *aDb;
71768  int nDb;
71769  db = p->db;
71770  aDb = db->aDb;
71771  nDb = db->nDb;
71772  for(i=0; i<nDb; i++){
71773    if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71774      sqlite3BtreeLeave(aDb[i].pBt);
71775    }
71776  }
71777}
71778SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
71779  if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
71780  vdbeLeave(p);
71781}
71782#endif
71783
71784#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
71785/*
71786** Print a single opcode.  This routine is used for debugging only.
71787*/
71788SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
71789  char *zP4;
71790  char zPtr[50];
71791  char zCom[100];
71792  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
71793  if( pOut==0 ) pOut = stdout;
71794  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
71795#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71796  displayComment(pOp, zP4, zCom, sizeof(zCom));
71797#else
71798  zCom[0] = 0;
71799#endif
71800  /* NB:  The sqlite3OpcodeName() function is implemented by code created
71801  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
71802  ** information from the vdbe.c source text */
71803  fprintf(pOut, zFormat1, pc,
71804      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
71805      zCom
71806  );
71807  fflush(pOut);
71808}
71809#endif
71810
71811/*
71812** Release an array of N Mem elements
71813*/
71814static void releaseMemArray(Mem *p, int N){
71815  if( p && N ){
71816    Mem *pEnd = &p[N];
71817    sqlite3 *db = p->db;
71818    if( db->pnBytesFreed ){
71819      do{
71820        if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71821      }while( (++p)<pEnd );
71822      return;
71823    }
71824    do{
71825      assert( (&p[1])==pEnd || p[0].db==p[1].db );
71826      assert( sqlite3VdbeCheckMemInvariants(p) );
71827
71828      /* This block is really an inlined version of sqlite3VdbeMemRelease()
71829      ** that takes advantage of the fact that the memory cell value is
71830      ** being set to NULL after releasing any dynamic resources.
71831      **
71832      ** The justification for duplicating code is that according to
71833      ** callgrind, this causes a certain test case to hit the CPU 4.7
71834      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
71835      ** sqlite3MemRelease() were called from here. With -O2, this jumps
71836      ** to 6.6 percent. The test case is inserting 1000 rows into a table
71837      ** with no indexes using a single prepared INSERT statement, bind()
71838      ** and reset(). Inserts are grouped into a transaction.
71839      */
71840      testcase( p->flags & MEM_Agg );
71841      testcase( p->flags & MEM_Dyn );
71842      testcase( p->flags & MEM_Frame );
71843      testcase( p->flags & MEM_RowSet );
71844      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
71845        sqlite3VdbeMemRelease(p);
71846      }else if( p->szMalloc ){
71847        sqlite3DbFree(db, p->zMalloc);
71848        p->szMalloc = 0;
71849      }
71850
71851      p->flags = MEM_Undefined;
71852    }while( (++p)<pEnd );
71853  }
71854}
71855
71856/*
71857** Delete a VdbeFrame object and its contents. VdbeFrame objects are
71858** allocated by the OP_Program opcode in sqlite3VdbeExec().
71859*/
71860SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
71861  int i;
71862  Mem *aMem = VdbeFrameMem(p);
71863  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
71864  for(i=0; i<p->nChildCsr; i++){
71865    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
71866  }
71867  releaseMemArray(aMem, p->nChildMem);
71868  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
71869  sqlite3DbFree(p->v->db, p);
71870}
71871
71872#ifndef SQLITE_OMIT_EXPLAIN
71873/*
71874** Give a listing of the program in the virtual machine.
71875**
71876** The interface is the same as sqlite3VdbeExec().  But instead of
71877** running the code, it invokes the callback once for each instruction.
71878** This feature is used to implement "EXPLAIN".
71879**
71880** When p->explain==1, each instruction is listed.  When
71881** p->explain==2, only OP_Explain instructions are listed and these
71882** are shown in a different format.  p->explain==2 is used to implement
71883** EXPLAIN QUERY PLAN.
71884**
71885** When p->explain==1, first the main program is listed, then each of
71886** the trigger subprograms are listed one by one.
71887*/
71888SQLITE_PRIVATE int sqlite3VdbeList(
71889  Vdbe *p                   /* The VDBE */
71890){
71891  int nRow;                            /* Stop when row count reaches this */
71892  int nSub = 0;                        /* Number of sub-vdbes seen so far */
71893  SubProgram **apSub = 0;              /* Array of sub-vdbes */
71894  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
71895  sqlite3 *db = p->db;                 /* The database connection */
71896  int i;                               /* Loop counter */
71897  int rc = SQLITE_OK;                  /* Return code */
71898  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
71899
71900  assert( p->explain );
71901  assert( p->magic==VDBE_MAGIC_RUN );
71902  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
71903
71904  /* Even though this opcode does not use dynamic strings for
71905  ** the result, result columns may become dynamic if the user calls
71906  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
71907  */
71908  releaseMemArray(pMem, 8);
71909  p->pResultSet = 0;
71910
71911  if( p->rc==SQLITE_NOMEM_BKPT ){
71912    /* This happens if a malloc() inside a call to sqlite3_column_text() or
71913    ** sqlite3_column_text16() failed.  */
71914    sqlite3OomFault(db);
71915    return SQLITE_ERROR;
71916  }
71917
71918  /* When the number of output rows reaches nRow, that means the
71919  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
71920  ** nRow is the sum of the number of rows in the main program, plus
71921  ** the sum of the number of rows in all trigger subprograms encountered
71922  ** so far.  The nRow value will increase as new trigger subprograms are
71923  ** encountered, but p->pc will eventually catch up to nRow.
71924  */
71925  nRow = p->nOp;
71926  if( p->explain==1 ){
71927    /* The first 8 memory cells are used for the result set.  So we will
71928    ** commandeer the 9th cell to use as storage for an array of pointers
71929    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
71930    ** cells.  */
71931    assert( p->nMem>9 );
71932    pSub = &p->aMem[9];
71933    if( pSub->flags&MEM_Blob ){
71934      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
71935      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
71936      nSub = pSub->n/sizeof(Vdbe*);
71937      apSub = (SubProgram **)pSub->z;
71938    }
71939    for(i=0; i<nSub; i++){
71940      nRow += apSub[i]->nOp;
71941    }
71942  }
71943
71944  do{
71945    i = p->pc++;
71946  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
71947  if( i>=nRow ){
71948    p->rc = SQLITE_OK;
71949    rc = SQLITE_DONE;
71950  }else if( db->u1.isInterrupted ){
71951    p->rc = SQLITE_INTERRUPT;
71952    rc = SQLITE_ERROR;
71953    sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
71954  }else{
71955    char *zP4;
71956    Op *pOp;
71957    if( i<p->nOp ){
71958      /* The output line number is small enough that we are still in the
71959      ** main program. */
71960      pOp = &p->aOp[i];
71961    }else{
71962      /* We are currently listing subprograms.  Figure out which one and
71963      ** pick up the appropriate opcode. */
71964      int j;
71965      i -= p->nOp;
71966      for(j=0; i>=apSub[j]->nOp; j++){
71967        i -= apSub[j]->nOp;
71968      }
71969      pOp = &apSub[j]->aOp[i];
71970    }
71971    if( p->explain==1 ){
71972      pMem->flags = MEM_Int;
71973      pMem->u.i = i;                                /* Program counter */
71974      pMem++;
71975
71976      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
71977      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
71978      assert( pMem->z!=0 );
71979      pMem->n = sqlite3Strlen30(pMem->z);
71980      pMem->enc = SQLITE_UTF8;
71981      pMem++;
71982
71983      /* When an OP_Program opcode is encounter (the only opcode that has
71984      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
71985      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
71986      ** has not already been seen.
71987      */
71988      if( pOp->p4type==P4_SUBPROGRAM ){
71989        int nByte = (nSub+1)*sizeof(SubProgram*);
71990        int j;
71991        for(j=0; j<nSub; j++){
71992          if( apSub[j]==pOp->p4.pProgram ) break;
71993        }
71994        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
71995          apSub = (SubProgram **)pSub->z;
71996          apSub[nSub++] = pOp->p4.pProgram;
71997          pSub->flags |= MEM_Blob;
71998          pSub->n = nSub*sizeof(SubProgram*);
71999        }
72000      }
72001    }
72002
72003    pMem->flags = MEM_Int;
72004    pMem->u.i = pOp->p1;                          /* P1 */
72005    pMem++;
72006
72007    pMem->flags = MEM_Int;
72008    pMem->u.i = pOp->p2;                          /* P2 */
72009    pMem++;
72010
72011    pMem->flags = MEM_Int;
72012    pMem->u.i = pOp->p3;                          /* P3 */
72013    pMem++;
72014
72015    if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
72016      assert( p->db->mallocFailed );
72017      return SQLITE_ERROR;
72018    }
72019    pMem->flags = MEM_Str|MEM_Term;
72020    zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
72021    if( zP4!=pMem->z ){
72022      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
72023    }else{
72024      assert( pMem->z!=0 );
72025      pMem->n = sqlite3Strlen30(pMem->z);
72026      pMem->enc = SQLITE_UTF8;
72027    }
72028    pMem++;
72029
72030    if( p->explain==1 ){
72031      if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
72032        assert( p->db->mallocFailed );
72033        return SQLITE_ERROR;
72034      }
72035      pMem->flags = MEM_Str|MEM_Term;
72036      pMem->n = 2;
72037      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
72038      pMem->enc = SQLITE_UTF8;
72039      pMem++;
72040
72041#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72042      if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
72043        assert( p->db->mallocFailed );
72044        return SQLITE_ERROR;
72045      }
72046      pMem->flags = MEM_Str|MEM_Term;
72047      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
72048      pMem->enc = SQLITE_UTF8;
72049#else
72050      pMem->flags = MEM_Null;                       /* Comment */
72051#endif
72052    }
72053
72054    p->nResColumn = 8 - 4*(p->explain-1);
72055    p->pResultSet = &p->aMem[1];
72056    p->rc = SQLITE_OK;
72057    rc = SQLITE_ROW;
72058  }
72059  return rc;
72060}
72061#endif /* SQLITE_OMIT_EXPLAIN */
72062
72063#ifdef SQLITE_DEBUG
72064/*
72065** Print the SQL that was used to generate a VDBE program.
72066*/
72067SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
72068  const char *z = 0;
72069  if( p->zSql ){
72070    z = p->zSql;
72071  }else if( p->nOp>=1 ){
72072    const VdbeOp *pOp = &p->aOp[0];
72073    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72074      z = pOp->p4.z;
72075      while( sqlite3Isspace(*z) ) z++;
72076    }
72077  }
72078  if( z ) printf("SQL: [%s]\n", z);
72079}
72080#endif
72081
72082#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
72083/*
72084** Print an IOTRACE message showing SQL content.
72085*/
72086SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
72087  int nOp = p->nOp;
72088  VdbeOp *pOp;
72089  if( sqlite3IoTrace==0 ) return;
72090  if( nOp<1 ) return;
72091  pOp = &p->aOp[0];
72092  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72093    int i, j;
72094    char z[1000];
72095    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
72096    for(i=0; sqlite3Isspace(z[i]); i++){}
72097    for(j=0; z[i]; i++){
72098      if( sqlite3Isspace(z[i]) ){
72099        if( z[i-1]!=' ' ){
72100          z[j++] = ' ';
72101        }
72102      }else{
72103        z[j++] = z[i];
72104      }
72105    }
72106    z[j] = 0;
72107    sqlite3IoTrace("SQL %s\n", z);
72108  }
72109}
72110#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
72111
72112/* An instance of this object describes bulk memory available for use
72113** by subcomponents of a prepared statement.  Space is allocated out
72114** of a ReusableSpace object by the allocSpace() routine below.
72115*/
72116struct ReusableSpace {
72117  u8 *pSpace;          /* Available memory */
72118  int nFree;           /* Bytes of available memory */
72119  int nNeeded;         /* Total bytes that could not be allocated */
72120};
72121
72122/* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
72123** from the ReusableSpace object.  Return a pointer to the allocated
72124** memory on success.  If insufficient memory is available in the
72125** ReusableSpace object, increase the ReusableSpace.nNeeded
72126** value by the amount needed and return NULL.
72127**
72128** If pBuf is not initially NULL, that means that the memory has already
72129** been allocated by a prior call to this routine, so just return a copy
72130** of pBuf and leave ReusableSpace unchanged.
72131**
72132** This allocator is employed to repurpose unused slots at the end of the
72133** opcode array of prepared state for other memory needs of the prepared
72134** statement.
72135*/
72136static void *allocSpace(
72137  struct ReusableSpace *p,  /* Bulk memory available for allocation */
72138  void *pBuf,               /* Pointer to a prior allocation */
72139  int nByte                 /* Bytes of memory needed */
72140){
72141  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
72142  if( pBuf==0 ){
72143    nByte = ROUND8(nByte);
72144    if( nByte <= p->nFree ){
72145      p->nFree -= nByte;
72146      pBuf = &p->pSpace[p->nFree];
72147    }else{
72148      p->nNeeded += nByte;
72149    }
72150  }
72151  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
72152  return pBuf;
72153}
72154
72155/*
72156** Rewind the VDBE back to the beginning in preparation for
72157** running it.
72158*/
72159SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
72160#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
72161  int i;
72162#endif
72163  assert( p!=0 );
72164  assert( p->magic==VDBE_MAGIC_INIT );
72165
72166  /* There should be at least one opcode.
72167  */
72168  assert( p->nOp>0 );
72169
72170  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
72171  p->magic = VDBE_MAGIC_RUN;
72172
72173#ifdef SQLITE_DEBUG
72174  for(i=0; i<p->nMem; i++){
72175    assert( p->aMem[i].db==p->db );
72176  }
72177#endif
72178  p->pc = -1;
72179  p->rc = SQLITE_OK;
72180  p->errorAction = OE_Abort;
72181  p->nChange = 0;
72182  p->cacheCtr = 1;
72183  p->minWriteFileFormat = 255;
72184  p->iStatement = 0;
72185  p->nFkConstraint = 0;
72186#ifdef VDBE_PROFILE
72187  for(i=0; i<p->nOp; i++){
72188    p->aOp[i].cnt = 0;
72189    p->aOp[i].cycles = 0;
72190  }
72191#endif
72192}
72193
72194/*
72195** Prepare a virtual machine for execution for the first time after
72196** creating the virtual machine.  This involves things such
72197** as allocating registers and initializing the program counter.
72198** After the VDBE has be prepped, it can be executed by one or more
72199** calls to sqlite3VdbeExec().
72200**
72201** This function may be called exactly once on each virtual machine.
72202** After this routine is called the VM has been "packaged" and is ready
72203** to run.  After this routine is called, further calls to
72204** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
72205** the Vdbe from the Parse object that helped generate it so that the
72206** the Vdbe becomes an independent entity and the Parse object can be
72207** destroyed.
72208**
72209** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
72210** to its initial state after it has been run.
72211*/
72212SQLITE_PRIVATE void sqlite3VdbeMakeReady(
72213  Vdbe *p,                       /* The VDBE */
72214  Parse *pParse                  /* Parsing context */
72215){
72216  sqlite3 *db;                   /* The database connection */
72217  int nVar;                      /* Number of parameters */
72218  int nMem;                      /* Number of VM memory registers */
72219  int nCursor;                   /* Number of cursors required */
72220  int nArg;                      /* Number of arguments in subprograms */
72221  int nOnce;                     /* Number of OP_Once instructions */
72222  int n;                         /* Loop counter */
72223  struct ReusableSpace x;        /* Reusable bulk memory */
72224
72225  assert( p!=0 );
72226  assert( p->nOp>0 );
72227  assert( pParse!=0 );
72228  assert( p->magic==VDBE_MAGIC_INIT );
72229  assert( pParse==p->pParse );
72230  db = p->db;
72231  assert( db->mallocFailed==0 );
72232  nVar = pParse->nVar;
72233  nMem = pParse->nMem;
72234  nCursor = pParse->nTab;
72235  nArg = pParse->nMaxArg;
72236  nOnce = pParse->nOnce;
72237  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
72238
72239  /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
72240  ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
72241  ** space at the end of aMem[] for cursors 1 and greater.
72242  ** See also: allocateCursor().
72243  */
72244  nMem += nCursor;
72245  if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
72246
72247  /* Figure out how much reusable memory is available at the end of the
72248  ** opcode array.  This extra memory will be reallocated for other elements
72249  ** of the prepared statement.
72250  */
72251  n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
72252  x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
72253  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
72254  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
72255  assert( x.nFree>=0 );
72256  if( x.nFree>0 ){
72257    memset(x.pSpace, 0, x.nFree);
72258    assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
72259  }
72260
72261  resolveP2Values(p, &nArg);
72262  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
72263  if( pParse->explain && nMem<10 ){
72264    nMem = 10;
72265  }
72266  p->expired = 0;
72267
72268  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
72269  ** passes.  On the first pass, we try to reuse unused memory at the
72270  ** end of the opcode array.  If we are unable to satisfy all memory
72271  ** requirements by reusing the opcode array tail, then the second
72272  ** pass will fill in the remainder using a fresh memory allocation.
72273  **
72274  ** This two-pass approach that reuses as much memory as possible from
72275  ** the leftover memory at the end of the opcode array.  This can significantly
72276  ** reduce the amount of memory held by a prepared statement.
72277  */
72278  do {
72279    x.nNeeded = 0;
72280    p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
72281    p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
72282    p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
72283    p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
72284    p->aOnceFlag = allocSpace(&x, p->aOnceFlag, nOnce);
72285#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72286    p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
72287#endif
72288    if( x.nNeeded==0 ) break;
72289    x.pSpace = p->pFree = sqlite3DbMallocZero(db, x.nNeeded);
72290    x.nFree = x.nNeeded;
72291  }while( !db->mallocFailed );
72292
72293  p->nCursor = nCursor;
72294  p->nOnceFlag = nOnce;
72295  if( p->aVar ){
72296    p->nVar = (ynVar)nVar;
72297    for(n=0; n<nVar; n++){
72298      p->aVar[n].flags = MEM_Null;
72299      p->aVar[n].db = db;
72300    }
72301  }
72302  p->nzVar = pParse->nzVar;
72303  p->azVar = pParse->azVar;
72304  pParse->nzVar =  0;
72305  pParse->azVar = 0;
72306  if( p->aMem ){
72307    p->nMem = nMem;
72308    for(n=0; n<nMem; n++){
72309      p->aMem[n].flags = MEM_Undefined;
72310      p->aMem[n].db = db;
72311    }
72312  }
72313  p->explain = pParse->explain;
72314  sqlite3VdbeRewind(p);
72315}
72316
72317/*
72318** Close a VDBE cursor and release all the resources that cursor
72319** happens to hold.
72320*/
72321SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
72322  if( pCx==0 ){
72323    return;
72324  }
72325  assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
72326  switch( pCx->eCurType ){
72327    case CURTYPE_SORTER: {
72328      sqlite3VdbeSorterClose(p->db, pCx);
72329      break;
72330    }
72331    case CURTYPE_BTREE: {
72332      if( pCx->pBt ){
72333        sqlite3BtreeClose(pCx->pBt);
72334        /* The pCx->pCursor will be close automatically, if it exists, by
72335        ** the call above. */
72336      }else{
72337        assert( pCx->uc.pCursor!=0 );
72338        sqlite3BtreeCloseCursor(pCx->uc.pCursor);
72339      }
72340      break;
72341    }
72342#ifndef SQLITE_OMIT_VIRTUALTABLE
72343    case CURTYPE_VTAB: {
72344      sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
72345      const sqlite3_module *pModule = pVCur->pVtab->pModule;
72346      assert( pVCur->pVtab->nRef>0 );
72347      pVCur->pVtab->nRef--;
72348      pModule->xClose(pVCur);
72349      break;
72350    }
72351#endif
72352  }
72353}
72354
72355/*
72356** Close all cursors in the current frame.
72357*/
72358static void closeCursorsInFrame(Vdbe *p){
72359  if( p->apCsr ){
72360    int i;
72361    for(i=0; i<p->nCursor; i++){
72362      VdbeCursor *pC = p->apCsr[i];
72363      if( pC ){
72364        sqlite3VdbeFreeCursor(p, pC);
72365        p->apCsr[i] = 0;
72366      }
72367    }
72368  }
72369}
72370
72371/*
72372** Copy the values stored in the VdbeFrame structure to its Vdbe. This
72373** is used, for example, when a trigger sub-program is halted to restore
72374** control to the main program.
72375*/
72376SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
72377  Vdbe *v = pFrame->v;
72378  closeCursorsInFrame(v);
72379#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72380  v->anExec = pFrame->anExec;
72381#endif
72382  v->aOnceFlag = pFrame->aOnceFlag;
72383  v->nOnceFlag = pFrame->nOnceFlag;
72384  v->aOp = pFrame->aOp;
72385  v->nOp = pFrame->nOp;
72386  v->aMem = pFrame->aMem;
72387  v->nMem = pFrame->nMem;
72388  v->apCsr = pFrame->apCsr;
72389  v->nCursor = pFrame->nCursor;
72390  v->db->lastRowid = pFrame->lastRowid;
72391  v->nChange = pFrame->nChange;
72392  v->db->nChange = pFrame->nDbChange;
72393  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
72394  v->pAuxData = pFrame->pAuxData;
72395  pFrame->pAuxData = 0;
72396  return pFrame->pc;
72397}
72398
72399/*
72400** Close all cursors.
72401**
72402** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
72403** cell array. This is necessary as the memory cell array may contain
72404** pointers to VdbeFrame objects, which may in turn contain pointers to
72405** open cursors.
72406*/
72407static void closeAllCursors(Vdbe *p){
72408  if( p->pFrame ){
72409    VdbeFrame *pFrame;
72410    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
72411    sqlite3VdbeFrameRestore(pFrame);
72412    p->pFrame = 0;
72413    p->nFrame = 0;
72414  }
72415  assert( p->nFrame==0 );
72416  closeCursorsInFrame(p);
72417  if( p->aMem ){
72418    releaseMemArray(p->aMem, p->nMem);
72419  }
72420  while( p->pDelFrame ){
72421    VdbeFrame *pDel = p->pDelFrame;
72422    p->pDelFrame = pDel->pParent;
72423    sqlite3VdbeFrameDelete(pDel);
72424  }
72425
72426  /* Delete any auxdata allocations made by the VM */
72427  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
72428  assert( p->pAuxData==0 );
72429}
72430
72431/*
72432** Clean up the VM after a single run.
72433*/
72434static void Cleanup(Vdbe *p){
72435  sqlite3 *db = p->db;
72436
72437#ifdef SQLITE_DEBUG
72438  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
72439  ** Vdbe.aMem[] arrays have already been cleaned up.  */
72440  int i;
72441  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
72442  if( p->aMem ){
72443    for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
72444  }
72445#endif
72446
72447  sqlite3DbFree(db, p->zErrMsg);
72448  p->zErrMsg = 0;
72449  p->pResultSet = 0;
72450}
72451
72452/*
72453** Set the number of result columns that will be returned by this SQL
72454** statement. This is now set at compile time, rather than during
72455** execution of the vdbe program so that sqlite3_column_count() can
72456** be called on an SQL statement before sqlite3_step().
72457*/
72458SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
72459  Mem *pColName;
72460  int n;
72461  sqlite3 *db = p->db;
72462
72463  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
72464  sqlite3DbFree(db, p->aColName);
72465  n = nResColumn*COLNAME_N;
72466  p->nResColumn = (u16)nResColumn;
72467  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
72468  if( p->aColName==0 ) return;
72469  while( n-- > 0 ){
72470    pColName->flags = MEM_Null;
72471    pColName->db = p->db;
72472    pColName++;
72473  }
72474}
72475
72476/*
72477** Set the name of the idx'th column to be returned by the SQL statement.
72478** zName must be a pointer to a nul terminated string.
72479**
72480** This call must be made after a call to sqlite3VdbeSetNumCols().
72481**
72482** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
72483** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
72484** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
72485*/
72486SQLITE_PRIVATE int sqlite3VdbeSetColName(
72487  Vdbe *p,                         /* Vdbe being configured */
72488  int idx,                         /* Index of column zName applies to */
72489  int var,                         /* One of the COLNAME_* constants */
72490  const char *zName,               /* Pointer to buffer containing name */
72491  void (*xDel)(void*)              /* Memory management strategy for zName */
72492){
72493  int rc;
72494  Mem *pColName;
72495  assert( idx<p->nResColumn );
72496  assert( var<COLNAME_N );
72497  if( p->db->mallocFailed ){
72498    assert( !zName || xDel!=SQLITE_DYNAMIC );
72499    return SQLITE_NOMEM_BKPT;
72500  }
72501  assert( p->aColName!=0 );
72502  pColName = &(p->aColName[idx+var*p->nResColumn]);
72503  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
72504  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
72505  return rc;
72506}
72507
72508/*
72509** A read or write transaction may or may not be active on database handle
72510** db. If a transaction is active, commit it. If there is a
72511** write-transaction spanning more than one database file, this routine
72512** takes care of the master journal trickery.
72513*/
72514static int vdbeCommit(sqlite3 *db, Vdbe *p){
72515  int i;
72516  int nTrans = 0;  /* Number of databases with an active write-transaction
72517                   ** that are candidates for a two-phase commit using a
72518                   ** master-journal */
72519  int rc = SQLITE_OK;
72520  int needXcommit = 0;
72521
72522#ifdef SQLITE_OMIT_VIRTUALTABLE
72523  /* With this option, sqlite3VtabSync() is defined to be simply
72524  ** SQLITE_OK so p is not used.
72525  */
72526  UNUSED_PARAMETER(p);
72527#endif
72528
72529  /* Before doing anything else, call the xSync() callback for any
72530  ** virtual module tables written in this transaction. This has to
72531  ** be done before determining whether a master journal file is
72532  ** required, as an xSync() callback may add an attached database
72533  ** to the transaction.
72534  */
72535  rc = sqlite3VtabSync(db, p);
72536
72537  /* This loop determines (a) if the commit hook should be invoked and
72538  ** (b) how many database files have open write transactions, not
72539  ** including the temp database. (b) is important because if more than
72540  ** one database file has an open write transaction, a master journal
72541  ** file is required for an atomic commit.
72542  */
72543  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72544    Btree *pBt = db->aDb[i].pBt;
72545    if( sqlite3BtreeIsInTrans(pBt) ){
72546      /* Whether or not a database might need a master journal depends upon
72547      ** its journal mode (among other things).  This matrix determines which
72548      ** journal modes use a master journal and which do not */
72549      static const u8 aMJNeeded[] = {
72550        /* DELETE   */  1,
72551        /* PERSIST   */ 1,
72552        /* OFF       */ 0,
72553        /* TRUNCATE  */ 1,
72554        /* MEMORY    */ 0,
72555        /* WAL       */ 0
72556      };
72557      Pager *pPager;   /* Pager associated with pBt */
72558      needXcommit = 1;
72559      sqlite3BtreeEnter(pBt);
72560      pPager = sqlite3BtreePager(pBt);
72561      if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
72562       && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
72563      ){
72564        assert( i!=1 );
72565        nTrans++;
72566      }
72567      rc = sqlite3PagerExclusiveLock(pPager);
72568      sqlite3BtreeLeave(pBt);
72569    }
72570  }
72571  if( rc!=SQLITE_OK ){
72572    return rc;
72573  }
72574
72575  /* If there are any write-transactions at all, invoke the commit hook */
72576  if( needXcommit && db->xCommitCallback ){
72577    rc = db->xCommitCallback(db->pCommitArg);
72578    if( rc ){
72579      return SQLITE_CONSTRAINT_COMMITHOOK;
72580    }
72581  }
72582
72583  /* The simple case - no more than one database file (not counting the
72584  ** TEMP database) has a transaction active.   There is no need for the
72585  ** master-journal.
72586  **
72587  ** If the return value of sqlite3BtreeGetFilename() is a zero length
72588  ** string, it means the main database is :memory: or a temp file.  In
72589  ** that case we do not support atomic multi-file commits, so use the
72590  ** simple case then too.
72591  */
72592  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
72593   || nTrans<=1
72594  ){
72595    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72596      Btree *pBt = db->aDb[i].pBt;
72597      if( pBt ){
72598        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
72599      }
72600    }
72601
72602    /* Do the commit only if all databases successfully complete phase 1.
72603    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
72604    ** IO error while deleting or truncating a journal file. It is unlikely,
72605    ** but could happen. In this case abandon processing and return the error.
72606    */
72607    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72608      Btree *pBt = db->aDb[i].pBt;
72609      if( pBt ){
72610        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
72611      }
72612    }
72613    if( rc==SQLITE_OK ){
72614      sqlite3VtabCommit(db);
72615    }
72616  }
72617
72618  /* The complex case - There is a multi-file write-transaction active.
72619  ** This requires a master journal file to ensure the transaction is
72620  ** committed atomically.
72621  */
72622#ifndef SQLITE_OMIT_DISKIO
72623  else{
72624    sqlite3_vfs *pVfs = db->pVfs;
72625    char *zMaster = 0;   /* File-name for the master journal */
72626    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
72627    sqlite3_file *pMaster = 0;
72628    i64 offset = 0;
72629    int res;
72630    int retryCount = 0;
72631    int nMainFile;
72632
72633    /* Select a master journal file name */
72634    nMainFile = sqlite3Strlen30(zMainFile);
72635    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
72636    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
72637    do {
72638      u32 iRandom;
72639      if( retryCount ){
72640        if( retryCount>100 ){
72641          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
72642          sqlite3OsDelete(pVfs, zMaster, 0);
72643          break;
72644        }else if( retryCount==1 ){
72645          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
72646        }
72647      }
72648      retryCount++;
72649      sqlite3_randomness(sizeof(iRandom), &iRandom);
72650      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
72651                               (iRandom>>8)&0xffffff, iRandom&0xff);
72652      /* The antipenultimate character of the master journal name must
72653      ** be "9" to avoid name collisions when using 8+3 filenames. */
72654      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
72655      sqlite3FileSuffix3(zMainFile, zMaster);
72656      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
72657    }while( rc==SQLITE_OK && res );
72658    if( rc==SQLITE_OK ){
72659      /* Open the master journal. */
72660      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
72661          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
72662          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
72663      );
72664    }
72665    if( rc!=SQLITE_OK ){
72666      sqlite3DbFree(db, zMaster);
72667      return rc;
72668    }
72669
72670    /* Write the name of each database file in the transaction into the new
72671    ** master journal file. If an error occurs at this point close
72672    ** and delete the master journal file. All the individual journal files
72673    ** still have 'null' as the master journal pointer, so they will roll
72674    ** back independently if a failure occurs.
72675    */
72676    for(i=0; i<db->nDb; i++){
72677      Btree *pBt = db->aDb[i].pBt;
72678      if( sqlite3BtreeIsInTrans(pBt) ){
72679        char const *zFile = sqlite3BtreeGetJournalname(pBt);
72680        if( zFile==0 ){
72681          continue;  /* Ignore TEMP and :memory: databases */
72682        }
72683        assert( zFile[0]!=0 );
72684        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
72685        offset += sqlite3Strlen30(zFile)+1;
72686        if( rc!=SQLITE_OK ){
72687          sqlite3OsCloseFree(pMaster);
72688          sqlite3OsDelete(pVfs, zMaster, 0);
72689          sqlite3DbFree(db, zMaster);
72690          return rc;
72691        }
72692      }
72693    }
72694
72695    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
72696    ** flag is set this is not required.
72697    */
72698    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
72699     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
72700    ){
72701      sqlite3OsCloseFree(pMaster);
72702      sqlite3OsDelete(pVfs, zMaster, 0);
72703      sqlite3DbFree(db, zMaster);
72704      return rc;
72705    }
72706
72707    /* Sync all the db files involved in the transaction. The same call
72708    ** sets the master journal pointer in each individual journal. If
72709    ** an error occurs here, do not delete the master journal file.
72710    **
72711    ** If the error occurs during the first call to
72712    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
72713    ** master journal file will be orphaned. But we cannot delete it,
72714    ** in case the master journal file name was written into the journal
72715    ** file before the failure occurred.
72716    */
72717    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72718      Btree *pBt = db->aDb[i].pBt;
72719      if( pBt ){
72720        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
72721      }
72722    }
72723    sqlite3OsCloseFree(pMaster);
72724    assert( rc!=SQLITE_BUSY );
72725    if( rc!=SQLITE_OK ){
72726      sqlite3DbFree(db, zMaster);
72727      return rc;
72728    }
72729
72730    /* Delete the master journal file. This commits the transaction. After
72731    ** doing this the directory is synced again before any individual
72732    ** transaction files are deleted.
72733    */
72734    rc = sqlite3OsDelete(pVfs, zMaster, 1);
72735    sqlite3DbFree(db, zMaster);
72736    zMaster = 0;
72737    if( rc ){
72738      return rc;
72739    }
72740
72741    /* All files and directories have already been synced, so the following
72742    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
72743    ** deleting or truncating journals. If something goes wrong while
72744    ** this is happening we don't really care. The integrity of the
72745    ** transaction is already guaranteed, but some stray 'cold' journals
72746    ** may be lying around. Returning an error code won't help matters.
72747    */
72748    disable_simulated_io_errors();
72749    sqlite3BeginBenignMalloc();
72750    for(i=0; i<db->nDb; i++){
72751      Btree *pBt = db->aDb[i].pBt;
72752      if( pBt ){
72753        sqlite3BtreeCommitPhaseTwo(pBt, 1);
72754      }
72755    }
72756    sqlite3EndBenignMalloc();
72757    enable_simulated_io_errors();
72758
72759    sqlite3VtabCommit(db);
72760  }
72761#endif
72762
72763  return rc;
72764}
72765
72766/*
72767** This routine checks that the sqlite3.nVdbeActive count variable
72768** matches the number of vdbe's in the list sqlite3.pVdbe that are
72769** currently active. An assertion fails if the two counts do not match.
72770** This is an internal self-check only - it is not an essential processing
72771** step.
72772**
72773** This is a no-op if NDEBUG is defined.
72774*/
72775#ifndef NDEBUG
72776static void checkActiveVdbeCnt(sqlite3 *db){
72777  Vdbe *p;
72778  int cnt = 0;
72779  int nWrite = 0;
72780  int nRead = 0;
72781  p = db->pVdbe;
72782  while( p ){
72783    if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
72784      cnt++;
72785      if( p->readOnly==0 ) nWrite++;
72786      if( p->bIsReader ) nRead++;
72787    }
72788    p = p->pNext;
72789  }
72790  assert( cnt==db->nVdbeActive );
72791  assert( nWrite==db->nVdbeWrite );
72792  assert( nRead==db->nVdbeRead );
72793}
72794#else
72795#define checkActiveVdbeCnt(x)
72796#endif
72797
72798/*
72799** If the Vdbe passed as the first argument opened a statement-transaction,
72800** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
72801** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
72802** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
72803** statement transaction is committed.
72804**
72805** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
72806** Otherwise SQLITE_OK.
72807*/
72808SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
72809  sqlite3 *const db = p->db;
72810  int rc = SQLITE_OK;
72811
72812  /* If p->iStatement is greater than zero, then this Vdbe opened a
72813  ** statement transaction that should be closed here. The only exception
72814  ** is that an IO error may have occurred, causing an emergency rollback.
72815  ** In this case (db->nStatement==0), and there is nothing to do.
72816  */
72817  if( db->nStatement && p->iStatement ){
72818    int i;
72819    const int iSavepoint = p->iStatement-1;
72820
72821    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
72822    assert( db->nStatement>0 );
72823    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
72824
72825    for(i=0; i<db->nDb; i++){
72826      int rc2 = SQLITE_OK;
72827      Btree *pBt = db->aDb[i].pBt;
72828      if( pBt ){
72829        if( eOp==SAVEPOINT_ROLLBACK ){
72830          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
72831        }
72832        if( rc2==SQLITE_OK ){
72833          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
72834        }
72835        if( rc==SQLITE_OK ){
72836          rc = rc2;
72837        }
72838      }
72839    }
72840    db->nStatement--;
72841    p->iStatement = 0;
72842
72843    if( rc==SQLITE_OK ){
72844      if( eOp==SAVEPOINT_ROLLBACK ){
72845        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
72846      }
72847      if( rc==SQLITE_OK ){
72848        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
72849      }
72850    }
72851
72852    /* If the statement transaction is being rolled back, also restore the
72853    ** database handles deferred constraint counter to the value it had when
72854    ** the statement transaction was opened.  */
72855    if( eOp==SAVEPOINT_ROLLBACK ){
72856      db->nDeferredCons = p->nStmtDefCons;
72857      db->nDeferredImmCons = p->nStmtDefImmCons;
72858    }
72859  }
72860  return rc;
72861}
72862
72863/*
72864** This function is called when a transaction opened by the database
72865** handle associated with the VM passed as an argument is about to be
72866** committed. If there are outstanding deferred foreign key constraint
72867** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
72868**
72869** If there are outstanding FK violations and this function returns
72870** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
72871** and write an error message to it. Then return SQLITE_ERROR.
72872*/
72873#ifndef SQLITE_OMIT_FOREIGN_KEY
72874SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
72875  sqlite3 *db = p->db;
72876  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
72877   || (!deferred && p->nFkConstraint>0)
72878  ){
72879    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
72880    p->errorAction = OE_Abort;
72881    sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
72882    return SQLITE_ERROR;
72883  }
72884  return SQLITE_OK;
72885}
72886#endif
72887
72888/*
72889** This routine is called the when a VDBE tries to halt.  If the VDBE
72890** has made changes and is in autocommit mode, then commit those
72891** changes.  If a rollback is needed, then do the rollback.
72892**
72893** This routine is the only way to move the state of a VM from
72894** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
72895** call this on a VM that is in the SQLITE_MAGIC_HALT state.
72896**
72897** Return an error code.  If the commit could not complete because of
72898** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
72899** means the close did not happen and needs to be repeated.
72900*/
72901SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
72902  int rc;                         /* Used to store transient return codes */
72903  sqlite3 *db = p->db;
72904
72905  /* This function contains the logic that determines if a statement or
72906  ** transaction will be committed or rolled back as a result of the
72907  ** execution of this virtual machine.
72908  **
72909  ** If any of the following errors occur:
72910  **
72911  **     SQLITE_NOMEM
72912  **     SQLITE_IOERR
72913  **     SQLITE_FULL
72914  **     SQLITE_INTERRUPT
72915  **
72916  ** Then the internal cache might have been left in an inconsistent
72917  ** state.  We need to rollback the statement transaction, if there is
72918  ** one, or the complete transaction if there is no statement transaction.
72919  */
72920
72921  if( db->mallocFailed ){
72922    p->rc = SQLITE_NOMEM_BKPT;
72923  }
72924  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
72925  closeAllCursors(p);
72926  if( p->magic!=VDBE_MAGIC_RUN ){
72927    return SQLITE_OK;
72928  }
72929  checkActiveVdbeCnt(db);
72930
72931  /* No commit or rollback needed if the program never started or if the
72932  ** SQL statement does not read or write a database file.  */
72933  if( p->pc>=0 && p->bIsReader ){
72934    int mrc;   /* Primary error code from p->rc */
72935    int eStatementOp = 0;
72936    int isSpecialError;            /* Set to true if a 'special' error */
72937
72938    /* Lock all btrees used by the statement */
72939    sqlite3VdbeEnter(p);
72940
72941    /* Check for one of the special errors */
72942    mrc = p->rc & 0xff;
72943    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
72944                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
72945    if( isSpecialError ){
72946      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
72947      ** no rollback is necessary. Otherwise, at least a savepoint
72948      ** transaction must be rolled back to restore the database to a
72949      ** consistent state.
72950      **
72951      ** Even if the statement is read-only, it is important to perform
72952      ** a statement or transaction rollback operation. If the error
72953      ** occurred while writing to the journal, sub-journal or database
72954      ** file as part of an effort to free up cache space (see function
72955      ** pagerStress() in pager.c), the rollback is required to restore
72956      ** the pager to a consistent state.
72957      */
72958      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
72959        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
72960          eStatementOp = SAVEPOINT_ROLLBACK;
72961        }else{
72962          /* We are forced to roll back the active transaction. Before doing
72963          ** so, abort any other statements this handle currently has active.
72964          */
72965          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
72966          sqlite3CloseSavepoints(db);
72967          db->autoCommit = 1;
72968          p->nChange = 0;
72969        }
72970      }
72971    }
72972
72973    /* Check for immediate foreign key violations. */
72974    if( p->rc==SQLITE_OK ){
72975      sqlite3VdbeCheckFk(p, 0);
72976    }
72977
72978    /* If the auto-commit flag is set and this is the only active writer
72979    ** VM, then we do either a commit or rollback of the current transaction.
72980    **
72981    ** Note: This block also runs if one of the special errors handled
72982    ** above has occurred.
72983    */
72984    if( !sqlite3VtabInSync(db)
72985     && db->autoCommit
72986     && db->nVdbeWrite==(p->readOnly==0)
72987    ){
72988      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
72989        rc = sqlite3VdbeCheckFk(p, 1);
72990        if( rc!=SQLITE_OK ){
72991          if( NEVER(p->readOnly) ){
72992            sqlite3VdbeLeave(p);
72993            return SQLITE_ERROR;
72994          }
72995          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
72996        }else{
72997          /* The auto-commit flag is true, the vdbe program was successful
72998          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
72999          ** key constraints to hold up the transaction. This means a commit
73000          ** is required. */
73001          rc = vdbeCommit(db, p);
73002        }
73003        if( rc==SQLITE_BUSY && p->readOnly ){
73004          sqlite3VdbeLeave(p);
73005          return SQLITE_BUSY;
73006        }else if( rc!=SQLITE_OK ){
73007          p->rc = rc;
73008          sqlite3RollbackAll(db, SQLITE_OK);
73009          p->nChange = 0;
73010        }else{
73011          db->nDeferredCons = 0;
73012          db->nDeferredImmCons = 0;
73013          db->flags &= ~SQLITE_DeferFKs;
73014          sqlite3CommitInternalChanges(db);
73015        }
73016      }else{
73017        sqlite3RollbackAll(db, SQLITE_OK);
73018        p->nChange = 0;
73019      }
73020      db->nStatement = 0;
73021    }else if( eStatementOp==0 ){
73022      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
73023        eStatementOp = SAVEPOINT_RELEASE;
73024      }else if( p->errorAction==OE_Abort ){
73025        eStatementOp = SAVEPOINT_ROLLBACK;
73026      }else{
73027        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73028        sqlite3CloseSavepoints(db);
73029        db->autoCommit = 1;
73030        p->nChange = 0;
73031      }
73032    }
73033
73034    /* If eStatementOp is non-zero, then a statement transaction needs to
73035    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
73036    ** do so. If this operation returns an error, and the current statement
73037    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
73038    ** current statement error code.
73039    */
73040    if( eStatementOp ){
73041      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
73042      if( rc ){
73043        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
73044          p->rc = rc;
73045          sqlite3DbFree(db, p->zErrMsg);
73046          p->zErrMsg = 0;
73047        }
73048        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73049        sqlite3CloseSavepoints(db);
73050        db->autoCommit = 1;
73051        p->nChange = 0;
73052      }
73053    }
73054
73055    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
73056    ** has been rolled back, update the database connection change-counter.
73057    */
73058    if( p->changeCntOn ){
73059      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
73060        sqlite3VdbeSetChanges(db, p->nChange);
73061      }else{
73062        sqlite3VdbeSetChanges(db, 0);
73063      }
73064      p->nChange = 0;
73065    }
73066
73067    /* Release the locks */
73068    sqlite3VdbeLeave(p);
73069  }
73070
73071  /* We have successfully halted and closed the VM.  Record this fact. */
73072  if( p->pc>=0 ){
73073    db->nVdbeActive--;
73074    if( !p->readOnly ) db->nVdbeWrite--;
73075    if( p->bIsReader ) db->nVdbeRead--;
73076    assert( db->nVdbeActive>=db->nVdbeRead );
73077    assert( db->nVdbeRead>=db->nVdbeWrite );
73078    assert( db->nVdbeWrite>=0 );
73079  }
73080  p->magic = VDBE_MAGIC_HALT;
73081  checkActiveVdbeCnt(db);
73082  if( db->mallocFailed ){
73083    p->rc = SQLITE_NOMEM_BKPT;
73084  }
73085
73086  /* If the auto-commit flag is set to true, then any locks that were held
73087  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
73088  ** to invoke any required unlock-notify callbacks.
73089  */
73090  if( db->autoCommit ){
73091    sqlite3ConnectionUnlocked(db);
73092  }
73093
73094  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
73095  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
73096}
73097
73098
73099/*
73100** Each VDBE holds the result of the most recent sqlite3_step() call
73101** in p->rc.  This routine sets that result back to SQLITE_OK.
73102*/
73103SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
73104  p->rc = SQLITE_OK;
73105}
73106
73107/*
73108** Copy the error code and error message belonging to the VDBE passed
73109** as the first argument to its database handle (so that they will be
73110** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
73111**
73112** This function does not clear the VDBE error code or message, just
73113** copies them to the database handle.
73114*/
73115SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
73116  sqlite3 *db = p->db;
73117  int rc = p->rc;
73118  if( p->zErrMsg ){
73119    db->bBenignMalloc++;
73120    sqlite3BeginBenignMalloc();
73121    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
73122    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
73123    sqlite3EndBenignMalloc();
73124    db->bBenignMalloc--;
73125    db->errCode = rc;
73126  }else{
73127    sqlite3Error(db, rc);
73128  }
73129  return rc;
73130}
73131
73132#ifdef SQLITE_ENABLE_SQLLOG
73133/*
73134** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
73135** invoke it.
73136*/
73137static void vdbeInvokeSqllog(Vdbe *v){
73138  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
73139    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
73140    assert( v->db->init.busy==0 );
73141    if( zExpanded ){
73142      sqlite3GlobalConfig.xSqllog(
73143          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
73144      );
73145      sqlite3DbFree(v->db, zExpanded);
73146    }
73147  }
73148}
73149#else
73150# define vdbeInvokeSqllog(x)
73151#endif
73152
73153/*
73154** Clean up a VDBE after execution but do not delete the VDBE just yet.
73155** Write any error messages into *pzErrMsg.  Return the result code.
73156**
73157** After this routine is run, the VDBE should be ready to be executed
73158** again.
73159**
73160** To look at it another way, this routine resets the state of the
73161** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
73162** VDBE_MAGIC_INIT.
73163*/
73164SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
73165  sqlite3 *db;
73166  db = p->db;
73167
73168  /* If the VM did not run to completion or if it encountered an
73169  ** error, then it might not have been halted properly.  So halt
73170  ** it now.
73171  */
73172  sqlite3VdbeHalt(p);
73173
73174  /* If the VDBE has be run even partially, then transfer the error code
73175  ** and error message from the VDBE into the main database structure.  But
73176  ** if the VDBE has just been set to run but has not actually executed any
73177  ** instructions yet, leave the main database error information unchanged.
73178  */
73179  if( p->pc>=0 ){
73180    vdbeInvokeSqllog(p);
73181    sqlite3VdbeTransferError(p);
73182    sqlite3DbFree(db, p->zErrMsg);
73183    p->zErrMsg = 0;
73184    if( p->runOnlyOnce ) p->expired = 1;
73185  }else if( p->rc && p->expired ){
73186    /* The expired flag was set on the VDBE before the first call
73187    ** to sqlite3_step(). For consistency (since sqlite3_step() was
73188    ** called), set the database error in this case as well.
73189    */
73190    sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
73191    sqlite3DbFree(db, p->zErrMsg);
73192    p->zErrMsg = 0;
73193  }
73194
73195  /* Reclaim all memory used by the VDBE
73196  */
73197  Cleanup(p);
73198
73199  /* Save profiling information from this VDBE run.
73200  */
73201#ifdef VDBE_PROFILE
73202  {
73203    FILE *out = fopen("vdbe_profile.out", "a");
73204    if( out ){
73205      int i;
73206      fprintf(out, "---- ");
73207      for(i=0; i<p->nOp; i++){
73208        fprintf(out, "%02x", p->aOp[i].opcode);
73209      }
73210      fprintf(out, "\n");
73211      if( p->zSql ){
73212        char c, pc = 0;
73213        fprintf(out, "-- ");
73214        for(i=0; (c = p->zSql[i])!=0; i++){
73215          if( pc=='\n' ) fprintf(out, "-- ");
73216          putc(c, out);
73217          pc = c;
73218        }
73219        if( pc!='\n' ) fprintf(out, "\n");
73220      }
73221      for(i=0; i<p->nOp; i++){
73222        char zHdr[100];
73223        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
73224           p->aOp[i].cnt,
73225           p->aOp[i].cycles,
73226           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
73227        );
73228        fprintf(out, "%s", zHdr);
73229        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
73230      }
73231      fclose(out);
73232    }
73233  }
73234#endif
73235  p->iCurrentTime = 0;
73236  p->magic = VDBE_MAGIC_INIT;
73237  return p->rc & db->errMask;
73238}
73239
73240/*
73241** Clean up and delete a VDBE after execution.  Return an integer which is
73242** the result code.  Write any error message text into *pzErrMsg.
73243*/
73244SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
73245  int rc = SQLITE_OK;
73246  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
73247    rc = sqlite3VdbeReset(p);
73248    assert( (rc & p->db->errMask)==rc );
73249  }
73250  sqlite3VdbeDelete(p);
73251  return rc;
73252}
73253
73254/*
73255** If parameter iOp is less than zero, then invoke the destructor for
73256** all auxiliary data pointers currently cached by the VM passed as
73257** the first argument.
73258**
73259** Or, if iOp is greater than or equal to zero, then the destructor is
73260** only invoked for those auxiliary data pointers created by the user
73261** function invoked by the OP_Function opcode at instruction iOp of
73262** VM pVdbe, and only then if:
73263**
73264**    * the associated function parameter is the 32nd or later (counting
73265**      from left to right), or
73266**
73267**    * the corresponding bit in argument mask is clear (where the first
73268**      function parameter corresponds to bit 0 etc.).
73269*/
73270SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
73271  while( *pp ){
73272    AuxData *pAux = *pp;
73273    if( (iOp<0)
73274     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
73275    ){
73276      testcase( pAux->iArg==31 );
73277      if( pAux->xDelete ){
73278        pAux->xDelete(pAux->pAux);
73279      }
73280      *pp = pAux->pNext;
73281      sqlite3DbFree(db, pAux);
73282    }else{
73283      pp= &pAux->pNext;
73284    }
73285  }
73286}
73287
73288/*
73289** Free all memory associated with the Vdbe passed as the second argument,
73290** except for object itself, which is preserved.
73291**
73292** The difference between this function and sqlite3VdbeDelete() is that
73293** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
73294** the database connection and frees the object itself.
73295*/
73296SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
73297  SubProgram *pSub, *pNext;
73298  int i;
73299  assert( p->db==0 || p->db==db );
73300  releaseMemArray(p->aVar, p->nVar);
73301  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73302  for(pSub=p->pProgram; pSub; pSub=pNext){
73303    pNext = pSub->pNext;
73304    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
73305    sqlite3DbFree(db, pSub);
73306  }
73307  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
73308  sqlite3DbFree(db, p->azVar);
73309  vdbeFreeOpArray(db, p->aOp, p->nOp);
73310  sqlite3DbFree(db, p->aColName);
73311  sqlite3DbFree(db, p->zSql);
73312  sqlite3DbFree(db, p->pFree);
73313#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73314  for(i=0; i<p->nScan; i++){
73315    sqlite3DbFree(db, p->aScan[i].zName);
73316  }
73317  sqlite3DbFree(db, p->aScan);
73318#endif
73319}
73320
73321/*
73322** Delete an entire VDBE.
73323*/
73324SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
73325  sqlite3 *db;
73326
73327  if( NEVER(p==0) ) return;
73328  db = p->db;
73329  assert( sqlite3_mutex_held(db->mutex) );
73330  sqlite3VdbeClearObject(db, p);
73331  if( p->pPrev ){
73332    p->pPrev->pNext = p->pNext;
73333  }else{
73334    assert( db->pVdbe==p );
73335    db->pVdbe = p->pNext;
73336  }
73337  if( p->pNext ){
73338    p->pNext->pPrev = p->pPrev;
73339  }
73340  p->magic = VDBE_MAGIC_DEAD;
73341  p->db = 0;
73342  sqlite3DbFree(db, p);
73343}
73344
73345/*
73346** The cursor "p" has a pending seek operation that has not yet been
73347** carried out.  Seek the cursor now.  If an error occurs, return
73348** the appropriate error code.
73349*/
73350static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
73351  int res, rc;
73352#ifdef SQLITE_TEST
73353  extern int sqlite3_search_count;
73354#endif
73355  assert( p->deferredMoveto );
73356  assert( p->isTable );
73357  assert( p->eCurType==CURTYPE_BTREE );
73358  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
73359  if( rc ) return rc;
73360  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
73361#ifdef SQLITE_TEST
73362  sqlite3_search_count++;
73363#endif
73364  p->deferredMoveto = 0;
73365  p->cacheStatus = CACHE_STALE;
73366  return SQLITE_OK;
73367}
73368
73369/*
73370** Something has moved cursor "p" out of place.  Maybe the row it was
73371** pointed to was deleted out from under it.  Or maybe the btree was
73372** rebalanced.  Whatever the cause, try to restore "p" to the place it
73373** is supposed to be pointing.  If the row was deleted out from under the
73374** cursor, set the cursor to point to a NULL row.
73375*/
73376static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
73377  int isDifferentRow, rc;
73378  assert( p->eCurType==CURTYPE_BTREE );
73379  assert( p->uc.pCursor!=0 );
73380  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
73381  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
73382  p->cacheStatus = CACHE_STALE;
73383  if( isDifferentRow ) p->nullRow = 1;
73384  return rc;
73385}
73386
73387/*
73388** Check to ensure that the cursor is valid.  Restore the cursor
73389** if need be.  Return any I/O error from the restore operation.
73390*/
73391SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
73392  assert( p->eCurType==CURTYPE_BTREE );
73393  if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73394    return handleMovedCursor(p);
73395  }
73396  return SQLITE_OK;
73397}
73398
73399/*
73400** Make sure the cursor p is ready to read or write the row to which it
73401** was last positioned.  Return an error code if an OOM fault or I/O error
73402** prevents us from positioning the cursor to its correct position.
73403**
73404** If a MoveTo operation is pending on the given cursor, then do that
73405** MoveTo now.  If no move is pending, check to see if the row has been
73406** deleted out from under the cursor and if it has, mark the row as
73407** a NULL row.
73408**
73409** If the cursor is already pointing to the correct row and that row has
73410** not been deleted out from under the cursor, then this routine is a no-op.
73411*/
73412SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
73413  VdbeCursor *p = *pp;
73414  if( p->eCurType==CURTYPE_BTREE ){
73415    if( p->deferredMoveto ){
73416      int iMap;
73417      if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
73418        *pp = p->pAltCursor;
73419        *piCol = iMap - 1;
73420        return SQLITE_OK;
73421      }
73422      return handleDeferredMoveto(p);
73423    }
73424    if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73425      return handleMovedCursor(p);
73426    }
73427  }
73428  return SQLITE_OK;
73429}
73430
73431/*
73432** The following functions:
73433**
73434** sqlite3VdbeSerialType()
73435** sqlite3VdbeSerialTypeLen()
73436** sqlite3VdbeSerialLen()
73437** sqlite3VdbeSerialPut()
73438** sqlite3VdbeSerialGet()
73439**
73440** encapsulate the code that serializes values for storage in SQLite
73441** data and index records. Each serialized value consists of a
73442** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
73443** integer, stored as a varint.
73444**
73445** In an SQLite index record, the serial type is stored directly before
73446** the blob of data that it corresponds to. In a table record, all serial
73447** types are stored at the start of the record, and the blobs of data at
73448** the end. Hence these functions allow the caller to handle the
73449** serial-type and data blob separately.
73450**
73451** The following table describes the various storage classes for data:
73452**
73453**   serial type        bytes of data      type
73454**   --------------     ---------------    ---------------
73455**      0                     0            NULL
73456**      1                     1            signed integer
73457**      2                     2            signed integer
73458**      3                     3            signed integer
73459**      4                     4            signed integer
73460**      5                     6            signed integer
73461**      6                     8            signed integer
73462**      7                     8            IEEE float
73463**      8                     0            Integer constant 0
73464**      9                     0            Integer constant 1
73465**     10,11                               reserved for expansion
73466**    N>=12 and even       (N-12)/2        BLOB
73467**    N>=13 and odd        (N-13)/2        text
73468**
73469** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
73470** of SQLite will not understand those serial types.
73471*/
73472
73473/*
73474** Return the serial-type for the value stored in pMem.
73475*/
73476SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
73477  int flags = pMem->flags;
73478  u32 n;
73479
73480  assert( pLen!=0 );
73481  if( flags&MEM_Null ){
73482    *pLen = 0;
73483    return 0;
73484  }
73485  if( flags&MEM_Int ){
73486    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73487#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
73488    i64 i = pMem->u.i;
73489    u64 u;
73490    if( i<0 ){
73491      u = ~i;
73492    }else{
73493      u = i;
73494    }
73495    if( u<=127 ){
73496      if( (i&1)==i && file_format>=4 ){
73497        *pLen = 0;
73498        return 8+(u32)u;
73499      }else{
73500        *pLen = 1;
73501        return 1;
73502      }
73503    }
73504    if( u<=32767 ){ *pLen = 2; return 2; }
73505    if( u<=8388607 ){ *pLen = 3; return 3; }
73506    if( u<=2147483647 ){ *pLen = 4; return 4; }
73507    if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
73508    *pLen = 8;
73509    return 6;
73510  }
73511  if( flags&MEM_Real ){
73512    *pLen = 8;
73513    return 7;
73514  }
73515  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
73516  assert( pMem->n>=0 );
73517  n = (u32)pMem->n;
73518  if( flags & MEM_Zero ){
73519    n += pMem->u.nZero;
73520  }
73521  *pLen = n;
73522  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73523}
73524
73525/*
73526** The sizes for serial types less than 128
73527*/
73528static const u8 sqlite3SmallTypeSizes[] = {
73529        /*  0   1   2   3   4   5   6   7   8   9 */
73530/*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
73531/*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
73532/*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
73533/*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
73534/*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
73535/*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
73536/*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
73537/*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
73538/*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
73539/*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
73540/* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
73541/* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
73542/* 120 */  54, 54, 55, 55, 56, 56, 57, 57
73543};
73544
73545/*
73546** Return the length of the data corresponding to the supplied serial-type.
73547*/
73548SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
73549  if( serial_type>=128 ){
73550    return (serial_type-12)/2;
73551  }else{
73552    assert( serial_type<12
73553            || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
73554    return sqlite3SmallTypeSizes[serial_type];
73555  }
73556}
73557SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
73558  assert( serial_type<128 );
73559  return sqlite3SmallTypeSizes[serial_type];
73560}
73561
73562/*
73563** If we are on an architecture with mixed-endian floating
73564** points (ex: ARM7) then swap the lower 4 bytes with the
73565** upper 4 bytes.  Return the result.
73566**
73567** For most architectures, this is a no-op.
73568**
73569** (later):  It is reported to me that the mixed-endian problem
73570** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
73571** that early versions of GCC stored the two words of a 64-bit
73572** float in the wrong order.  And that error has been propagated
73573** ever since.  The blame is not necessarily with GCC, though.
73574** GCC might have just copying the problem from a prior compiler.
73575** I am also told that newer versions of GCC that follow a different
73576** ABI get the byte order right.
73577**
73578** Developers using SQLite on an ARM7 should compile and run their
73579** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
73580** enabled, some asserts below will ensure that the byte order of
73581** floating point values is correct.
73582**
73583** (2007-08-30)  Frank van Vugt has studied this problem closely
73584** and has send his findings to the SQLite developers.  Frank
73585** writes that some Linux kernels offer floating point hardware
73586** emulation that uses only 32-bit mantissas instead of a full
73587** 48-bits as required by the IEEE standard.  (This is the
73588** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
73589** byte swapping becomes very complicated.  To avoid problems,
73590** the necessary byte swapping is carried out using a 64-bit integer
73591** rather than a 64-bit float.  Frank assures us that the code here
73592** works for him.  We, the developers, have no way to independently
73593** verify this, but Frank seems to know what he is talking about
73594** so we trust him.
73595*/
73596#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73597static u64 floatSwap(u64 in){
73598  union {
73599    u64 r;
73600    u32 i[2];
73601  } u;
73602  u32 t;
73603
73604  u.r = in;
73605  t = u.i[0];
73606  u.i[0] = u.i[1];
73607  u.i[1] = t;
73608  return u.r;
73609}
73610# define swapMixedEndianFloat(X)  X = floatSwap(X)
73611#else
73612# define swapMixedEndianFloat(X)
73613#endif
73614
73615/*
73616** Write the serialized data blob for the value stored in pMem into
73617** buf. It is assumed that the caller has allocated sufficient space.
73618** Return the number of bytes written.
73619**
73620** nBuf is the amount of space left in buf[].  The caller is responsible
73621** for allocating enough space to buf[] to hold the entire field, exclusive
73622** of the pMem->u.nZero bytes for a MEM_Zero value.
73623**
73624** Return the number of bytes actually written into buf[].  The number
73625** of bytes in the zero-filled tail is included in the return value only
73626** if those bytes were zeroed in buf[].
73627*/
73628SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
73629  u32 len;
73630
73631  /* Integer and Real */
73632  if( serial_type<=7 && serial_type>0 ){
73633    u64 v;
73634    u32 i;
73635    if( serial_type==7 ){
73636      assert( sizeof(v)==sizeof(pMem->u.r) );
73637      memcpy(&v, &pMem->u.r, sizeof(v));
73638      swapMixedEndianFloat(v);
73639    }else{
73640      v = pMem->u.i;
73641    }
73642    len = i = sqlite3SmallTypeSizes[serial_type];
73643    assert( i>0 );
73644    do{
73645      buf[--i] = (u8)(v&0xFF);
73646      v >>= 8;
73647    }while( i );
73648    return len;
73649  }
73650
73651  /* String or blob */
73652  if( serial_type>=12 ){
73653    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
73654             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
73655    len = pMem->n;
73656    if( len>0 ) memcpy(buf, pMem->z, len);
73657    return len;
73658  }
73659
73660  /* NULL or constants 0 or 1 */
73661  return 0;
73662}
73663
73664/* Input "x" is a sequence of unsigned characters that represent a
73665** big-endian integer.  Return the equivalent native integer
73666*/
73667#define ONE_BYTE_INT(x)    ((i8)(x)[0])
73668#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
73669#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
73670#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73671#define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73672
73673/*
73674** Deserialize the data blob pointed to by buf as serial type serial_type
73675** and store the result in pMem.  Return the number of bytes read.
73676**
73677** This function is implemented as two separate routines for performance.
73678** The few cases that require local variables are broken out into a separate
73679** routine so that in most cases the overhead of moving the stack pointer
73680** is avoided.
73681*/
73682static u32 SQLITE_NOINLINE serialGet(
73683  const unsigned char *buf,     /* Buffer to deserialize from */
73684  u32 serial_type,              /* Serial type to deserialize */
73685  Mem *pMem                     /* Memory cell to write value into */
73686){
73687  u64 x = FOUR_BYTE_UINT(buf);
73688  u32 y = FOUR_BYTE_UINT(buf+4);
73689  x = (x<<32) + y;
73690  if( serial_type==6 ){
73691    /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
73692    ** twos-complement integer. */
73693    pMem->u.i = *(i64*)&x;
73694    pMem->flags = MEM_Int;
73695    testcase( pMem->u.i<0 );
73696  }else{
73697    /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
73698    ** floating point number. */
73699#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73700    /* Verify that integers and floating point values use the same
73701    ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73702    ** defined that 64-bit floating point values really are mixed
73703    ** endian.
73704    */
73705    static const u64 t1 = ((u64)0x3ff00000)<<32;
73706    static const double r1 = 1.0;
73707    u64 t2 = t1;
73708    swapMixedEndianFloat(t2);
73709    assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
73710#endif
73711    assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
73712    swapMixedEndianFloat(x);
73713    memcpy(&pMem->u.r, &x, sizeof(x));
73714    pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
73715  }
73716  return 8;
73717}
73718SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
73719  const unsigned char *buf,     /* Buffer to deserialize from */
73720  u32 serial_type,              /* Serial type to deserialize */
73721  Mem *pMem                     /* Memory cell to write value into */
73722){
73723  switch( serial_type ){
73724    case 10:   /* Reserved for future use */
73725    case 11:   /* Reserved for future use */
73726    case 0: {  /* Null */
73727      /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
73728      pMem->flags = MEM_Null;
73729      break;
73730    }
73731    case 1: {
73732      /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
73733      ** integer. */
73734      pMem->u.i = ONE_BYTE_INT(buf);
73735      pMem->flags = MEM_Int;
73736      testcase( pMem->u.i<0 );
73737      return 1;
73738    }
73739    case 2: { /* 2-byte signed integer */
73740      /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
73741      ** twos-complement integer. */
73742      pMem->u.i = TWO_BYTE_INT(buf);
73743      pMem->flags = MEM_Int;
73744      testcase( pMem->u.i<0 );
73745      return 2;
73746    }
73747    case 3: { /* 3-byte signed integer */
73748      /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
73749      ** twos-complement integer. */
73750      pMem->u.i = THREE_BYTE_INT(buf);
73751      pMem->flags = MEM_Int;
73752      testcase( pMem->u.i<0 );
73753      return 3;
73754    }
73755    case 4: { /* 4-byte signed integer */
73756      /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
73757      ** twos-complement integer. */
73758      pMem->u.i = FOUR_BYTE_INT(buf);
73759#ifdef __HP_cc
73760      /* Work around a sign-extension bug in the HP compiler for HP/UX */
73761      if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
73762#endif
73763      pMem->flags = MEM_Int;
73764      testcase( pMem->u.i<0 );
73765      return 4;
73766    }
73767    case 5: { /* 6-byte signed integer */
73768      /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
73769      ** twos-complement integer. */
73770      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
73771      pMem->flags = MEM_Int;
73772      testcase( pMem->u.i<0 );
73773      return 6;
73774    }
73775    case 6:   /* 8-byte signed integer */
73776    case 7: { /* IEEE floating point */
73777      /* These use local variables, so do them in a separate routine
73778      ** to avoid having to move the frame pointer in the common case */
73779      return serialGet(buf,serial_type,pMem);
73780    }
73781    case 8:    /* Integer 0 */
73782    case 9: {  /* Integer 1 */
73783      /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
73784      /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
73785      pMem->u.i = serial_type-8;
73786      pMem->flags = MEM_Int;
73787      return 0;
73788    }
73789    default: {
73790      /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
73791      ** length.
73792      ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
73793      ** (N-13)/2 bytes in length. */
73794      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
73795      pMem->z = (char *)buf;
73796      pMem->n = (serial_type-12)/2;
73797      pMem->flags = aFlag[serial_type&1];
73798      return pMem->n;
73799    }
73800  }
73801  return 0;
73802}
73803/*
73804** This routine is used to allocate sufficient space for an UnpackedRecord
73805** structure large enough to be used with sqlite3VdbeRecordUnpack() if
73806** the first argument is a pointer to KeyInfo structure pKeyInfo.
73807**
73808** The space is either allocated using sqlite3DbMallocRaw() or from within
73809** the unaligned buffer passed via the second and third arguments (presumably
73810** stack space). If the former, then *ppFree is set to a pointer that should
73811** be eventually freed by the caller using sqlite3DbFree(). Or, if the
73812** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
73813** before returning.
73814**
73815** If an OOM error occurs, NULL is returned.
73816*/
73817SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
73818  KeyInfo *pKeyInfo,              /* Description of the record */
73819  char *pSpace,                   /* Unaligned space available */
73820  int szSpace,                    /* Size of pSpace[] in bytes */
73821  char **ppFree                   /* OUT: Caller should free this pointer */
73822){
73823  UnpackedRecord *p;              /* Unpacked record to return */
73824  int nOff;                       /* Increment pSpace by nOff to align it */
73825  int nByte;                      /* Number of bytes required for *p */
73826
73827  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
73828  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
73829  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
73830  */
73831  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
73832  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
73833  if( nByte>szSpace+nOff ){
73834    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
73835    *ppFree = (char *)p;
73836    if( !p ) return 0;
73837  }else{
73838    p = (UnpackedRecord*)&pSpace[nOff];
73839    *ppFree = 0;
73840  }
73841
73842  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
73843  assert( pKeyInfo->aSortOrder!=0 );
73844  p->pKeyInfo = pKeyInfo;
73845  p->nField = pKeyInfo->nField + 1;
73846  return p;
73847}
73848
73849/*
73850** Given the nKey-byte encoding of a record in pKey[], populate the
73851** UnpackedRecord structure indicated by the fourth argument with the
73852** contents of the decoded record.
73853*/
73854SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
73855  KeyInfo *pKeyInfo,     /* Information about the record format */
73856  int nKey,              /* Size of the binary record */
73857  const void *pKey,      /* The binary record */
73858  UnpackedRecord *p      /* Populate this structure before returning. */
73859){
73860  const unsigned char *aKey = (const unsigned char *)pKey;
73861  int d;
73862  u32 idx;                        /* Offset in aKey[] to read from */
73863  u16 u;                          /* Unsigned loop counter */
73864  u32 szHdr;
73865  Mem *pMem = p->aMem;
73866
73867  p->default_rc = 0;
73868  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
73869  idx = getVarint32(aKey, szHdr);
73870  d = szHdr;
73871  u = 0;
73872  while( idx<szHdr && d<=nKey ){
73873    u32 serial_type;
73874
73875    idx += getVarint32(&aKey[idx], serial_type);
73876    pMem->enc = pKeyInfo->enc;
73877    pMem->db = pKeyInfo->db;
73878    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
73879    pMem->szMalloc = 0;
73880    pMem->z = 0;
73881    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
73882    pMem++;
73883    if( (++u)>=p->nField ) break;
73884  }
73885  assert( u<=pKeyInfo->nField + 1 );
73886  p->nField = u;
73887}
73888
73889#if SQLITE_DEBUG
73890/*
73891** This function compares two index or table record keys in the same way
73892** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
73893** this function deserializes and compares values using the
73894** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
73895** in assert() statements to ensure that the optimized code in
73896** sqlite3VdbeRecordCompare() returns results with these two primitives.
73897**
73898** Return true if the result of comparison is equivalent to desiredResult.
73899** Return false if there is a disagreement.
73900*/
73901static int vdbeRecordCompareDebug(
73902  int nKey1, const void *pKey1, /* Left key */
73903  const UnpackedRecord *pPKey2, /* Right key */
73904  int desiredResult             /* Correct answer */
73905){
73906  u32 d1;            /* Offset into aKey[] of next data element */
73907  u32 idx1;          /* Offset into aKey[] of next header element */
73908  u32 szHdr1;        /* Number of bytes in header */
73909  int i = 0;
73910  int rc = 0;
73911  const unsigned char *aKey1 = (const unsigned char *)pKey1;
73912  KeyInfo *pKeyInfo;
73913  Mem mem1;
73914
73915  pKeyInfo = pPKey2->pKeyInfo;
73916  if( pKeyInfo->db==0 ) return 1;
73917  mem1.enc = pKeyInfo->enc;
73918  mem1.db = pKeyInfo->db;
73919  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
73920  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
73921
73922  /* Compilers may complain that mem1.u.i is potentially uninitialized.
73923  ** We could initialize it, as shown here, to silence those complaints.
73924  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
73925  ** the unnecessary initialization has a measurable negative performance
73926  ** impact, since this routine is a very high runner.  And so, we choose
73927  ** to ignore the compiler warnings and leave this variable uninitialized.
73928  */
73929  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
73930
73931  idx1 = getVarint32(aKey1, szHdr1);
73932  if( szHdr1>98307 ) return SQLITE_CORRUPT;
73933  d1 = szHdr1;
73934  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
73935  assert( pKeyInfo->aSortOrder!=0 );
73936  assert( pKeyInfo->nField>0 );
73937  assert( idx1<=szHdr1 || CORRUPT_DB );
73938  do{
73939    u32 serial_type1;
73940
73941    /* Read the serial types for the next element in each key. */
73942    idx1 += getVarint32( aKey1+idx1, serial_type1 );
73943
73944    /* Verify that there is enough key space remaining to avoid
73945    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
73946    ** always be greater than or equal to the amount of required key space.
73947    ** Use that approximation to avoid the more expensive call to
73948    ** sqlite3VdbeSerialTypeLen() in the common case.
73949    */
73950    if( d1+serial_type1+2>(u32)nKey1
73951     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
73952    ){
73953      break;
73954    }
73955
73956    /* Extract the values to be compared.
73957    */
73958    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
73959
73960    /* Do the comparison
73961    */
73962    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
73963    if( rc!=0 ){
73964      assert( mem1.szMalloc==0 );  /* See comment below */
73965      if( pKeyInfo->aSortOrder[i] ){
73966        rc = -rc;  /* Invert the result for DESC sort order. */
73967      }
73968      goto debugCompareEnd;
73969    }
73970    i++;
73971  }while( idx1<szHdr1 && i<pPKey2->nField );
73972
73973  /* No memory allocation is ever used on mem1.  Prove this using
73974  ** the following assert().  If the assert() fails, it indicates a
73975  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
73976  */
73977  assert( mem1.szMalloc==0 );
73978
73979  /* rc==0 here means that one of the keys ran out of fields and
73980  ** all the fields up to that point were equal. Return the default_rc
73981  ** value.  */
73982  rc = pPKey2->default_rc;
73983
73984debugCompareEnd:
73985  if( desiredResult==0 && rc==0 ) return 1;
73986  if( desiredResult<0 && rc<0 ) return 1;
73987  if( desiredResult>0 && rc>0 ) return 1;
73988  if( CORRUPT_DB ) return 1;
73989  if( pKeyInfo->db->mallocFailed ) return 1;
73990  return 0;
73991}
73992#endif
73993
73994#if SQLITE_DEBUG
73995/*
73996** Count the number of fields (a.k.a. columns) in the record given by
73997** pKey,nKey.  The verify that this count is less than or equal to the
73998** limit given by pKeyInfo->nField + pKeyInfo->nXField.
73999**
74000** If this constraint is not satisfied, it means that the high-speed
74001** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
74002** not work correctly.  If this assert() ever fires, it probably means
74003** that the KeyInfo.nField or KeyInfo.nXField values were computed
74004** incorrectly.
74005*/
74006static void vdbeAssertFieldCountWithinLimits(
74007  int nKey, const void *pKey,   /* The record to verify */
74008  const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
74009){
74010  int nField = 0;
74011  u32 szHdr;
74012  u32 idx;
74013  u32 notUsed;
74014  const unsigned char *aKey = (const unsigned char*)pKey;
74015
74016  if( CORRUPT_DB ) return;
74017  idx = getVarint32(aKey, szHdr);
74018  assert( nKey>=0 );
74019  assert( szHdr<=(u32)nKey );
74020  while( idx<szHdr ){
74021    idx += getVarint32(aKey+idx, notUsed);
74022    nField++;
74023  }
74024  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
74025}
74026#else
74027# define vdbeAssertFieldCountWithinLimits(A,B,C)
74028#endif
74029
74030/*
74031** Both *pMem1 and *pMem2 contain string values. Compare the two values
74032** using the collation sequence pColl. As usual, return a negative , zero
74033** or positive value if *pMem1 is less than, equal to or greater than
74034** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
74035*/
74036static int vdbeCompareMemString(
74037  const Mem *pMem1,
74038  const Mem *pMem2,
74039  const CollSeq *pColl,
74040  u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
74041){
74042  if( pMem1->enc==pColl->enc ){
74043    /* The strings are already in the correct encoding.  Call the
74044     ** comparison function directly */
74045    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
74046  }else{
74047    int rc;
74048    const void *v1, *v2;
74049    int n1, n2;
74050    Mem c1;
74051    Mem c2;
74052    sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
74053    sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
74054    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
74055    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
74056    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
74057    n1 = v1==0 ? 0 : c1.n;
74058    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
74059    n2 = v2==0 ? 0 : c2.n;
74060    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
74061    if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
74062    sqlite3VdbeMemRelease(&c1);
74063    sqlite3VdbeMemRelease(&c2);
74064    return rc;
74065  }
74066}
74067
74068/*
74069** Compare two blobs.  Return negative, zero, or positive if the first
74070** is less than, equal to, or greater than the second, respectively.
74071** If one blob is a prefix of the other, then the shorter is the lessor.
74072*/
74073static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
74074  int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
74075  if( c ) return c;
74076  return pB1->n - pB2->n;
74077}
74078
74079/*
74080** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
74081** number.  Return negative, zero, or positive if the first (i64) is less than,
74082** equal to, or greater than the second (double).
74083*/
74084static int sqlite3IntFloatCompare(i64 i, double r){
74085  if( sizeof(LONGDOUBLE_TYPE)>8 ){
74086    LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
74087    if( x<r ) return -1;
74088    if( x>r ) return +1;
74089    return 0;
74090  }else{
74091    i64 y;
74092    double s;
74093    if( r<-9223372036854775808.0 ) return +1;
74094    if( r>9223372036854775807.0 ) return -1;
74095    y = (i64)r;
74096    if( i<y ) return -1;
74097    if( i>y ){
74098      if( y==SMALLEST_INT64 && r>0.0 ) return -1;
74099      return +1;
74100    }
74101    s = (double)i;
74102    if( s<r ) return -1;
74103    if( s>r ) return +1;
74104    return 0;
74105  }
74106}
74107
74108/*
74109** Compare the values contained by the two memory cells, returning
74110** negative, zero or positive if pMem1 is less than, equal to, or greater
74111** than pMem2. Sorting order is NULL's first, followed by numbers (integers
74112** and reals) sorted numerically, followed by text ordered by the collating
74113** sequence pColl and finally blob's ordered by memcmp().
74114**
74115** Two NULL values are considered equal by this function.
74116*/
74117SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
74118  int f1, f2;
74119  int combined_flags;
74120
74121  f1 = pMem1->flags;
74122  f2 = pMem2->flags;
74123  combined_flags = f1|f2;
74124  assert( (combined_flags & MEM_RowSet)==0 );
74125
74126  /* If one value is NULL, it is less than the other. If both values
74127  ** are NULL, return 0.
74128  */
74129  if( combined_flags&MEM_Null ){
74130    return (f2&MEM_Null) - (f1&MEM_Null);
74131  }
74132
74133  /* At least one of the two values is a number
74134  */
74135  if( combined_flags&(MEM_Int|MEM_Real) ){
74136    if( (f1 & f2 & MEM_Int)!=0 ){
74137      if( pMem1->u.i < pMem2->u.i ) return -1;
74138      if( pMem1->u.i > pMem2->u.i ) return +1;
74139      return 0;
74140    }
74141    if( (f1 & f2 & MEM_Real)!=0 ){
74142      if( pMem1->u.r < pMem2->u.r ) return -1;
74143      if( pMem1->u.r > pMem2->u.r ) return +1;
74144      return 0;
74145    }
74146    if( (f1&MEM_Int)!=0 ){
74147      if( (f2&MEM_Real)!=0 ){
74148        return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
74149      }else{
74150        return -1;
74151      }
74152    }
74153    if( (f1&MEM_Real)!=0 ){
74154      if( (f2&MEM_Int)!=0 ){
74155        return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
74156      }else{
74157        return -1;
74158      }
74159    }
74160    return +1;
74161  }
74162
74163  /* If one value is a string and the other is a blob, the string is less.
74164  ** If both are strings, compare using the collating functions.
74165  */
74166  if( combined_flags&MEM_Str ){
74167    if( (f1 & MEM_Str)==0 ){
74168      return 1;
74169    }
74170    if( (f2 & MEM_Str)==0 ){
74171      return -1;
74172    }
74173
74174    assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
74175    assert( pMem1->enc==SQLITE_UTF8 ||
74176            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
74177
74178    /* The collation sequence must be defined at this point, even if
74179    ** the user deletes the collation sequence after the vdbe program is
74180    ** compiled (this was not always the case).
74181    */
74182    assert( !pColl || pColl->xCmp );
74183
74184    if( pColl ){
74185      return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
74186    }
74187    /* If a NULL pointer was passed as the collate function, fall through
74188    ** to the blob case and use memcmp().  */
74189  }
74190
74191  /* Both values must be blobs.  Compare using memcmp().  */
74192  return sqlite3BlobCompare(pMem1, pMem2);
74193}
74194
74195
74196/*
74197** The first argument passed to this function is a serial-type that
74198** corresponds to an integer - all values between 1 and 9 inclusive
74199** except 7. The second points to a buffer containing an integer value
74200** serialized according to serial_type. This function deserializes
74201** and returns the value.
74202*/
74203static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
74204  u32 y;
74205  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
74206  switch( serial_type ){
74207    case 0:
74208    case 1:
74209      testcase( aKey[0]&0x80 );
74210      return ONE_BYTE_INT(aKey);
74211    case 2:
74212      testcase( aKey[0]&0x80 );
74213      return TWO_BYTE_INT(aKey);
74214    case 3:
74215      testcase( aKey[0]&0x80 );
74216      return THREE_BYTE_INT(aKey);
74217    case 4: {
74218      testcase( aKey[0]&0x80 );
74219      y = FOUR_BYTE_UINT(aKey);
74220      return (i64)*(int*)&y;
74221    }
74222    case 5: {
74223      testcase( aKey[0]&0x80 );
74224      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74225    }
74226    case 6: {
74227      u64 x = FOUR_BYTE_UINT(aKey);
74228      testcase( aKey[0]&0x80 );
74229      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74230      return (i64)*(i64*)&x;
74231    }
74232  }
74233
74234  return (serial_type - 8);
74235}
74236
74237/*
74238** This function compares the two table rows or index records
74239** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
74240** or positive integer if key1 is less than, equal to or
74241** greater than key2.  The {nKey1, pKey1} key must be a blob
74242** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
74243** key must be a parsed key such as obtained from
74244** sqlite3VdbeParseRecord.
74245**
74246** If argument bSkip is non-zero, it is assumed that the caller has already
74247** determined that the first fields of the keys are equal.
74248**
74249** Key1 and Key2 do not have to contain the same number of fields. If all
74250** fields that appear in both keys are equal, then pPKey2->default_rc is
74251** returned.
74252**
74253** If database corruption is discovered, set pPKey2->errCode to
74254** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
74255** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
74256** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
74257*/
74258SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
74259  int nKey1, const void *pKey1,   /* Left key */
74260  UnpackedRecord *pPKey2,         /* Right key */
74261  int bSkip                       /* If true, skip the first field */
74262){
74263  u32 d1;                         /* Offset into aKey[] of next data element */
74264  int i;                          /* Index of next field to compare */
74265  u32 szHdr1;                     /* Size of record header in bytes */
74266  u32 idx1;                       /* Offset of first type in header */
74267  int rc = 0;                     /* Return value */
74268  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
74269  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
74270  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74271  Mem mem1;
74272
74273  /* If bSkip is true, then the caller has already determined that the first
74274  ** two elements in the keys are equal. Fix the various stack variables so
74275  ** that this routine begins comparing at the second field. */
74276  if( bSkip ){
74277    u32 s1;
74278    idx1 = 1 + getVarint32(&aKey1[1], s1);
74279    szHdr1 = aKey1[0];
74280    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
74281    i = 1;
74282    pRhs++;
74283  }else{
74284    idx1 = getVarint32(aKey1, szHdr1);
74285    d1 = szHdr1;
74286    if( d1>(unsigned)nKey1 ){
74287      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74288      return 0;  /* Corruption */
74289    }
74290    i = 0;
74291  }
74292
74293  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74294  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
74295       || CORRUPT_DB );
74296  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
74297  assert( pPKey2->pKeyInfo->nField>0 );
74298  assert( idx1<=szHdr1 || CORRUPT_DB );
74299  do{
74300    u32 serial_type;
74301
74302    /* RHS is an integer */
74303    if( pRhs->flags & MEM_Int ){
74304      serial_type = aKey1[idx1];
74305      testcase( serial_type==12 );
74306      if( serial_type>=10 ){
74307        rc = +1;
74308      }else if( serial_type==0 ){
74309        rc = -1;
74310      }else if( serial_type==7 ){
74311        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74312        rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
74313      }else{
74314        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
74315        i64 rhs = pRhs->u.i;
74316        if( lhs<rhs ){
74317          rc = -1;
74318        }else if( lhs>rhs ){
74319          rc = +1;
74320        }
74321      }
74322    }
74323
74324    /* RHS is real */
74325    else if( pRhs->flags & MEM_Real ){
74326      serial_type = aKey1[idx1];
74327      if( serial_type>=10 ){
74328        /* Serial types 12 or greater are strings and blobs (greater than
74329        ** numbers). Types 10 and 11 are currently "reserved for future
74330        ** use", so it doesn't really matter what the results of comparing
74331        ** them to numberic values are.  */
74332        rc = +1;
74333      }else if( serial_type==0 ){
74334        rc = -1;
74335      }else{
74336        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74337        if( serial_type==7 ){
74338          if( mem1.u.r<pRhs->u.r ){
74339            rc = -1;
74340          }else if( mem1.u.r>pRhs->u.r ){
74341            rc = +1;
74342          }
74343        }else{
74344          rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
74345        }
74346      }
74347    }
74348
74349    /* RHS is a string */
74350    else if( pRhs->flags & MEM_Str ){
74351      getVarint32(&aKey1[idx1], serial_type);
74352      testcase( serial_type==12 );
74353      if( serial_type<12 ){
74354        rc = -1;
74355      }else if( !(serial_type & 0x01) ){
74356        rc = +1;
74357      }else{
74358        mem1.n = (serial_type - 12) / 2;
74359        testcase( (d1+mem1.n)==(unsigned)nKey1 );
74360        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
74361        if( (d1+mem1.n) > (unsigned)nKey1 ){
74362          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74363          return 0;                /* Corruption */
74364        }else if( pKeyInfo->aColl[i] ){
74365          mem1.enc = pKeyInfo->enc;
74366          mem1.db = pKeyInfo->db;
74367          mem1.flags = MEM_Str;
74368          mem1.z = (char*)&aKey1[d1];
74369          rc = vdbeCompareMemString(
74370              &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
74371          );
74372        }else{
74373          int nCmp = MIN(mem1.n, pRhs->n);
74374          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74375          if( rc==0 ) rc = mem1.n - pRhs->n;
74376        }
74377      }
74378    }
74379
74380    /* RHS is a blob */
74381    else if( pRhs->flags & MEM_Blob ){
74382      getVarint32(&aKey1[idx1], serial_type);
74383      testcase( serial_type==12 );
74384      if( serial_type<12 || (serial_type & 0x01) ){
74385        rc = -1;
74386      }else{
74387        int nStr = (serial_type - 12) / 2;
74388        testcase( (d1+nStr)==(unsigned)nKey1 );
74389        testcase( (d1+nStr+1)==(unsigned)nKey1 );
74390        if( (d1+nStr) > (unsigned)nKey1 ){
74391          pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74392          return 0;                /* Corruption */
74393        }else{
74394          int nCmp = MIN(nStr, pRhs->n);
74395          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74396          if( rc==0 ) rc = nStr - pRhs->n;
74397        }
74398      }
74399    }
74400
74401    /* RHS is null */
74402    else{
74403      serial_type = aKey1[idx1];
74404      rc = (serial_type!=0);
74405    }
74406
74407    if( rc!=0 ){
74408      if( pKeyInfo->aSortOrder[i] ){
74409        rc = -rc;
74410      }
74411      assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
74412      assert( mem1.szMalloc==0 );  /* See comment below */
74413      return rc;
74414    }
74415
74416    i++;
74417    pRhs++;
74418    d1 += sqlite3VdbeSerialTypeLen(serial_type);
74419    idx1 += sqlite3VarintLen(serial_type);
74420  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
74421
74422  /* No memory allocation is ever used on mem1.  Prove this using
74423  ** the following assert().  If the assert() fails, it indicates a
74424  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
74425  assert( mem1.szMalloc==0 );
74426
74427  /* rc==0 here means that one or both of the keys ran out of fields and
74428  ** all the fields up to that point were equal. Return the default_rc
74429  ** value.  */
74430  assert( CORRUPT_DB
74431       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
74432       || pKeyInfo->db->mallocFailed
74433  );
74434  pPKey2->eqSeen = 1;
74435  return pPKey2->default_rc;
74436}
74437SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
74438  int nKey1, const void *pKey1,   /* Left key */
74439  UnpackedRecord *pPKey2          /* Right key */
74440){
74441  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
74442}
74443
74444
74445/*
74446** This function is an optimized version of sqlite3VdbeRecordCompare()
74447** that (a) the first field of pPKey2 is an integer, and (b) the
74448** size-of-header varint at the start of (pKey1/nKey1) fits in a single
74449** byte (i.e. is less than 128).
74450**
74451** To avoid concerns about buffer overreads, this routine is only used
74452** on schemas where the maximum valid header size is 63 bytes or less.
74453*/
74454static int vdbeRecordCompareInt(
74455  int nKey1, const void *pKey1, /* Left key */
74456  UnpackedRecord *pPKey2        /* Right key */
74457){
74458  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
74459  int serial_type = ((const u8*)pKey1)[1];
74460  int res;
74461  u32 y;
74462  u64 x;
74463  i64 v = pPKey2->aMem[0].u.i;
74464  i64 lhs;
74465
74466  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74467  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
74468  switch( serial_type ){
74469    case 1: { /* 1-byte signed integer */
74470      lhs = ONE_BYTE_INT(aKey);
74471      testcase( lhs<0 );
74472      break;
74473    }
74474    case 2: { /* 2-byte signed integer */
74475      lhs = TWO_BYTE_INT(aKey);
74476      testcase( lhs<0 );
74477      break;
74478    }
74479    case 3: { /* 3-byte signed integer */
74480      lhs = THREE_BYTE_INT(aKey);
74481      testcase( lhs<0 );
74482      break;
74483    }
74484    case 4: { /* 4-byte signed integer */
74485      y = FOUR_BYTE_UINT(aKey);
74486      lhs = (i64)*(int*)&y;
74487      testcase( lhs<0 );
74488      break;
74489    }
74490    case 5: { /* 6-byte signed integer */
74491      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74492      testcase( lhs<0 );
74493      break;
74494    }
74495    case 6: { /* 8-byte signed integer */
74496      x = FOUR_BYTE_UINT(aKey);
74497      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74498      lhs = *(i64*)&x;
74499      testcase( lhs<0 );
74500      break;
74501    }
74502    case 8:
74503      lhs = 0;
74504      break;
74505    case 9:
74506      lhs = 1;
74507      break;
74508
74509    /* This case could be removed without changing the results of running
74510    ** this code. Including it causes gcc to generate a faster switch
74511    ** statement (since the range of switch targets now starts at zero and
74512    ** is contiguous) but does not cause any duplicate code to be generated
74513    ** (as gcc is clever enough to combine the two like cases). Other
74514    ** compilers might be similar.  */
74515    case 0: case 7:
74516      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74517
74518    default:
74519      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74520  }
74521
74522  if( v>lhs ){
74523    res = pPKey2->r1;
74524  }else if( v<lhs ){
74525    res = pPKey2->r2;
74526  }else if( pPKey2->nField>1 ){
74527    /* The first fields of the two keys are equal. Compare the trailing
74528    ** fields.  */
74529    res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74530  }else{
74531    /* The first fields of the two keys are equal and there are no trailing
74532    ** fields. Return pPKey2->default_rc in this case. */
74533    res = pPKey2->default_rc;
74534    pPKey2->eqSeen = 1;
74535  }
74536
74537  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
74538  return res;
74539}
74540
74541/*
74542** This function is an optimized version of sqlite3VdbeRecordCompare()
74543** that (a) the first field of pPKey2 is a string, that (b) the first field
74544** uses the collation sequence BINARY and (c) that the size-of-header varint
74545** at the start of (pKey1/nKey1) fits in a single byte.
74546*/
74547static int vdbeRecordCompareString(
74548  int nKey1, const void *pKey1, /* Left key */
74549  UnpackedRecord *pPKey2        /* Right key */
74550){
74551  const u8 *aKey1 = (const u8*)pKey1;
74552  int serial_type;
74553  int res;
74554
74555  assert( pPKey2->aMem[0].flags & MEM_Str );
74556  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74557  getVarint32(&aKey1[1], serial_type);
74558  if( serial_type<12 ){
74559    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
74560  }else if( !(serial_type & 0x01) ){
74561    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
74562  }else{
74563    int nCmp;
74564    int nStr;
74565    int szHdr = aKey1[0];
74566
74567    nStr = (serial_type-12) / 2;
74568    if( (szHdr + nStr) > nKey1 ){
74569      pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74570      return 0;    /* Corruption */
74571    }
74572    nCmp = MIN( pPKey2->aMem[0].n, nStr );
74573    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
74574
74575    if( res==0 ){
74576      res = nStr - pPKey2->aMem[0].n;
74577      if( res==0 ){
74578        if( pPKey2->nField>1 ){
74579          res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74580        }else{
74581          res = pPKey2->default_rc;
74582          pPKey2->eqSeen = 1;
74583        }
74584      }else if( res>0 ){
74585        res = pPKey2->r2;
74586      }else{
74587        res = pPKey2->r1;
74588      }
74589    }else if( res>0 ){
74590      res = pPKey2->r2;
74591    }else{
74592      res = pPKey2->r1;
74593    }
74594  }
74595
74596  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
74597       || CORRUPT_DB
74598       || pPKey2->pKeyInfo->db->mallocFailed
74599  );
74600  return res;
74601}
74602
74603/*
74604** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
74605** suitable for comparing serialized records to the unpacked record passed
74606** as the only argument.
74607*/
74608SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
74609  /* varintRecordCompareInt() and varintRecordCompareString() both assume
74610  ** that the size-of-header varint that occurs at the start of each record
74611  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
74612  ** also assumes that it is safe to overread a buffer by at least the
74613  ** maximum possible legal header size plus 8 bytes. Because there is
74614  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
74615  ** buffer passed to varintRecordCompareInt() this makes it convenient to
74616  ** limit the size of the header to 64 bytes in cases where the first field
74617  ** is an integer.
74618  **
74619  ** The easiest way to enforce this limit is to consider only records with
74620  ** 13 fields or less. If the first field is an integer, the maximum legal
74621  ** header size is (12*5 + 1 + 1) bytes.  */
74622  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
74623    int flags = p->aMem[0].flags;
74624    if( p->pKeyInfo->aSortOrder[0] ){
74625      p->r1 = 1;
74626      p->r2 = -1;
74627    }else{
74628      p->r1 = -1;
74629      p->r2 = 1;
74630    }
74631    if( (flags & MEM_Int) ){
74632      return vdbeRecordCompareInt;
74633    }
74634    testcase( flags & MEM_Real );
74635    testcase( flags & MEM_Null );
74636    testcase( flags & MEM_Blob );
74637    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
74638      assert( flags & MEM_Str );
74639      return vdbeRecordCompareString;
74640    }
74641  }
74642
74643  return sqlite3VdbeRecordCompare;
74644}
74645
74646/*
74647** pCur points at an index entry created using the OP_MakeRecord opcode.
74648** Read the rowid (the last field in the record) and store it in *rowid.
74649** Return SQLITE_OK if everything works, or an error code otherwise.
74650**
74651** pCur might be pointing to text obtained from a corrupt database file.
74652** So the content cannot be trusted.  Do appropriate checks on the content.
74653*/
74654SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
74655  i64 nCellKey = 0;
74656  int rc;
74657  u32 szHdr;        /* Size of the header */
74658  u32 typeRowid;    /* Serial type of the rowid */
74659  u32 lenRowid;     /* Size of the rowid */
74660  Mem m, v;
74661
74662  /* Get the size of the index entry.  Only indices entries of less
74663  ** than 2GiB are support - anything large must be database corruption.
74664  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
74665  ** this code can safely assume that nCellKey is 32-bits
74666  */
74667  assert( sqlite3BtreeCursorIsValid(pCur) );
74668  nCellKey = sqlite3BtreePayloadSize(pCur);
74669  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
74670
74671  /* Read in the complete content of the index entry */
74672  sqlite3VdbeMemInit(&m, db, 0);
74673  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74674  if( rc ){
74675    return rc;
74676  }
74677
74678  /* The index entry must begin with a header size */
74679  (void)getVarint32((u8*)m.z, szHdr);
74680  testcase( szHdr==3 );
74681  testcase( szHdr==m.n );
74682  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
74683    goto idx_rowid_corruption;
74684  }
74685
74686  /* The last field of the index should be an integer - the ROWID.
74687  ** Verify that the last entry really is an integer. */
74688  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
74689  testcase( typeRowid==1 );
74690  testcase( typeRowid==2 );
74691  testcase( typeRowid==3 );
74692  testcase( typeRowid==4 );
74693  testcase( typeRowid==5 );
74694  testcase( typeRowid==6 );
74695  testcase( typeRowid==8 );
74696  testcase( typeRowid==9 );
74697  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
74698    goto idx_rowid_corruption;
74699  }
74700  lenRowid = sqlite3SmallTypeSizes[typeRowid];
74701  testcase( (u32)m.n==szHdr+lenRowid );
74702  if( unlikely((u32)m.n<szHdr+lenRowid) ){
74703    goto idx_rowid_corruption;
74704  }
74705
74706  /* Fetch the integer off the end of the index record */
74707  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
74708  *rowid = v.u.i;
74709  sqlite3VdbeMemRelease(&m);
74710  return SQLITE_OK;
74711
74712  /* Jump here if database corruption is detected after m has been
74713  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
74714idx_rowid_corruption:
74715  testcase( m.szMalloc!=0 );
74716  sqlite3VdbeMemRelease(&m);
74717  return SQLITE_CORRUPT_BKPT;
74718}
74719
74720/*
74721** Compare the key of the index entry that cursor pC is pointing to against
74722** the key string in pUnpacked.  Write into *pRes a number
74723** that is negative, zero, or positive if pC is less than, equal to,
74724** or greater than pUnpacked.  Return SQLITE_OK on success.
74725**
74726** pUnpacked is either created without a rowid or is truncated so that it
74727** omits the rowid at the end.  The rowid at the end of the index entry
74728** is ignored as well.  Hence, this routine only compares the prefixes
74729** of the keys prior to the final rowid, not the entire key.
74730*/
74731SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
74732  sqlite3 *db,                     /* Database connection */
74733  VdbeCursor *pC,                  /* The cursor to compare against */
74734  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
74735  int *res                         /* Write the comparison result here */
74736){
74737  i64 nCellKey = 0;
74738  int rc;
74739  BtCursor *pCur;
74740  Mem m;
74741
74742  assert( pC->eCurType==CURTYPE_BTREE );
74743  pCur = pC->uc.pCursor;
74744  assert( sqlite3BtreeCursorIsValid(pCur) );
74745  nCellKey = sqlite3BtreePayloadSize(pCur);
74746  /* nCellKey will always be between 0 and 0xffffffff because of the way
74747  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
74748  if( nCellKey<=0 || nCellKey>0x7fffffff ){
74749    *res = 0;
74750    return SQLITE_CORRUPT_BKPT;
74751  }
74752  sqlite3VdbeMemInit(&m, db, 0);
74753  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74754  if( rc ){
74755    return rc;
74756  }
74757  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
74758  sqlite3VdbeMemRelease(&m);
74759  return SQLITE_OK;
74760}
74761
74762/*
74763** This routine sets the value to be returned by subsequent calls to
74764** sqlite3_changes() on the database handle 'db'.
74765*/
74766SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
74767  assert( sqlite3_mutex_held(db->mutex) );
74768  db->nChange = nChange;
74769  db->nTotalChange += nChange;
74770}
74771
74772/*
74773** Set a flag in the vdbe to update the change counter when it is finalised
74774** or reset.
74775*/
74776SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
74777  v->changeCntOn = 1;
74778}
74779
74780/*
74781** Mark every prepared statement associated with a database connection
74782** as expired.
74783**
74784** An expired statement means that recompilation of the statement is
74785** recommend.  Statements expire when things happen that make their
74786** programs obsolete.  Removing user-defined functions or collating
74787** sequences, or changing an authorization function are the types of
74788** things that make prepared statements obsolete.
74789*/
74790SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
74791  Vdbe *p;
74792  for(p = db->pVdbe; p; p=p->pNext){
74793    p->expired = 1;
74794  }
74795}
74796
74797/*
74798** Return the database associated with the Vdbe.
74799*/
74800SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
74801  return v->db;
74802}
74803
74804/*
74805** Return a pointer to an sqlite3_value structure containing the value bound
74806** parameter iVar of VM v. Except, if the value is an SQL NULL, return
74807** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
74808** constants) to the value before returning it.
74809**
74810** The returned value must be freed by the caller using sqlite3ValueFree().
74811*/
74812SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
74813  assert( iVar>0 );
74814  if( v ){
74815    Mem *pMem = &v->aVar[iVar-1];
74816    if( 0==(pMem->flags & MEM_Null) ){
74817      sqlite3_value *pRet = sqlite3ValueNew(v->db);
74818      if( pRet ){
74819        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
74820        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
74821      }
74822      return pRet;
74823    }
74824  }
74825  return 0;
74826}
74827
74828/*
74829** Configure SQL variable iVar so that binding a new value to it signals
74830** to sqlite3_reoptimize() that re-preparing the statement may result
74831** in a better query plan.
74832*/
74833SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
74834  assert( iVar>0 );
74835  if( iVar>32 ){
74836    v->expmask = 0xffffffff;
74837  }else{
74838    v->expmask |= ((u32)1 << (iVar-1));
74839  }
74840}
74841
74842#ifndef SQLITE_OMIT_VIRTUALTABLE
74843/*
74844** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
74845** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
74846** in memory obtained from sqlite3DbMalloc).
74847*/
74848SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
74849  if( pVtab->zErrMsg ){
74850    sqlite3 *db = p->db;
74851    sqlite3DbFree(db, p->zErrMsg);
74852    p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
74853    sqlite3_free(pVtab->zErrMsg);
74854    pVtab->zErrMsg = 0;
74855  }
74856}
74857#endif /* SQLITE_OMIT_VIRTUALTABLE */
74858
74859#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74860
74861/*
74862** If the second argument is not NULL, release any allocations associated
74863** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
74864** structure itself, using sqlite3DbFree().
74865**
74866** This function is used to free UnpackedRecord structures allocated by
74867** the vdbeUnpackRecord() function found in vdbeapi.c.
74868*/
74869static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
74870  if( p ){
74871    int i;
74872    for(i=0; i<p->nField; i++){
74873      Mem *pMem = &p->aMem[i];
74874      if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
74875    }
74876    sqlite3DbFree(db, p);
74877  }
74878}
74879#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74880
74881#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74882/*
74883** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
74884** then cursor passed as the second argument should point to the row about
74885** to be update or deleted. If the application calls sqlite3_preupdate_old(),
74886** the required value will be read from the row the cursor points to.
74887*/
74888SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
74889  Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
74890  VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
74891  int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
74892  const char *zDb,                /* Database name */
74893  Table *pTab,                    /* Modified table */
74894  i64 iKey1,                      /* Initial key value */
74895  int iReg                        /* Register for new.* record */
74896){
74897  sqlite3 *db = v->db;
74898  i64 iKey2;
74899  PreUpdate preupdate;
74900  const char *zTbl = pTab->zName;
74901  static const u8 fakeSortOrder = 0;
74902
74903  assert( db->pPreUpdate==0 );
74904  memset(&preupdate, 0, sizeof(PreUpdate));
74905  if( op==SQLITE_UPDATE ){
74906    iKey2 = v->aMem[iReg].u.i;
74907  }else{
74908    iKey2 = iKey1;
74909  }
74910
74911  assert( pCsr->nField==pTab->nCol
74912       || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
74913  );
74914
74915  preupdate.v = v;
74916  preupdate.pCsr = pCsr;
74917  preupdate.op = op;
74918  preupdate.iNewReg = iReg;
74919  preupdate.keyinfo.db = db;
74920  preupdate.keyinfo.enc = ENC(db);
74921  preupdate.keyinfo.nField = pTab->nCol;
74922  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
74923  preupdate.iKey1 = iKey1;
74924  preupdate.iKey2 = iKey2;
74925  preupdate.iPKey = pTab->iPKey;
74926
74927  db->pPreUpdate = &preupdate;
74928  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
74929  db->pPreUpdate = 0;
74930  sqlite3DbFree(db, preupdate.aRecord);
74931  vdbeFreeUnpacked(db, preupdate.pUnpacked);
74932  vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
74933  if( preupdate.aNew ){
74934    int i;
74935    for(i=0; i<pCsr->nField; i++){
74936      sqlite3VdbeMemRelease(&preupdate.aNew[i]);
74937    }
74938    sqlite3DbFree(db, preupdate.aNew);
74939  }
74940}
74941#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74942
74943/************** End of vdbeaux.c *********************************************/
74944/************** Begin file vdbeapi.c *****************************************/
74945/*
74946** 2004 May 26
74947**
74948** The author disclaims copyright to this source code.  In place of
74949** a legal notice, here is a blessing:
74950**
74951**    May you do good and not evil.
74952**    May you find forgiveness for yourself and forgive others.
74953**    May you share freely, never taking more than you give.
74954**
74955*************************************************************************
74956**
74957** This file contains code use to implement APIs that are part of the
74958** VDBE.
74959*/
74960/* #include "sqliteInt.h" */
74961/* #include "vdbeInt.h" */
74962
74963#ifndef SQLITE_OMIT_DEPRECATED
74964/*
74965** Return TRUE (non-zero) of the statement supplied as an argument needs
74966** to be recompiled.  A statement needs to be recompiled whenever the
74967** execution environment changes in a way that would alter the program
74968** that sqlite3_prepare() generates.  For example, if new functions or
74969** collating sequences are registered or if an authorizer function is
74970** added or changed.
74971*/
74972SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
74973  Vdbe *p = (Vdbe*)pStmt;
74974  return p==0 || p->expired;
74975}
74976#endif
74977
74978/*
74979** Check on a Vdbe to make sure it has not been finalized.  Log
74980** an error and return true if it has been finalized (or is otherwise
74981** invalid).  Return false if it is ok.
74982*/
74983static int vdbeSafety(Vdbe *p){
74984  if( p->db==0 ){
74985    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
74986    return 1;
74987  }else{
74988    return 0;
74989  }
74990}
74991static int vdbeSafetyNotNull(Vdbe *p){
74992  if( p==0 ){
74993    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
74994    return 1;
74995  }else{
74996    return vdbeSafety(p);
74997  }
74998}
74999
75000#ifndef SQLITE_OMIT_TRACE
75001/*
75002** Invoke the profile callback.  This routine is only called if we already
75003** know that the profile callback is defined and needs to be invoked.
75004*/
75005static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
75006  sqlite3_int64 iNow;
75007  sqlite3_int64 iElapse;
75008  assert( p->startTime>0 );
75009  assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
75010  assert( db->init.busy==0 );
75011  assert( p->zSql!=0 );
75012  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
75013  iElapse = (iNow - p->startTime)*1000000;
75014  if( db->xProfile ){
75015    db->xProfile(db->pProfileArg, p->zSql, iElapse);
75016  }
75017  if( db->mTrace & SQLITE_TRACE_PROFILE ){
75018    db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
75019  }
75020  p->startTime = 0;
75021}
75022/*
75023** The checkProfileCallback(DB,P) macro checks to see if a profile callback
75024** is needed, and it invokes the callback if it is needed.
75025*/
75026# define checkProfileCallback(DB,P) \
75027   if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
75028#else
75029# define checkProfileCallback(DB,P)  /*no-op*/
75030#endif
75031
75032/*
75033** The following routine destroys a virtual machine that is created by
75034** the sqlite3_compile() routine. The integer returned is an SQLITE_
75035** success/failure code that describes the result of executing the virtual
75036** machine.
75037**
75038** This routine sets the error code and string returned by
75039** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75040*/
75041SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
75042  int rc;
75043  if( pStmt==0 ){
75044    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
75045    ** pointer is a harmless no-op. */
75046    rc = SQLITE_OK;
75047  }else{
75048    Vdbe *v = (Vdbe*)pStmt;
75049    sqlite3 *db = v->db;
75050    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
75051    sqlite3_mutex_enter(db->mutex);
75052    checkProfileCallback(db, v);
75053    rc = sqlite3VdbeFinalize(v);
75054    rc = sqlite3ApiExit(db, rc);
75055    sqlite3LeaveMutexAndCloseZombie(db);
75056  }
75057  return rc;
75058}
75059
75060/*
75061** Terminate the current execution of an SQL statement and reset it
75062** back to its starting state so that it can be reused. A success code from
75063** the prior execution is returned.
75064**
75065** This routine sets the error code and string returned by
75066** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75067*/
75068SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
75069  int rc;
75070  if( pStmt==0 ){
75071    rc = SQLITE_OK;
75072  }else{
75073    Vdbe *v = (Vdbe*)pStmt;
75074    sqlite3 *db = v->db;
75075    sqlite3_mutex_enter(db->mutex);
75076    checkProfileCallback(db, v);
75077    rc = sqlite3VdbeReset(v);
75078    sqlite3VdbeRewind(v);
75079    assert( (rc & (db->errMask))==rc );
75080    rc = sqlite3ApiExit(db, rc);
75081    sqlite3_mutex_leave(db->mutex);
75082  }
75083  return rc;
75084}
75085
75086/*
75087** Set all the parameters in the compiled SQL statement to NULL.
75088*/
75089SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
75090  int i;
75091  int rc = SQLITE_OK;
75092  Vdbe *p = (Vdbe*)pStmt;
75093#if SQLITE_THREADSAFE
75094  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
75095#endif
75096  sqlite3_mutex_enter(mutex);
75097  for(i=0; i<p->nVar; i++){
75098    sqlite3VdbeMemRelease(&p->aVar[i]);
75099    p->aVar[i].flags = MEM_Null;
75100  }
75101  if( p->isPrepareV2 && p->expmask ){
75102    p->expired = 1;
75103  }
75104  sqlite3_mutex_leave(mutex);
75105  return rc;
75106}
75107
75108
75109/**************************** sqlite3_value_  *******************************
75110** The following routines extract information from a Mem or sqlite3_value
75111** structure.
75112*/
75113SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
75114  Mem *p = (Mem*)pVal;
75115  if( p->flags & (MEM_Blob|MEM_Str) ){
75116    if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
75117      assert( p->flags==MEM_Null && p->z==0 );
75118      return 0;
75119    }
75120    p->flags |= MEM_Blob;
75121    return p->n ? p->z : 0;
75122  }else{
75123    return sqlite3_value_text(pVal);
75124  }
75125}
75126SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
75127  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
75128}
75129SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
75130  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
75131}
75132SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
75133  return sqlite3VdbeRealValue((Mem*)pVal);
75134}
75135SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
75136  return (int)sqlite3VdbeIntValue((Mem*)pVal);
75137}
75138SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
75139  return sqlite3VdbeIntValue((Mem*)pVal);
75140}
75141SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *pVal){
75142  Mem *pMem = (Mem*)pVal;
75143  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
75144}
75145SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
75146  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
75147}
75148#ifndef SQLITE_OMIT_UTF16
75149SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
75150  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
75151}
75152SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
75153  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
75154}
75155SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
75156  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
75157}
75158#endif /* SQLITE_OMIT_UTF16 */
75159/* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
75160** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
75161** point number string BLOB NULL
75162*/
75163SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
75164  static const u8 aType[] = {
75165     SQLITE_BLOB,     /* 0x00 */
75166     SQLITE_NULL,     /* 0x01 */
75167     SQLITE_TEXT,     /* 0x02 */
75168     SQLITE_NULL,     /* 0x03 */
75169     SQLITE_INTEGER,  /* 0x04 */
75170     SQLITE_NULL,     /* 0x05 */
75171     SQLITE_INTEGER,  /* 0x06 */
75172     SQLITE_NULL,     /* 0x07 */
75173     SQLITE_FLOAT,    /* 0x08 */
75174     SQLITE_NULL,     /* 0x09 */
75175     SQLITE_FLOAT,    /* 0x0a */
75176     SQLITE_NULL,     /* 0x0b */
75177     SQLITE_INTEGER,  /* 0x0c */
75178     SQLITE_NULL,     /* 0x0d */
75179     SQLITE_INTEGER,  /* 0x0e */
75180     SQLITE_NULL,     /* 0x0f */
75181     SQLITE_BLOB,     /* 0x10 */
75182     SQLITE_NULL,     /* 0x11 */
75183     SQLITE_TEXT,     /* 0x12 */
75184     SQLITE_NULL,     /* 0x13 */
75185     SQLITE_INTEGER,  /* 0x14 */
75186     SQLITE_NULL,     /* 0x15 */
75187     SQLITE_INTEGER,  /* 0x16 */
75188     SQLITE_NULL,     /* 0x17 */
75189     SQLITE_FLOAT,    /* 0x18 */
75190     SQLITE_NULL,     /* 0x19 */
75191     SQLITE_FLOAT,    /* 0x1a */
75192     SQLITE_NULL,     /* 0x1b */
75193     SQLITE_INTEGER,  /* 0x1c */
75194     SQLITE_NULL,     /* 0x1d */
75195     SQLITE_INTEGER,  /* 0x1e */
75196     SQLITE_NULL,     /* 0x1f */
75197  };
75198  return aType[pVal->flags&MEM_AffMask];
75199}
75200
75201/* Make a copy of an sqlite3_value object
75202*/
75203SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
75204  sqlite3_value *pNew;
75205  if( pOrig==0 ) return 0;
75206  pNew = sqlite3_malloc( sizeof(*pNew) );
75207  if( pNew==0 ) return 0;
75208  memset(pNew, 0, sizeof(*pNew));
75209  memcpy(pNew, pOrig, MEMCELLSIZE);
75210  pNew->flags &= ~MEM_Dyn;
75211  pNew->db = 0;
75212  if( pNew->flags&(MEM_Str|MEM_Blob) ){
75213    pNew->flags &= ~(MEM_Static|MEM_Dyn);
75214    pNew->flags |= MEM_Ephem;
75215    if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
75216      sqlite3ValueFree(pNew);
75217      pNew = 0;
75218    }
75219  }
75220  return pNew;
75221}
75222
75223/* Destroy an sqlite3_value object previously obtained from
75224** sqlite3_value_dup().
75225*/
75226SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
75227  sqlite3ValueFree(pOld);
75228}
75229
75230
75231/**************************** sqlite3_result_  *******************************
75232** The following routines are used by user-defined functions to specify
75233** the function result.
75234**
75235** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
75236** result as a string or blob but if the string or blob is too large, it
75237** then sets the error code to SQLITE_TOOBIG
75238**
75239** The invokeValueDestructor(P,X) routine invokes destructor function X()
75240** on value P is not going to be used and need to be destroyed.
75241*/
75242static void setResultStrOrError(
75243  sqlite3_context *pCtx,  /* Function context */
75244  const char *z,          /* String pointer */
75245  int n,                  /* Bytes in string, or negative */
75246  u8 enc,                 /* Encoding of z.  0 for BLOBs */
75247  void (*xDel)(void*)     /* Destructor function */
75248){
75249  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
75250    sqlite3_result_error_toobig(pCtx);
75251  }
75252}
75253static int invokeValueDestructor(
75254  const void *p,             /* Value to destroy */
75255  void (*xDel)(void*),       /* The destructor */
75256  sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
75257){
75258  assert( xDel!=SQLITE_DYNAMIC );
75259  if( xDel==0 ){
75260    /* noop */
75261  }else if( xDel==SQLITE_TRANSIENT ){
75262    /* noop */
75263  }else{
75264    xDel((void*)p);
75265  }
75266  if( pCtx ) sqlite3_result_error_toobig(pCtx);
75267  return SQLITE_TOOBIG;
75268}
75269SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
75270  sqlite3_context *pCtx,
75271  const void *z,
75272  int n,
75273  void (*xDel)(void *)
75274){
75275  assert( n>=0 );
75276  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75277  setResultStrOrError(pCtx, z, n, 0, xDel);
75278}
75279SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
75280  sqlite3_context *pCtx,
75281  const void *z,
75282  sqlite3_uint64 n,
75283  void (*xDel)(void *)
75284){
75285  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75286  assert( xDel!=SQLITE_DYNAMIC );
75287  if( n>0x7fffffff ){
75288    (void)invokeValueDestructor(z, xDel, pCtx);
75289  }else{
75290    setResultStrOrError(pCtx, z, (int)n, 0, xDel);
75291  }
75292}
75293SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
75294  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75295  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
75296}
75297SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
75298  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75299  pCtx->isError = SQLITE_ERROR;
75300  pCtx->fErrorOrAux = 1;
75301  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
75302}
75303#ifndef SQLITE_OMIT_UTF16
75304SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
75305  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75306  pCtx->isError = SQLITE_ERROR;
75307  pCtx->fErrorOrAux = 1;
75308  sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
75309}
75310#endif
75311SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
75312  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75313  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
75314}
75315SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
75316  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75317  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
75318}
75319SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
75320  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75321  sqlite3VdbeMemSetNull(pCtx->pOut);
75322}
75323SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
75324  Mem *pOut = pCtx->pOut;
75325  assert( sqlite3_mutex_held(pOut->db->mutex) );
75326  pOut->eSubtype = eSubtype & 0xff;
75327  pOut->flags |= MEM_Subtype;
75328}
75329SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
75330  sqlite3_context *pCtx,
75331  const char *z,
75332  int n,
75333  void (*xDel)(void *)
75334){
75335  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75336  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
75337}
75338SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
75339  sqlite3_context *pCtx,
75340  const char *z,
75341  sqlite3_uint64 n,
75342  void (*xDel)(void *),
75343  unsigned char enc
75344){
75345  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75346  assert( xDel!=SQLITE_DYNAMIC );
75347  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
75348  if( n>0x7fffffff ){
75349    (void)invokeValueDestructor(z, xDel, pCtx);
75350  }else{
75351    setResultStrOrError(pCtx, z, (int)n, enc, xDel);
75352  }
75353}
75354#ifndef SQLITE_OMIT_UTF16
75355SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
75356  sqlite3_context *pCtx,
75357  const void *z,
75358  int n,
75359  void (*xDel)(void *)
75360){
75361  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75362  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
75363}
75364SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
75365  sqlite3_context *pCtx,
75366  const void *z,
75367  int n,
75368  void (*xDel)(void *)
75369){
75370  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75371  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
75372}
75373SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
75374  sqlite3_context *pCtx,
75375  const void *z,
75376  int n,
75377  void (*xDel)(void *)
75378){
75379  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75380  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
75381}
75382#endif /* SQLITE_OMIT_UTF16 */
75383SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
75384  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75385  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
75386}
75387SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
75388  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75389  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
75390}
75391SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
75392  Mem *pOut = pCtx->pOut;
75393  assert( sqlite3_mutex_held(pOut->db->mutex) );
75394  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
75395    return SQLITE_TOOBIG;
75396  }
75397  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
75398  return SQLITE_OK;
75399}
75400SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
75401  pCtx->isError = errCode;
75402  pCtx->fErrorOrAux = 1;
75403#ifdef SQLITE_DEBUG
75404  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
75405#endif
75406  if( pCtx->pOut->flags & MEM_Null ){
75407    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
75408                         SQLITE_UTF8, SQLITE_STATIC);
75409  }
75410}
75411
75412/* Force an SQLITE_TOOBIG error. */
75413SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
75414  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75415  pCtx->isError = SQLITE_TOOBIG;
75416  pCtx->fErrorOrAux = 1;
75417  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
75418                       SQLITE_UTF8, SQLITE_STATIC);
75419}
75420
75421/* An SQLITE_NOMEM error. */
75422SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
75423  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75424  sqlite3VdbeMemSetNull(pCtx->pOut);
75425  pCtx->isError = SQLITE_NOMEM_BKPT;
75426  pCtx->fErrorOrAux = 1;
75427  sqlite3OomFault(pCtx->pOut->db);
75428}
75429
75430/*
75431** This function is called after a transaction has been committed. It
75432** invokes callbacks registered with sqlite3_wal_hook() as required.
75433*/
75434static int doWalCallbacks(sqlite3 *db){
75435  int rc = SQLITE_OK;
75436#ifndef SQLITE_OMIT_WAL
75437  int i;
75438  for(i=0; i<db->nDb; i++){
75439    Btree *pBt = db->aDb[i].pBt;
75440    if( pBt ){
75441      int nEntry;
75442      sqlite3BtreeEnter(pBt);
75443      nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
75444      sqlite3BtreeLeave(pBt);
75445      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
75446        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
75447      }
75448    }
75449  }
75450#endif
75451  return rc;
75452}
75453
75454
75455/*
75456** Execute the statement pStmt, either until a row of data is ready, the
75457** statement is completely executed or an error occurs.
75458**
75459** This routine implements the bulk of the logic behind the sqlite_step()
75460** API.  The only thing omitted is the automatic recompile if a
75461** schema change has occurred.  That detail is handled by the
75462** outer sqlite3_step() wrapper procedure.
75463*/
75464static int sqlite3Step(Vdbe *p){
75465  sqlite3 *db;
75466  int rc;
75467
75468  assert(p);
75469  if( p->magic!=VDBE_MAGIC_RUN ){
75470    /* We used to require that sqlite3_reset() be called before retrying
75471    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
75472    ** with version 3.7.0, we changed this so that sqlite3_reset() would
75473    ** be called automatically instead of throwing the SQLITE_MISUSE error.
75474    ** This "automatic-reset" change is not technically an incompatibility,
75475    ** since any application that receives an SQLITE_MISUSE is broken by
75476    ** definition.
75477    **
75478    ** Nevertheless, some published applications that were originally written
75479    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
75480    ** returns, and those were broken by the automatic-reset change.  As a
75481    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
75482    ** legacy behavior of returning SQLITE_MISUSE for cases where the
75483    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
75484    ** or SQLITE_BUSY error.
75485    */
75486#ifdef SQLITE_OMIT_AUTORESET
75487    if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
75488      sqlite3_reset((sqlite3_stmt*)p);
75489    }else{
75490      return SQLITE_MISUSE_BKPT;
75491    }
75492#else
75493    sqlite3_reset((sqlite3_stmt*)p);
75494#endif
75495  }
75496
75497  /* Check that malloc() has not failed. If it has, return early. */
75498  db = p->db;
75499  if( db->mallocFailed ){
75500    p->rc = SQLITE_NOMEM;
75501    return SQLITE_NOMEM_BKPT;
75502  }
75503
75504  if( p->pc<=0 && p->expired ){
75505    p->rc = SQLITE_SCHEMA;
75506    rc = SQLITE_ERROR;
75507    goto end_of_step;
75508  }
75509  if( p->pc<0 ){
75510    /* If there are no other statements currently running, then
75511    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
75512    ** from interrupting a statement that has not yet started.
75513    */
75514    if( db->nVdbeActive==0 ){
75515      db->u1.isInterrupted = 0;
75516    }
75517
75518    assert( db->nVdbeWrite>0 || db->autoCommit==0
75519        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
75520    );
75521
75522#ifndef SQLITE_OMIT_TRACE
75523    if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
75524        && !db->init.busy && p->zSql ){
75525      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
75526    }else{
75527      assert( p->startTime==0 );
75528    }
75529#endif
75530
75531    db->nVdbeActive++;
75532    if( p->readOnly==0 ) db->nVdbeWrite++;
75533    if( p->bIsReader ) db->nVdbeRead++;
75534    p->pc = 0;
75535  }
75536#ifdef SQLITE_DEBUG
75537  p->rcApp = SQLITE_OK;
75538#endif
75539#ifndef SQLITE_OMIT_EXPLAIN
75540  if( p->explain ){
75541    rc = sqlite3VdbeList(p);
75542  }else
75543#endif /* SQLITE_OMIT_EXPLAIN */
75544  {
75545    db->nVdbeExec++;
75546    rc = sqlite3VdbeExec(p);
75547    db->nVdbeExec--;
75548  }
75549
75550#ifndef SQLITE_OMIT_TRACE
75551  /* If the statement completed successfully, invoke the profile callback */
75552  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
75553#endif
75554
75555  if( rc==SQLITE_DONE ){
75556    assert( p->rc==SQLITE_OK );
75557    p->rc = doWalCallbacks(db);
75558    if( p->rc!=SQLITE_OK ){
75559      rc = SQLITE_ERROR;
75560    }
75561  }
75562
75563  db->errCode = rc;
75564  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
75565    p->rc = SQLITE_NOMEM_BKPT;
75566  }
75567end_of_step:
75568  /* At this point local variable rc holds the value that should be
75569  ** returned if this statement was compiled using the legacy
75570  ** sqlite3_prepare() interface. According to the docs, this can only
75571  ** be one of the values in the first assert() below. Variable p->rc
75572  ** contains the value that would be returned if sqlite3_finalize()
75573  ** were called on statement p.
75574  */
75575  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
75576       || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
75577  );
75578  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
75579  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
75580    /* If this statement was prepared using sqlite3_prepare_v2(), and an
75581    ** error has occurred, then return the error code in p->rc to the
75582    ** caller. Set the error code in the database handle to the same value.
75583    */
75584    rc = sqlite3VdbeTransferError(p);
75585  }
75586  return (rc&db->errMask);
75587}
75588
75589/*
75590** This is the top-level implementation of sqlite3_step().  Call
75591** sqlite3Step() to do most of the work.  If a schema error occurs,
75592** call sqlite3Reprepare() and try again.
75593*/
75594SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
75595  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
75596  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
75597  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
75598  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
75599  sqlite3 *db;             /* The database connection */
75600
75601  if( vdbeSafetyNotNull(v) ){
75602    return SQLITE_MISUSE_BKPT;
75603  }
75604  db = v->db;
75605  sqlite3_mutex_enter(db->mutex);
75606  v->doingRerun = 0;
75607  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
75608         && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
75609    int savedPc = v->pc;
75610    rc2 = rc = sqlite3Reprepare(v);
75611    if( rc!=SQLITE_OK) break;
75612    sqlite3_reset(pStmt);
75613    if( savedPc>=0 ) v->doingRerun = 1;
75614    assert( v->expired==0 );
75615  }
75616  if( rc2!=SQLITE_OK ){
75617    /* This case occurs after failing to recompile an sql statement.
75618    ** The error message from the SQL compiler has already been loaded
75619    ** into the database handle. This block copies the error message
75620    ** from the database handle into the statement and sets the statement
75621    ** program counter to 0 to ensure that when the statement is
75622    ** finalized or reset the parser error message is available via
75623    ** sqlite3_errmsg() and sqlite3_errcode().
75624    */
75625    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
75626    sqlite3DbFree(db, v->zErrMsg);
75627    if( !db->mallocFailed ){
75628      v->zErrMsg = sqlite3DbStrDup(db, zErr);
75629      v->rc = rc2;
75630    } else {
75631      v->zErrMsg = 0;
75632      v->rc = rc = SQLITE_NOMEM_BKPT;
75633    }
75634  }
75635  rc = sqlite3ApiExit(db, rc);
75636  sqlite3_mutex_leave(db->mutex);
75637  return rc;
75638}
75639
75640
75641/*
75642** Extract the user data from a sqlite3_context structure and return a
75643** pointer to it.
75644*/
75645SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
75646  assert( p && p->pFunc );
75647  return p->pFunc->pUserData;
75648}
75649
75650/*
75651** Extract the user data from a sqlite3_context structure and return a
75652** pointer to it.
75653**
75654** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
75655** returns a copy of the pointer to the database connection (the 1st
75656** parameter) of the sqlite3_create_function() and
75657** sqlite3_create_function16() routines that originally registered the
75658** application defined function.
75659*/
75660SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
75661  assert( p && p->pOut );
75662  return p->pOut->db;
75663}
75664
75665/*
75666** Return the current time for a statement.  If the current time
75667** is requested more than once within the same run of a single prepared
75668** statement, the exact same time is returned for each invocation regardless
75669** of the amount of time that elapses between invocations.  In other words,
75670** the time returned is always the time of the first call.
75671*/
75672SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
75673  int rc;
75674#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
75675  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
75676  assert( p->pVdbe!=0 );
75677#else
75678  sqlite3_int64 iTime = 0;
75679  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
75680#endif
75681  if( *piTime==0 ){
75682    rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
75683    if( rc ) *piTime = 0;
75684  }
75685  return *piTime;
75686}
75687
75688/*
75689** The following is the implementation of an SQL function that always
75690** fails with an error message stating that the function is used in the
75691** wrong context.  The sqlite3_overload_function() API might construct
75692** SQL function that use this routine so that the functions will exist
75693** for name resolution but are actually overloaded by the xFindFunction
75694** method of virtual tables.
75695*/
75696SQLITE_PRIVATE void sqlite3InvalidFunction(
75697  sqlite3_context *context,  /* The function calling context */
75698  int NotUsed,               /* Number of arguments to the function */
75699  sqlite3_value **NotUsed2   /* Value of each argument */
75700){
75701  const char *zName = context->pFunc->zName;
75702  char *zErr;
75703  UNUSED_PARAMETER2(NotUsed, NotUsed2);
75704  zErr = sqlite3_mprintf(
75705      "unable to use function %s in the requested context", zName);
75706  sqlite3_result_error(context, zErr, -1);
75707  sqlite3_free(zErr);
75708}
75709
75710/*
75711** Create a new aggregate context for p and return a pointer to
75712** its pMem->z element.
75713*/
75714static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
75715  Mem *pMem = p->pMem;
75716  assert( (pMem->flags & MEM_Agg)==0 );
75717  if( nByte<=0 ){
75718    sqlite3VdbeMemSetNull(pMem);
75719    pMem->z = 0;
75720  }else{
75721    sqlite3VdbeMemClearAndResize(pMem, nByte);
75722    pMem->flags = MEM_Agg;
75723    pMem->u.pDef = p->pFunc;
75724    if( pMem->z ){
75725      memset(pMem->z, 0, nByte);
75726    }
75727  }
75728  return (void*)pMem->z;
75729}
75730
75731/*
75732** Allocate or return the aggregate context for a user function.  A new
75733** context is allocated on the first call.  Subsequent calls return the
75734** same context that was returned on prior calls.
75735*/
75736SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
75737  assert( p && p->pFunc && p->pFunc->xFinalize );
75738  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
75739  testcase( nByte<0 );
75740  if( (p->pMem->flags & MEM_Agg)==0 ){
75741    return createAggContext(p, nByte);
75742  }else{
75743    return (void*)p->pMem->z;
75744  }
75745}
75746
75747/*
75748** Return the auxiliary data pointer, if any, for the iArg'th argument to
75749** the user-function defined by pCtx.
75750*/
75751SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
75752  AuxData *pAuxData;
75753
75754  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75755#if SQLITE_ENABLE_STAT3_OR_STAT4
75756  if( pCtx->pVdbe==0 ) return 0;
75757#else
75758  assert( pCtx->pVdbe!=0 );
75759#endif
75760  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75761    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75762  }
75763
75764  return (pAuxData ? pAuxData->pAux : 0);
75765}
75766
75767/*
75768** Set the auxiliary data pointer and delete function, for the iArg'th
75769** argument to the user-function defined by pCtx. Any previous value is
75770** deleted by calling the delete function specified when it was set.
75771*/
75772SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
75773  sqlite3_context *pCtx,
75774  int iArg,
75775  void *pAux,
75776  void (*xDelete)(void*)
75777){
75778  AuxData *pAuxData;
75779  Vdbe *pVdbe = pCtx->pVdbe;
75780
75781  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75782  if( iArg<0 ) goto failed;
75783#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
75784  if( pVdbe==0 ) goto failed;
75785#else
75786  assert( pVdbe!=0 );
75787#endif
75788
75789  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75790    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75791  }
75792  if( pAuxData==0 ){
75793    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
75794    if( !pAuxData ) goto failed;
75795    pAuxData->iOp = pCtx->iOp;
75796    pAuxData->iArg = iArg;
75797    pAuxData->pNext = pVdbe->pAuxData;
75798    pVdbe->pAuxData = pAuxData;
75799    if( pCtx->fErrorOrAux==0 ){
75800      pCtx->isError = 0;
75801      pCtx->fErrorOrAux = 1;
75802    }
75803  }else if( pAuxData->xDelete ){
75804    pAuxData->xDelete(pAuxData->pAux);
75805  }
75806
75807  pAuxData->pAux = pAux;
75808  pAuxData->xDelete = xDelete;
75809  return;
75810
75811failed:
75812  if( xDelete ){
75813    xDelete(pAux);
75814  }
75815}
75816
75817#ifndef SQLITE_OMIT_DEPRECATED
75818/*
75819** Return the number of times the Step function of an aggregate has been
75820** called.
75821**
75822** This function is deprecated.  Do not use it for new code.  It is
75823** provide only to avoid breaking legacy code.  New aggregate function
75824** implementations should keep their own counts within their aggregate
75825** context.
75826*/
75827SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
75828  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
75829  return p->pMem->n;
75830}
75831#endif
75832
75833/*
75834** Return the number of columns in the result set for the statement pStmt.
75835*/
75836SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
75837  Vdbe *pVm = (Vdbe *)pStmt;
75838  return pVm ? pVm->nResColumn : 0;
75839}
75840
75841/*
75842** Return the number of values available from the current row of the
75843** currently executing statement pStmt.
75844*/
75845SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
75846  Vdbe *pVm = (Vdbe *)pStmt;
75847  if( pVm==0 || pVm->pResultSet==0 ) return 0;
75848  return pVm->nResColumn;
75849}
75850
75851/*
75852** Return a pointer to static memory containing an SQL NULL value.
75853*/
75854static const Mem *columnNullValue(void){
75855  /* Even though the Mem structure contains an element
75856  ** of type i64, on certain architectures (x86) with certain compiler
75857  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
75858  ** instead of an 8-byte one. This all works fine, except that when
75859  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
75860  ** that a Mem structure is located on an 8-byte boundary. To prevent
75861  ** these assert()s from failing, when building with SQLITE_DEBUG defined
75862  ** using gcc, we force nullMem to be 8-byte aligned using the magical
75863  ** __attribute__((aligned(8))) macro.  */
75864  static const Mem nullMem
75865#if defined(SQLITE_DEBUG) && defined(__GNUC__)
75866    __attribute__((aligned(8)))
75867#endif
75868    = {
75869        /* .u          = */ {0},
75870        /* .flags      = */ (u16)MEM_Null,
75871        /* .enc        = */ (u8)0,
75872        /* .eSubtype   = */ (u8)0,
75873        /* .n          = */ (int)0,
75874        /* .z          = */ (char*)0,
75875        /* .zMalloc    = */ (char*)0,
75876        /* .szMalloc   = */ (int)0,
75877        /* .uTemp      = */ (u32)0,
75878        /* .db         = */ (sqlite3*)0,
75879        /* .xDel       = */ (void(*)(void*))0,
75880#ifdef SQLITE_DEBUG
75881        /* .pScopyFrom = */ (Mem*)0,
75882        /* .pFiller    = */ (void*)0,
75883#endif
75884      };
75885  return &nullMem;
75886}
75887
75888/*
75889** Check to see if column iCol of the given statement is valid.  If
75890** it is, return a pointer to the Mem for the value of that column.
75891** If iCol is not valid, return a pointer to a Mem which has a value
75892** of NULL.
75893*/
75894static Mem *columnMem(sqlite3_stmt *pStmt, int i){
75895  Vdbe *pVm;
75896  Mem *pOut;
75897
75898  pVm = (Vdbe *)pStmt;
75899  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
75900    sqlite3_mutex_enter(pVm->db->mutex);
75901    pOut = &pVm->pResultSet[i];
75902  }else{
75903    if( pVm && ALWAYS(pVm->db) ){
75904      sqlite3_mutex_enter(pVm->db->mutex);
75905      sqlite3Error(pVm->db, SQLITE_RANGE);
75906    }
75907    pOut = (Mem*)columnNullValue();
75908  }
75909  return pOut;
75910}
75911
75912/*
75913** This function is called after invoking an sqlite3_value_XXX function on a
75914** column value (i.e. a value returned by evaluating an SQL expression in the
75915** select list of a SELECT statement) that may cause a malloc() failure. If
75916** malloc() has failed, the threads mallocFailed flag is cleared and the result
75917** code of statement pStmt set to SQLITE_NOMEM.
75918**
75919** Specifically, this is called from within:
75920**
75921**     sqlite3_column_int()
75922**     sqlite3_column_int64()
75923**     sqlite3_column_text()
75924**     sqlite3_column_text16()
75925**     sqlite3_column_real()
75926**     sqlite3_column_bytes()
75927**     sqlite3_column_bytes16()
75928**     sqiite3_column_blob()
75929*/
75930static void columnMallocFailure(sqlite3_stmt *pStmt)
75931{
75932  /* If malloc() failed during an encoding conversion within an
75933  ** sqlite3_column_XXX API, then set the return code of the statement to
75934  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
75935  ** and _finalize() will return NOMEM.
75936  */
75937  Vdbe *p = (Vdbe *)pStmt;
75938  if( p ){
75939    p->rc = sqlite3ApiExit(p->db, p->rc);
75940    sqlite3_mutex_leave(p->db->mutex);
75941  }
75942}
75943
75944/**************************** sqlite3_column_  *******************************
75945** The following routines are used to access elements of the current row
75946** in the result set.
75947*/
75948SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
75949  const void *val;
75950  val = sqlite3_value_blob( columnMem(pStmt,i) );
75951  /* Even though there is no encoding conversion, value_blob() might
75952  ** need to call malloc() to expand the result of a zeroblob()
75953  ** expression.
75954  */
75955  columnMallocFailure(pStmt);
75956  return val;
75957}
75958SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
75959  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
75960  columnMallocFailure(pStmt);
75961  return val;
75962}
75963SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
75964  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
75965  columnMallocFailure(pStmt);
75966  return val;
75967}
75968SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
75969  double val = sqlite3_value_double( columnMem(pStmt,i) );
75970  columnMallocFailure(pStmt);
75971  return val;
75972}
75973SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
75974  int val = sqlite3_value_int( columnMem(pStmt,i) );
75975  columnMallocFailure(pStmt);
75976  return val;
75977}
75978SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
75979  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
75980  columnMallocFailure(pStmt);
75981  return val;
75982}
75983SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
75984  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
75985  columnMallocFailure(pStmt);
75986  return val;
75987}
75988SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
75989  Mem *pOut = columnMem(pStmt, i);
75990  if( pOut->flags&MEM_Static ){
75991    pOut->flags &= ~MEM_Static;
75992    pOut->flags |= MEM_Ephem;
75993  }
75994  columnMallocFailure(pStmt);
75995  return (sqlite3_value *)pOut;
75996}
75997#ifndef SQLITE_OMIT_UTF16
75998SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
75999  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
76000  columnMallocFailure(pStmt);
76001  return val;
76002}
76003#endif /* SQLITE_OMIT_UTF16 */
76004SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
76005  int iType = sqlite3_value_type( columnMem(pStmt,i) );
76006  columnMallocFailure(pStmt);
76007  return iType;
76008}
76009
76010/*
76011** Convert the N-th element of pStmt->pColName[] into a string using
76012** xFunc() then return that string.  If N is out of range, return 0.
76013**
76014** There are up to 5 names for each column.  useType determines which
76015** name is returned.  Here are the names:
76016**
76017**    0      The column name as it should be displayed for output
76018**    1      The datatype name for the column
76019**    2      The name of the database that the column derives from
76020**    3      The name of the table that the column derives from
76021**    4      The name of the table column that the result column derives from
76022**
76023** If the result is not a simple column reference (if it is an expression
76024** or a constant) then useTypes 2, 3, and 4 return NULL.
76025*/
76026static const void *columnName(
76027  sqlite3_stmt *pStmt,
76028  int N,
76029  const void *(*xFunc)(Mem*),
76030  int useType
76031){
76032  const void *ret;
76033  Vdbe *p;
76034  int n;
76035  sqlite3 *db;
76036#ifdef SQLITE_ENABLE_API_ARMOR
76037  if( pStmt==0 ){
76038    (void)SQLITE_MISUSE_BKPT;
76039    return 0;
76040  }
76041#endif
76042  ret = 0;
76043  p = (Vdbe *)pStmt;
76044  db = p->db;
76045  assert( db!=0 );
76046  n = sqlite3_column_count(pStmt);
76047  if( N<n && N>=0 ){
76048    N += useType*n;
76049    sqlite3_mutex_enter(db->mutex);
76050    assert( db->mallocFailed==0 );
76051    ret = xFunc(&p->aColName[N]);
76052     /* A malloc may have failed inside of the xFunc() call. If this
76053    ** is the case, clear the mallocFailed flag and return NULL.
76054    */
76055    if( db->mallocFailed ){
76056      sqlite3OomClear(db);
76057      ret = 0;
76058    }
76059    sqlite3_mutex_leave(db->mutex);
76060  }
76061  return ret;
76062}
76063
76064/*
76065** Return the name of the Nth column of the result set returned by SQL
76066** statement pStmt.
76067*/
76068SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
76069  return columnName(
76070      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
76071}
76072#ifndef SQLITE_OMIT_UTF16
76073SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
76074  return columnName(
76075      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
76076}
76077#endif
76078
76079/*
76080** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
76081** not define OMIT_DECLTYPE.
76082*/
76083#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
76084# error "Must not define both SQLITE_OMIT_DECLTYPE \
76085         and SQLITE_ENABLE_COLUMN_METADATA"
76086#endif
76087
76088#ifndef SQLITE_OMIT_DECLTYPE
76089/*
76090** Return the column declaration type (if applicable) of the 'i'th column
76091** of the result set of SQL statement pStmt.
76092*/
76093SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
76094  return columnName(
76095      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
76096}
76097#ifndef SQLITE_OMIT_UTF16
76098SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
76099  return columnName(
76100      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
76101}
76102#endif /* SQLITE_OMIT_UTF16 */
76103#endif /* SQLITE_OMIT_DECLTYPE */
76104
76105#ifdef SQLITE_ENABLE_COLUMN_METADATA
76106/*
76107** Return the name of the database from which a result column derives.
76108** NULL is returned if the result column is an expression or constant or
76109** anything else which is not an unambiguous reference to a database column.
76110*/
76111SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
76112  return columnName(
76113      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
76114}
76115#ifndef SQLITE_OMIT_UTF16
76116SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
76117  return columnName(
76118      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
76119}
76120#endif /* SQLITE_OMIT_UTF16 */
76121
76122/*
76123** Return the name of the table from which a result column derives.
76124** NULL is returned if the result column is an expression or constant or
76125** anything else which is not an unambiguous reference to a database column.
76126*/
76127SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
76128  return columnName(
76129      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
76130}
76131#ifndef SQLITE_OMIT_UTF16
76132SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
76133  return columnName(
76134      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
76135}
76136#endif /* SQLITE_OMIT_UTF16 */
76137
76138/*
76139** Return the name of the table column from which a result column derives.
76140** NULL is returned if the result column is an expression or constant or
76141** anything else which is not an unambiguous reference to a database column.
76142*/
76143SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
76144  return columnName(
76145      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
76146}
76147#ifndef SQLITE_OMIT_UTF16
76148SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
76149  return columnName(
76150      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
76151}
76152#endif /* SQLITE_OMIT_UTF16 */
76153#endif /* SQLITE_ENABLE_COLUMN_METADATA */
76154
76155
76156/******************************* sqlite3_bind_  ***************************
76157**
76158** Routines used to attach values to wildcards in a compiled SQL statement.
76159*/
76160/*
76161** Unbind the value bound to variable i in virtual machine p. This is the
76162** the same as binding a NULL value to the column. If the "i" parameter is
76163** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
76164**
76165** A successful evaluation of this routine acquires the mutex on p.
76166** the mutex is released if any kind of error occurs.
76167**
76168** The error code stored in database p->db is overwritten with the return
76169** value in any case.
76170*/
76171static int vdbeUnbind(Vdbe *p, int i){
76172  Mem *pVar;
76173  if( vdbeSafetyNotNull(p) ){
76174    return SQLITE_MISUSE_BKPT;
76175  }
76176  sqlite3_mutex_enter(p->db->mutex);
76177  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
76178    sqlite3Error(p->db, SQLITE_MISUSE);
76179    sqlite3_mutex_leave(p->db->mutex);
76180    sqlite3_log(SQLITE_MISUSE,
76181        "bind on a busy prepared statement: [%s]", p->zSql);
76182    return SQLITE_MISUSE_BKPT;
76183  }
76184  if( i<1 || i>p->nVar ){
76185    sqlite3Error(p->db, SQLITE_RANGE);
76186    sqlite3_mutex_leave(p->db->mutex);
76187    return SQLITE_RANGE;
76188  }
76189  i--;
76190  pVar = &p->aVar[i];
76191  sqlite3VdbeMemRelease(pVar);
76192  pVar->flags = MEM_Null;
76193  sqlite3Error(p->db, SQLITE_OK);
76194
76195  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
76196  ** binding a new value to this variable invalidates the current query plan.
76197  **
76198  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
76199  ** parameter in the WHERE clause might influence the choice of query plan
76200  ** for a statement, then the statement will be automatically recompiled,
76201  ** as if there had been a schema change, on the first sqlite3_step() call
76202  ** following any change to the bindings of that parameter.
76203  */
76204  if( p->isPrepareV2 &&
76205     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
76206  ){
76207    p->expired = 1;
76208  }
76209  return SQLITE_OK;
76210}
76211
76212/*
76213** Bind a text or BLOB value.
76214*/
76215static int bindText(
76216  sqlite3_stmt *pStmt,   /* The statement to bind against */
76217  int i,                 /* Index of the parameter to bind */
76218  const void *zData,     /* Pointer to the data to be bound */
76219  int nData,             /* Number of bytes of data to be bound */
76220  void (*xDel)(void*),   /* Destructor for the data */
76221  u8 encoding            /* Encoding for the data */
76222){
76223  Vdbe *p = (Vdbe *)pStmt;
76224  Mem *pVar;
76225  int rc;
76226
76227  rc = vdbeUnbind(p, i);
76228  if( rc==SQLITE_OK ){
76229    if( zData!=0 ){
76230      pVar = &p->aVar[i-1];
76231      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
76232      if( rc==SQLITE_OK && encoding!=0 ){
76233        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
76234      }
76235      sqlite3Error(p->db, rc);
76236      rc = sqlite3ApiExit(p->db, rc);
76237    }
76238    sqlite3_mutex_leave(p->db->mutex);
76239  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
76240    xDel((void*)zData);
76241  }
76242  return rc;
76243}
76244
76245
76246/*
76247** Bind a blob value to an SQL statement variable.
76248*/
76249SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
76250  sqlite3_stmt *pStmt,
76251  int i,
76252  const void *zData,
76253  int nData,
76254  void (*xDel)(void*)
76255){
76256#ifdef SQLITE_ENABLE_API_ARMOR
76257  if( nData<0 ) return SQLITE_MISUSE_BKPT;
76258#endif
76259  return bindText(pStmt, i, zData, nData, xDel, 0);
76260}
76261SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
76262  sqlite3_stmt *pStmt,
76263  int i,
76264  const void *zData,
76265  sqlite3_uint64 nData,
76266  void (*xDel)(void*)
76267){
76268  assert( xDel!=SQLITE_DYNAMIC );
76269  if( nData>0x7fffffff ){
76270    return invokeValueDestructor(zData, xDel, 0);
76271  }else{
76272    return bindText(pStmt, i, zData, (int)nData, xDel, 0);
76273  }
76274}
76275SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
76276  int rc;
76277  Vdbe *p = (Vdbe *)pStmt;
76278  rc = vdbeUnbind(p, i);
76279  if( rc==SQLITE_OK ){
76280    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
76281    sqlite3_mutex_leave(p->db->mutex);
76282  }
76283  return rc;
76284}
76285SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
76286  return sqlite3_bind_int64(p, i, (i64)iValue);
76287}
76288SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
76289  int rc;
76290  Vdbe *p = (Vdbe *)pStmt;
76291  rc = vdbeUnbind(p, i);
76292  if( rc==SQLITE_OK ){
76293    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
76294    sqlite3_mutex_leave(p->db->mutex);
76295  }
76296  return rc;
76297}
76298SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
76299  int rc;
76300  Vdbe *p = (Vdbe*)pStmt;
76301  rc = vdbeUnbind(p, i);
76302  if( rc==SQLITE_OK ){
76303    sqlite3_mutex_leave(p->db->mutex);
76304  }
76305  return rc;
76306}
76307SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
76308  sqlite3_stmt *pStmt,
76309  int i,
76310  const char *zData,
76311  int nData,
76312  void (*xDel)(void*)
76313){
76314  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
76315}
76316SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
76317  sqlite3_stmt *pStmt,
76318  int i,
76319  const char *zData,
76320  sqlite3_uint64 nData,
76321  void (*xDel)(void*),
76322  unsigned char enc
76323){
76324  assert( xDel!=SQLITE_DYNAMIC );
76325  if( nData>0x7fffffff ){
76326    return invokeValueDestructor(zData, xDel, 0);
76327  }else{
76328    if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
76329    return bindText(pStmt, i, zData, (int)nData, xDel, enc);
76330  }
76331}
76332#ifndef SQLITE_OMIT_UTF16
76333SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
76334  sqlite3_stmt *pStmt,
76335  int i,
76336  const void *zData,
76337  int nData,
76338  void (*xDel)(void*)
76339){
76340  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
76341}
76342#endif /* SQLITE_OMIT_UTF16 */
76343SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
76344  int rc;
76345  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
76346    case SQLITE_INTEGER: {
76347      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
76348      break;
76349    }
76350    case SQLITE_FLOAT: {
76351      rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
76352      break;
76353    }
76354    case SQLITE_BLOB: {
76355      if( pValue->flags & MEM_Zero ){
76356        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
76357      }else{
76358        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
76359      }
76360      break;
76361    }
76362    case SQLITE_TEXT: {
76363      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
76364                              pValue->enc);
76365      break;
76366    }
76367    default: {
76368      rc = sqlite3_bind_null(pStmt, i);
76369      break;
76370    }
76371  }
76372  return rc;
76373}
76374SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
76375  int rc;
76376  Vdbe *p = (Vdbe *)pStmt;
76377  rc = vdbeUnbind(p, i);
76378  if( rc==SQLITE_OK ){
76379    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
76380    sqlite3_mutex_leave(p->db->mutex);
76381  }
76382  return rc;
76383}
76384SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
76385  int rc;
76386  Vdbe *p = (Vdbe *)pStmt;
76387  sqlite3_mutex_enter(p->db->mutex);
76388  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
76389    rc = SQLITE_TOOBIG;
76390  }else{
76391    assert( (n & 0x7FFFFFFF)==n );
76392    rc = sqlite3_bind_zeroblob(pStmt, i, n);
76393  }
76394  rc = sqlite3ApiExit(p->db, rc);
76395  sqlite3_mutex_leave(p->db->mutex);
76396  return rc;
76397}
76398
76399/*
76400** Return the number of wildcards that can be potentially bound to.
76401** This routine is added to support DBD::SQLite.
76402*/
76403SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
76404  Vdbe *p = (Vdbe*)pStmt;
76405  return p ? p->nVar : 0;
76406}
76407
76408/*
76409** Return the name of a wildcard parameter.  Return NULL if the index
76410** is out of range or if the wildcard is unnamed.
76411**
76412** The result is always UTF-8.
76413*/
76414SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
76415  Vdbe *p = (Vdbe*)pStmt;
76416  if( p==0 || i<1 || i>p->nzVar ){
76417    return 0;
76418  }
76419  return p->azVar[i-1];
76420}
76421
76422/*
76423** Given a wildcard parameter name, return the index of the variable
76424** with that name.  If there is no variable with the given name,
76425** return 0.
76426*/
76427SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
76428  int i;
76429  if( p==0 ){
76430    return 0;
76431  }
76432  if( zName ){
76433    for(i=0; i<p->nzVar; i++){
76434      const char *z = p->azVar[i];
76435      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
76436        return i+1;
76437      }
76438    }
76439  }
76440  return 0;
76441}
76442SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
76443  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
76444}
76445
76446/*
76447** Transfer all bindings from the first statement over to the second.
76448*/
76449SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76450  Vdbe *pFrom = (Vdbe*)pFromStmt;
76451  Vdbe *pTo = (Vdbe*)pToStmt;
76452  int i;
76453  assert( pTo->db==pFrom->db );
76454  assert( pTo->nVar==pFrom->nVar );
76455  sqlite3_mutex_enter(pTo->db->mutex);
76456  for(i=0; i<pFrom->nVar; i++){
76457    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
76458  }
76459  sqlite3_mutex_leave(pTo->db->mutex);
76460  return SQLITE_OK;
76461}
76462
76463#ifndef SQLITE_OMIT_DEPRECATED
76464/*
76465** Deprecated external interface.  Internal/core SQLite code
76466** should call sqlite3TransferBindings.
76467**
76468** It is misuse to call this routine with statements from different
76469** database connections.  But as this is a deprecated interface, we
76470** will not bother to check for that condition.
76471**
76472** If the two statements contain a different number of bindings, then
76473** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
76474** SQLITE_OK is returned.
76475*/
76476SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76477  Vdbe *pFrom = (Vdbe*)pFromStmt;
76478  Vdbe *pTo = (Vdbe*)pToStmt;
76479  if( pFrom->nVar!=pTo->nVar ){
76480    return SQLITE_ERROR;
76481  }
76482  if( pTo->isPrepareV2 && pTo->expmask ){
76483    pTo->expired = 1;
76484  }
76485  if( pFrom->isPrepareV2 && pFrom->expmask ){
76486    pFrom->expired = 1;
76487  }
76488  return sqlite3TransferBindings(pFromStmt, pToStmt);
76489}
76490#endif
76491
76492/*
76493** Return the sqlite3* database handle to which the prepared statement given
76494** in the argument belongs.  This is the same database handle that was
76495** the first argument to the sqlite3_prepare() that was used to create
76496** the statement in the first place.
76497*/
76498SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
76499  return pStmt ? ((Vdbe*)pStmt)->db : 0;
76500}
76501
76502/*
76503** Return true if the prepared statement is guaranteed to not modify the
76504** database.
76505*/
76506SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
76507  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
76508}
76509
76510/*
76511** Return true if the prepared statement is in need of being reset.
76512*/
76513SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
76514  Vdbe *v = (Vdbe*)pStmt;
76515  return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
76516}
76517
76518/*
76519** Return a pointer to the next prepared statement after pStmt associated
76520** with database connection pDb.  If pStmt is NULL, return the first
76521** prepared statement for the database connection.  Return NULL if there
76522** are no more.
76523*/
76524SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
76525  sqlite3_stmt *pNext;
76526#ifdef SQLITE_ENABLE_API_ARMOR
76527  if( !sqlite3SafetyCheckOk(pDb) ){
76528    (void)SQLITE_MISUSE_BKPT;
76529    return 0;
76530  }
76531#endif
76532  sqlite3_mutex_enter(pDb->mutex);
76533  if( pStmt==0 ){
76534    pNext = (sqlite3_stmt*)pDb->pVdbe;
76535  }else{
76536    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
76537  }
76538  sqlite3_mutex_leave(pDb->mutex);
76539  return pNext;
76540}
76541
76542/*
76543** Return the value of a status counter for a prepared statement
76544*/
76545SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
76546  Vdbe *pVdbe = (Vdbe*)pStmt;
76547  u32 v;
76548#ifdef SQLITE_ENABLE_API_ARMOR
76549  if( !pStmt ){
76550    (void)SQLITE_MISUSE_BKPT;
76551    return 0;
76552  }
76553#endif
76554  v = pVdbe->aCounter[op];
76555  if( resetFlag ) pVdbe->aCounter[op] = 0;
76556  return (int)v;
76557}
76558
76559/*
76560** Return the SQL associated with a prepared statement
76561*/
76562SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
76563  Vdbe *p = (Vdbe *)pStmt;
76564  return p ? p->zSql : 0;
76565}
76566
76567/*
76568** Return the SQL associated with a prepared statement with
76569** bound parameters expanded.  Space to hold the returned string is
76570** obtained from sqlite3_malloc().  The caller is responsible for
76571** freeing the returned string by passing it to sqlite3_free().
76572**
76573** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
76574** expanded bound parameters.
76575*/
76576SQLITE_API char *SQLITE_STDCALL sqlite3_expanded_sql(sqlite3_stmt *pStmt){
76577#ifdef SQLITE_OMIT_TRACE
76578  return 0;
76579#else
76580  char *z = 0;
76581  const char *zSql = sqlite3_sql(pStmt);
76582  if( zSql ){
76583    Vdbe *p = (Vdbe *)pStmt;
76584    sqlite3_mutex_enter(p->db->mutex);
76585    z = sqlite3VdbeExpandSql(p, zSql);
76586    sqlite3_mutex_leave(p->db->mutex);
76587  }
76588  return z;
76589#endif
76590}
76591
76592#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76593/*
76594** Allocate and populate an UnpackedRecord structure based on the serialized
76595** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76596** if successful, or a NULL pointer if an OOM error is encountered.
76597*/
76598static UnpackedRecord *vdbeUnpackRecord(
76599  KeyInfo *pKeyInfo,
76600  int nKey,
76601  const void *pKey
76602){
76603  char *dummy;                    /* Dummy argument for AllocUnpackedRecord() */
76604  UnpackedRecord *pRet;           /* Return value */
76605
76606  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76607  if( pRet ){
76608    memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76609    sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76610  }
76611  return pRet;
76612}
76613
76614/*
76615** This function is called from within a pre-update callback to retrieve
76616** a field of the row currently being updated or deleted.
76617*/
76618SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76619  PreUpdate *p = db->pPreUpdate;
76620  int rc = SQLITE_OK;
76621
76622  /* Test that this call is being made from within an SQLITE_DELETE or
76623  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76624  if( !p || p->op==SQLITE_INSERT ){
76625    rc = SQLITE_MISUSE_BKPT;
76626    goto preupdate_old_out;
76627  }
76628  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76629    rc = SQLITE_RANGE;
76630    goto preupdate_old_out;
76631  }
76632
76633  /* If the old.* record has not yet been loaded into memory, do so now. */
76634  if( p->pUnpacked==0 ){
76635    u32 nRec;
76636    u8 *aRec;
76637
76638    nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
76639    aRec = sqlite3DbMallocRaw(db, nRec);
76640    if( !aRec ) goto preupdate_old_out;
76641    rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76642    if( rc==SQLITE_OK ){
76643      p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76644      if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76645    }
76646    if( rc!=SQLITE_OK ){
76647      sqlite3DbFree(db, aRec);
76648      goto preupdate_old_out;
76649    }
76650    p->aRecord = aRec;
76651  }
76652
76653  if( iIdx>=p->pUnpacked->nField ){
76654    *ppValue = (sqlite3_value *)columnNullValue();
76655  }else{
76656    *ppValue = &p->pUnpacked->aMem[iIdx];
76657    if( iIdx==p->iPKey ){
76658      sqlite3VdbeMemSetInt64(*ppValue, p->iKey1);
76659    }
76660  }
76661
76662 preupdate_old_out:
76663  sqlite3Error(db, rc);
76664  return sqlite3ApiExit(db, rc);
76665}
76666#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76667
76668#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76669/*
76670** This function is called from within a pre-update callback to retrieve
76671** the number of columns in the row being updated, deleted or inserted.
76672*/
76673SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *db){
76674  PreUpdate *p = db->pPreUpdate;
76675  return (p ? p->keyinfo.nField : 0);
76676}
76677#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76678
76679#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76680/*
76681** This function is designed to be called from within a pre-update callback
76682** only. It returns zero if the change that caused the callback was made
76683** immediately by a user SQL statement. Or, if the change was made by a
76684** trigger program, it returns the number of trigger programs currently
76685** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76686** top-level trigger etc.).
76687**
76688** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76689** or SET DEFAULT action is considered a trigger.
76690*/
76691SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *db){
76692  PreUpdate *p = db->pPreUpdate;
76693  return (p ? p->v->nFrame : 0);
76694}
76695#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76696
76697#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76698/*
76699** This function is called from within a pre-update callback to retrieve
76700** a field of the row currently being updated or inserted.
76701*/
76702SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76703  PreUpdate *p = db->pPreUpdate;
76704  int rc = SQLITE_OK;
76705  Mem *pMem;
76706
76707  if( !p || p->op==SQLITE_DELETE ){
76708    rc = SQLITE_MISUSE_BKPT;
76709    goto preupdate_new_out;
76710  }
76711  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76712    rc = SQLITE_RANGE;
76713    goto preupdate_new_out;
76714  }
76715
76716  if( p->op==SQLITE_INSERT ){
76717    /* For an INSERT, memory cell p->iNewReg contains the serialized record
76718    ** that is being inserted. Deserialize it. */
76719    UnpackedRecord *pUnpack = p->pNewUnpacked;
76720    if( !pUnpack ){
76721      Mem *pData = &p->v->aMem[p->iNewReg];
76722      rc = sqlite3VdbeMemExpandBlob(pData);
76723      if( rc!=SQLITE_OK ) goto preupdate_new_out;
76724      pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76725      if( !pUnpack ){
76726        rc = SQLITE_NOMEM;
76727        goto preupdate_new_out;
76728      }
76729      p->pNewUnpacked = pUnpack;
76730    }
76731    if( iIdx>=pUnpack->nField ){
76732      pMem = (sqlite3_value *)columnNullValue();
76733    }else{
76734      pMem = &pUnpack->aMem[iIdx];
76735      if( iIdx==p->iPKey ){
76736        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76737      }
76738    }
76739  }else{
76740    /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76741    ** value. Make a copy of the cell contents and return a pointer to it.
76742    ** It is not safe to return a pointer to the memory cell itself as the
76743    ** caller may modify the value text encoding.
76744    */
76745    assert( p->op==SQLITE_UPDATE );
76746    if( !p->aNew ){
76747      p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76748      if( !p->aNew ){
76749        rc = SQLITE_NOMEM;
76750        goto preupdate_new_out;
76751      }
76752    }
76753    assert( iIdx>=0 && iIdx<p->pCsr->nField );
76754    pMem = &p->aNew[iIdx];
76755    if( pMem->flags==0 ){
76756      if( iIdx==p->iPKey ){
76757        sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76758      }else{
76759        rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76760        if( rc!=SQLITE_OK ) goto preupdate_new_out;
76761      }
76762    }
76763  }
76764  *ppValue = pMem;
76765
76766 preupdate_new_out:
76767  sqlite3Error(db, rc);
76768  return sqlite3ApiExit(db, rc);
76769}
76770#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76771
76772#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76773/*
76774** Return status data for a single loop within query pStmt.
76775*/
76776SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
76777  sqlite3_stmt *pStmt,            /* Prepared statement being queried */
76778  int idx,                        /* Index of loop to report on */
76779  int iScanStatusOp,              /* Which metric to return */
76780  void *pOut                      /* OUT: Write the answer here */
76781){
76782  Vdbe *p = (Vdbe*)pStmt;
76783  ScanStatus *pScan;
76784  if( idx<0 || idx>=p->nScan ) return 1;
76785  pScan = &p->aScan[idx];
76786  switch( iScanStatusOp ){
76787    case SQLITE_SCANSTAT_NLOOP: {
76788      *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
76789      break;
76790    }
76791    case SQLITE_SCANSTAT_NVISIT: {
76792      *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
76793      break;
76794    }
76795    case SQLITE_SCANSTAT_EST: {
76796      double r = 1.0;
76797      LogEst x = pScan->nEst;
76798      while( x<100 ){
76799        x += 10;
76800        r *= 0.5;
76801      }
76802      *(double*)pOut = r*sqlite3LogEstToInt(x);
76803      break;
76804    }
76805    case SQLITE_SCANSTAT_NAME: {
76806      *(const char**)pOut = pScan->zName;
76807      break;
76808    }
76809    case SQLITE_SCANSTAT_EXPLAIN: {
76810      if( pScan->addrExplain ){
76811        *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
76812      }else{
76813        *(const char**)pOut = 0;
76814      }
76815      break;
76816    }
76817    case SQLITE_SCANSTAT_SELECTID: {
76818      if( pScan->addrExplain ){
76819        *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
76820      }else{
76821        *(int*)pOut = -1;
76822      }
76823      break;
76824    }
76825    default: {
76826      return 1;
76827    }
76828  }
76829  return 0;
76830}
76831
76832/*
76833** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
76834*/
76835SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
76836  Vdbe *p = (Vdbe*)pStmt;
76837  memset(p->anExec, 0, p->nOp * sizeof(i64));
76838}
76839#endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
76840
76841/************** End of vdbeapi.c *********************************************/
76842/************** Begin file vdbetrace.c ***************************************/
76843/*
76844** 2009 November 25
76845**
76846** The author disclaims copyright to this source code.  In place of
76847** a legal notice, here is a blessing:
76848**
76849**    May you do good and not evil.
76850**    May you find forgiveness for yourself and forgive others.
76851**    May you share freely, never taking more than you give.
76852**
76853*************************************************************************
76854**
76855** This file contains code used to insert the values of host parameters
76856** (aka "wildcards") into the SQL text output by sqlite3_trace().
76857**
76858** The Vdbe parse-tree explainer is also found here.
76859*/
76860/* #include "sqliteInt.h" */
76861/* #include "vdbeInt.h" */
76862
76863#ifndef SQLITE_OMIT_TRACE
76864
76865/*
76866** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
76867** bytes in this text up to but excluding the first character in
76868** a host parameter.  If the text contains no host parameters, return
76869** the total number of bytes in the text.
76870*/
76871static int findNextHostParameter(const char *zSql, int *pnToken){
76872  int tokenType;
76873  int nTotal = 0;
76874  int n;
76875
76876  *pnToken = 0;
76877  while( zSql[0] ){
76878    n = sqlite3GetToken((u8*)zSql, &tokenType);
76879    assert( n>0 && tokenType!=TK_ILLEGAL );
76880    if( tokenType==TK_VARIABLE ){
76881      *pnToken = n;
76882      break;
76883    }
76884    nTotal += n;
76885    zSql += n;
76886  }
76887  return nTotal;
76888}
76889
76890/*
76891** This function returns a pointer to a nul-terminated string in memory
76892** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
76893** string contains a copy of zRawSql but with host parameters expanded to
76894** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
76895** then the returned string holds a copy of zRawSql with "-- " prepended
76896** to each line of text.
76897**
76898** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
76899** then long strings and blobs are truncated to that many bytes.  This
76900** can be used to prevent unreasonably large trace strings when dealing
76901** with large (multi-megabyte) strings and blobs.
76902**
76903** The calling function is responsible for making sure the memory returned
76904** is eventually freed.
76905**
76906** ALGORITHM:  Scan the input string looking for host parameters in any of
76907** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
76908** string literals, quoted identifier names, and comments.  For text forms,
76909** the host parameter index is found by scanning the prepared
76910** statement for the corresponding OP_Variable opcode.  Once the host
76911** parameter index is known, locate the value in p->aVar[].  Then render
76912** the value as a literal in place of the host parameter name.
76913*/
76914SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
76915  Vdbe *p,                 /* The prepared statement being evaluated */
76916  const char *zRawSql      /* Raw text of the SQL statement */
76917){
76918  sqlite3 *db;             /* The database connection */
76919  int idx = 0;             /* Index of a host parameter */
76920  int nextIndex = 1;       /* Index of next ? host parameter */
76921  int n;                   /* Length of a token prefix */
76922  int nToken;              /* Length of the parameter token */
76923  int i;                   /* Loop counter */
76924  Mem *pVar;               /* Value of a host parameter */
76925  StrAccum out;            /* Accumulate the output here */
76926#ifndef SQLITE_OMIT_UTF16
76927  Mem utf8;                /* Used to convert UTF16 parameters into UTF8 for display */
76928#endif
76929  char zBase[100];         /* Initial working space */
76930
76931  db = p->db;
76932  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
76933                      db->aLimit[SQLITE_LIMIT_LENGTH]);
76934  if( db->nVdbeExec>1 ){
76935    while( *zRawSql ){
76936      const char *zStart = zRawSql;
76937      while( *(zRawSql++)!='\n' && *zRawSql );
76938      sqlite3StrAccumAppend(&out, "-- ", 3);
76939      assert( (zRawSql - zStart) > 0 );
76940      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
76941    }
76942  }else if( p->nVar==0 ){
76943    sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
76944  }else{
76945    while( zRawSql[0] ){
76946      n = findNextHostParameter(zRawSql, &nToken);
76947      assert( n>0 );
76948      sqlite3StrAccumAppend(&out, zRawSql, n);
76949      zRawSql += n;
76950      assert( zRawSql[0] || nToken==0 );
76951      if( nToken==0 ) break;
76952      if( zRawSql[0]=='?' ){
76953        if( nToken>1 ){
76954          assert( sqlite3Isdigit(zRawSql[1]) );
76955          sqlite3GetInt32(&zRawSql[1], &idx);
76956        }else{
76957          idx = nextIndex;
76958        }
76959      }else{
76960        assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
76961                zRawSql[0]=='@' || zRawSql[0]=='#' );
76962        testcase( zRawSql[0]==':' );
76963        testcase( zRawSql[0]=='$' );
76964        testcase( zRawSql[0]=='@' );
76965        testcase( zRawSql[0]=='#' );
76966        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
76967        assert( idx>0 );
76968      }
76969      zRawSql += nToken;
76970      nextIndex = idx + 1;
76971      assert( idx>0 && idx<=p->nVar );
76972      pVar = &p->aVar[idx-1];
76973      if( pVar->flags & MEM_Null ){
76974        sqlite3StrAccumAppend(&out, "NULL", 4);
76975      }else if( pVar->flags & MEM_Int ){
76976        sqlite3XPrintf(&out, "%lld", pVar->u.i);
76977      }else if( pVar->flags & MEM_Real ){
76978        sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
76979      }else if( pVar->flags & MEM_Str ){
76980        int nOut;  /* Number of bytes of the string text to include in output */
76981#ifndef SQLITE_OMIT_UTF16
76982        u8 enc = ENC(db);
76983        if( enc!=SQLITE_UTF8 ){
76984          memset(&utf8, 0, sizeof(utf8));
76985          utf8.db = db;
76986          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
76987          if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
76988            out.accError = STRACCUM_NOMEM;
76989            out.nAlloc = 0;
76990          }
76991          pVar = &utf8;
76992        }
76993#endif
76994        nOut = pVar->n;
76995#ifdef SQLITE_TRACE_SIZE_LIMIT
76996        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
76997          nOut = SQLITE_TRACE_SIZE_LIMIT;
76998          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
76999        }
77000#endif
77001        sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
77002#ifdef SQLITE_TRACE_SIZE_LIMIT
77003        if( nOut<pVar->n ){
77004          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77005        }
77006#endif
77007#ifndef SQLITE_OMIT_UTF16
77008        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
77009#endif
77010      }else if( pVar->flags & MEM_Zero ){
77011        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
77012      }else{
77013        int nOut;  /* Number of bytes of the blob to include in output */
77014        assert( pVar->flags & MEM_Blob );
77015        sqlite3StrAccumAppend(&out, "x'", 2);
77016        nOut = pVar->n;
77017#ifdef SQLITE_TRACE_SIZE_LIMIT
77018        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
77019#endif
77020        for(i=0; i<nOut; i++){
77021          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
77022        }
77023        sqlite3StrAccumAppend(&out, "'", 1);
77024#ifdef SQLITE_TRACE_SIZE_LIMIT
77025        if( nOut<pVar->n ){
77026          sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77027        }
77028#endif
77029      }
77030    }
77031  }
77032  if( out.accError ) sqlite3StrAccumReset(&out);
77033  return sqlite3StrAccumFinish(&out);
77034}
77035
77036#endif /* #ifndef SQLITE_OMIT_TRACE */
77037
77038/************** End of vdbetrace.c *******************************************/
77039/************** Begin file vdbe.c ********************************************/
77040/*
77041** 2001 September 15
77042**
77043** The author disclaims copyright to this source code.  In place of
77044** a legal notice, here is a blessing:
77045**
77046**    May you do good and not evil.
77047**    May you find forgiveness for yourself and forgive others.
77048**    May you share freely, never taking more than you give.
77049**
77050*************************************************************************
77051** The code in this file implements the function that runs the
77052** bytecode of a prepared statement.
77053**
77054** Various scripts scan this source file in order to generate HTML
77055** documentation, headers files, or other derived files.  The formatting
77056** of the code in this file is, therefore, important.  See other comments
77057** in this file for details.  If in doubt, do not deviate from existing
77058** commenting and indentation practices when changing or adding code.
77059*/
77060/* #include "sqliteInt.h" */
77061/* #include "vdbeInt.h" */
77062
77063/*
77064** Invoke this macro on memory cells just prior to changing the
77065** value of the cell.  This macro verifies that shallow copies are
77066** not misused.  A shallow copy of a string or blob just copies a
77067** pointer to the string or blob, not the content.  If the original
77068** is changed while the copy is still in use, the string or blob might
77069** be changed out from under the copy.  This macro verifies that nothing
77070** like that ever happens.
77071*/
77072#ifdef SQLITE_DEBUG
77073# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
77074#else
77075# define memAboutToChange(P,M)
77076#endif
77077
77078/*
77079** The following global variable is incremented every time a cursor
77080** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
77081** procedures use this information to make sure that indices are
77082** working correctly.  This variable has no function other than to
77083** help verify the correct operation of the library.
77084*/
77085#ifdef SQLITE_TEST
77086SQLITE_API int sqlite3_search_count = 0;
77087#endif
77088
77089/*
77090** When this global variable is positive, it gets decremented once before
77091** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
77092** field of the sqlite3 structure is set in order to simulate an interrupt.
77093**
77094** This facility is used for testing purposes only.  It does not function
77095** in an ordinary build.
77096*/
77097#ifdef SQLITE_TEST
77098SQLITE_API int sqlite3_interrupt_count = 0;
77099#endif
77100
77101/*
77102** The next global variable is incremented each type the OP_Sort opcode
77103** is executed.  The test procedures use this information to make sure that
77104** sorting is occurring or not occurring at appropriate times.   This variable
77105** has no function other than to help verify the correct operation of the
77106** library.
77107*/
77108#ifdef SQLITE_TEST
77109SQLITE_API int sqlite3_sort_count = 0;
77110#endif
77111
77112/*
77113** The next global variable records the size of the largest MEM_Blob
77114** or MEM_Str that has been used by a VDBE opcode.  The test procedures
77115** use this information to make sure that the zero-blob functionality
77116** is working correctly.   This variable has no function other than to
77117** help verify the correct operation of the library.
77118*/
77119#ifdef SQLITE_TEST
77120SQLITE_API int sqlite3_max_blobsize = 0;
77121static void updateMaxBlobsize(Mem *p){
77122  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
77123    sqlite3_max_blobsize = p->n;
77124  }
77125}
77126#endif
77127
77128/*
77129** This macro evaluates to true if either the update hook or the preupdate
77130** hook are enabled for database connect DB.
77131*/
77132#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77133# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
77134#else
77135# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
77136#endif
77137
77138/*
77139** The next global variable is incremented each time the OP_Found opcode
77140** is executed. This is used to test whether or not the foreign key
77141** operation implemented using OP_FkIsZero is working. This variable
77142** has no function other than to help verify the correct operation of the
77143** library.
77144*/
77145#ifdef SQLITE_TEST
77146SQLITE_API int sqlite3_found_count = 0;
77147#endif
77148
77149/*
77150** Test a register to see if it exceeds the current maximum blob size.
77151** If it does, record the new maximum blob size.
77152*/
77153#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
77154# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
77155#else
77156# define UPDATE_MAX_BLOBSIZE(P)
77157#endif
77158
77159/*
77160** Invoke the VDBE coverage callback, if that callback is defined.  This
77161** feature is used for test suite validation only and does not appear an
77162** production builds.
77163**
77164** M is an integer, 2 or 3, that indices how many different ways the
77165** branch can go.  It is usually 2.  "I" is the direction the branch
77166** goes.  0 means falls through.  1 means branch is taken.  2 means the
77167** second alternative branch is taken.
77168**
77169** iSrcLine is the source code line (from the __LINE__ macro) that
77170** generated the VDBE instruction.  This instrumentation assumes that all
77171** source code is in a single file (the amalgamation).  Special values 1
77172** and 2 for the iSrcLine parameter mean that this particular branch is
77173** always taken or never taken, respectively.
77174*/
77175#if !defined(SQLITE_VDBE_COVERAGE)
77176# define VdbeBranchTaken(I,M)
77177#else
77178# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
77179  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
77180    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
77181      M = iSrcLine;
77182      /* Assert the truth of VdbeCoverageAlwaysTaken() and
77183      ** VdbeCoverageNeverTaken() */
77184      assert( (M & I)==I );
77185    }else{
77186      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
77187      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
77188                                      iSrcLine,I,M);
77189    }
77190  }
77191#endif
77192
77193/*
77194** Convert the given register into a string if it isn't one
77195** already. Return non-zero if a malloc() fails.
77196*/
77197#define Stringify(P, enc) \
77198   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
77199     { goto no_mem; }
77200
77201/*
77202** An ephemeral string value (signified by the MEM_Ephem flag) contains
77203** a pointer to a dynamically allocated string where some other entity
77204** is responsible for deallocating that string.  Because the register
77205** does not control the string, it might be deleted without the register
77206** knowing it.
77207**
77208** This routine converts an ephemeral string into a dynamically allocated
77209** string that the register itself controls.  In other words, it
77210** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
77211*/
77212#define Deephemeralize(P) \
77213   if( ((P)->flags&MEM_Ephem)!=0 \
77214       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
77215
77216/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
77217#define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
77218
77219/*
77220** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
77221** if we run out of memory.
77222*/
77223static VdbeCursor *allocateCursor(
77224  Vdbe *p,              /* The virtual machine */
77225  int iCur,             /* Index of the new VdbeCursor */
77226  int nField,           /* Number of fields in the table or index */
77227  int iDb,              /* Database the cursor belongs to, or -1 */
77228  u8 eCurType           /* Type of the new cursor */
77229){
77230  /* Find the memory cell that will be used to store the blob of memory
77231  ** required for this VdbeCursor structure. It is convenient to use a
77232  ** vdbe memory cell to manage the memory allocation required for a
77233  ** VdbeCursor structure for the following reasons:
77234  **
77235  **   * Sometimes cursor numbers are used for a couple of different
77236  **     purposes in a vdbe program. The different uses might require
77237  **     different sized allocations. Memory cells provide growable
77238  **     allocations.
77239  **
77240  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
77241  **     be freed lazily via the sqlite3_release_memory() API. This
77242  **     minimizes the number of malloc calls made by the system.
77243  **
77244  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
77245  ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
77246  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
77247  */
77248  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
77249
77250  int nByte;
77251  VdbeCursor *pCx = 0;
77252  nByte =
77253      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
77254      (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
77255
77256  assert( iCur>=0 && iCur<p->nCursor );
77257  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
77258    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
77259    p->apCsr[iCur] = 0;
77260  }
77261  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
77262    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
77263    memset(pCx, 0, sizeof(VdbeCursor));
77264    pCx->eCurType = eCurType;
77265    pCx->iDb = iDb;
77266    pCx->nField = nField;
77267    pCx->aOffset = &pCx->aType[nField];
77268    if( eCurType==CURTYPE_BTREE ){
77269      pCx->uc.pCursor = (BtCursor*)
77270          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
77271      sqlite3BtreeCursorZero(pCx->uc.pCursor);
77272    }
77273  }
77274  return pCx;
77275}
77276
77277/*
77278** Try to convert a value into a numeric representation if we can
77279** do so without loss of information.  In other words, if the string
77280** looks like a number, convert it into a number.  If it does not
77281** look like a number, leave it alone.
77282**
77283** If the bTryForInt flag is true, then extra effort is made to give
77284** an integer representation.  Strings that look like floating point
77285** values but which have no fractional component (example: '48.00')
77286** will have a MEM_Int representation when bTryForInt is true.
77287**
77288** If bTryForInt is false, then if the input string contains a decimal
77289** point or exponential notation, the result is only MEM_Real, even
77290** if there is an exact integer representation of the quantity.
77291*/
77292static void applyNumericAffinity(Mem *pRec, int bTryForInt){
77293  double rValue;
77294  i64 iValue;
77295  u8 enc = pRec->enc;
77296  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
77297  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
77298  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
77299    pRec->u.i = iValue;
77300    pRec->flags |= MEM_Int;
77301  }else{
77302    pRec->u.r = rValue;
77303    pRec->flags |= MEM_Real;
77304    if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
77305  }
77306}
77307
77308/*
77309** Processing is determine by the affinity parameter:
77310**
77311** SQLITE_AFF_INTEGER:
77312** SQLITE_AFF_REAL:
77313** SQLITE_AFF_NUMERIC:
77314**    Try to convert pRec to an integer representation or a
77315**    floating-point representation if an integer representation
77316**    is not possible.  Note that the integer representation is
77317**    always preferred, even if the affinity is REAL, because
77318**    an integer representation is more space efficient on disk.
77319**
77320** SQLITE_AFF_TEXT:
77321**    Convert pRec to a text representation.
77322**
77323** SQLITE_AFF_BLOB:
77324**    No-op.  pRec is unchanged.
77325*/
77326static void applyAffinity(
77327  Mem *pRec,          /* The value to apply affinity to */
77328  char affinity,      /* The affinity to be applied */
77329  u8 enc              /* Use this text encoding */
77330){
77331  if( affinity>=SQLITE_AFF_NUMERIC ){
77332    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
77333             || affinity==SQLITE_AFF_NUMERIC );
77334    if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
77335      if( (pRec->flags & MEM_Real)==0 ){
77336        if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
77337      }else{
77338        sqlite3VdbeIntegerAffinity(pRec);
77339      }
77340    }
77341  }else if( affinity==SQLITE_AFF_TEXT ){
77342    /* Only attempt the conversion to TEXT if there is an integer or real
77343    ** representation (blob and NULL do not get converted) but no string
77344    ** representation.  It would be harmless to repeat the conversion if
77345    ** there is already a string rep, but it is pointless to waste those
77346    ** CPU cycles. */
77347    if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
77348      if( (pRec->flags&(MEM_Real|MEM_Int)) ){
77349        sqlite3VdbeMemStringify(pRec, enc, 1);
77350      }
77351    }
77352    pRec->flags &= ~(MEM_Real|MEM_Int);
77353  }
77354}
77355
77356/*
77357** Try to convert the type of a function argument or a result column
77358** into a numeric representation.  Use either INTEGER or REAL whichever
77359** is appropriate.  But only do the conversion if it is possible without
77360** loss of information and return the revised type of the argument.
77361*/
77362SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
77363  int eType = sqlite3_value_type(pVal);
77364  if( eType==SQLITE_TEXT ){
77365    Mem *pMem = (Mem*)pVal;
77366    applyNumericAffinity(pMem, 0);
77367    eType = sqlite3_value_type(pVal);
77368  }
77369  return eType;
77370}
77371
77372/*
77373** Exported version of applyAffinity(). This one works on sqlite3_value*,
77374** not the internal Mem* type.
77375*/
77376SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
77377  sqlite3_value *pVal,
77378  u8 affinity,
77379  u8 enc
77380){
77381  applyAffinity((Mem *)pVal, affinity, enc);
77382}
77383
77384/*
77385** pMem currently only holds a string type (or maybe a BLOB that we can
77386** interpret as a string if we want to).  Compute its corresponding
77387** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
77388** accordingly.
77389*/
77390static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
77391  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
77392  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
77393  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
77394    return 0;
77395  }
77396  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
77397    return MEM_Int;
77398  }
77399  return MEM_Real;
77400}
77401
77402/*
77403** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
77404** none.
77405**
77406** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
77407** But it does set pMem->u.r and pMem->u.i appropriately.
77408*/
77409static u16 numericType(Mem *pMem){
77410  if( pMem->flags & (MEM_Int|MEM_Real) ){
77411    return pMem->flags & (MEM_Int|MEM_Real);
77412  }
77413  if( pMem->flags & (MEM_Str|MEM_Blob) ){
77414    return computeNumericType(pMem);
77415  }
77416  return 0;
77417}
77418
77419#ifdef SQLITE_DEBUG
77420/*
77421** Write a nice string representation of the contents of cell pMem
77422** into buffer zBuf, length nBuf.
77423*/
77424SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
77425  char *zCsr = zBuf;
77426  int f = pMem->flags;
77427
77428  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
77429
77430  if( f&MEM_Blob ){
77431    int i;
77432    char c;
77433    if( f & MEM_Dyn ){
77434      c = 'z';
77435      assert( (f & (MEM_Static|MEM_Ephem))==0 );
77436    }else if( f & MEM_Static ){
77437      c = 't';
77438      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77439    }else if( f & MEM_Ephem ){
77440      c = 'e';
77441      assert( (f & (MEM_Static|MEM_Dyn))==0 );
77442    }else{
77443      c = 's';
77444    }
77445
77446    sqlite3_snprintf(100, zCsr, "%c", c);
77447    zCsr += sqlite3Strlen30(zCsr);
77448    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
77449    zCsr += sqlite3Strlen30(zCsr);
77450    for(i=0; i<16 && i<pMem->n; i++){
77451      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
77452      zCsr += sqlite3Strlen30(zCsr);
77453    }
77454    for(i=0; i<16 && i<pMem->n; i++){
77455      char z = pMem->z[i];
77456      if( z<32 || z>126 ) *zCsr++ = '.';
77457      else *zCsr++ = z;
77458    }
77459
77460    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
77461    zCsr += sqlite3Strlen30(zCsr);
77462    if( f & MEM_Zero ){
77463      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
77464      zCsr += sqlite3Strlen30(zCsr);
77465    }
77466    *zCsr = '\0';
77467  }else if( f & MEM_Str ){
77468    int j, k;
77469    zBuf[0] = ' ';
77470    if( f & MEM_Dyn ){
77471      zBuf[1] = 'z';
77472      assert( (f & (MEM_Static|MEM_Ephem))==0 );
77473    }else if( f & MEM_Static ){
77474      zBuf[1] = 't';
77475      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77476    }else if( f & MEM_Ephem ){
77477      zBuf[1] = 'e';
77478      assert( (f & (MEM_Static|MEM_Dyn))==0 );
77479    }else{
77480      zBuf[1] = 's';
77481    }
77482    k = 2;
77483    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
77484    k += sqlite3Strlen30(&zBuf[k]);
77485    zBuf[k++] = '[';
77486    for(j=0; j<15 && j<pMem->n; j++){
77487      u8 c = pMem->z[j];
77488      if( c>=0x20 && c<0x7f ){
77489        zBuf[k++] = c;
77490      }else{
77491        zBuf[k++] = '.';
77492      }
77493    }
77494    zBuf[k++] = ']';
77495    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
77496    k += sqlite3Strlen30(&zBuf[k]);
77497    zBuf[k++] = 0;
77498  }
77499}
77500#endif
77501
77502#ifdef SQLITE_DEBUG
77503/*
77504** Print the value of a register for tracing purposes:
77505*/
77506static void memTracePrint(Mem *p){
77507  if( p->flags & MEM_Undefined ){
77508    printf(" undefined");
77509  }else if( p->flags & MEM_Null ){
77510    printf(" NULL");
77511  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
77512    printf(" si:%lld", p->u.i);
77513  }else if( p->flags & MEM_Int ){
77514    printf(" i:%lld", p->u.i);
77515#ifndef SQLITE_OMIT_FLOATING_POINT
77516  }else if( p->flags & MEM_Real ){
77517    printf(" r:%g", p->u.r);
77518#endif
77519  }else if( p->flags & MEM_RowSet ){
77520    printf(" (rowset)");
77521  }else{
77522    char zBuf[200];
77523    sqlite3VdbeMemPrettyPrint(p, zBuf);
77524    printf(" %s", zBuf);
77525  }
77526  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
77527}
77528static void registerTrace(int iReg, Mem *p){
77529  printf("REG[%d] = ", iReg);
77530  memTracePrint(p);
77531  printf("\n");
77532}
77533#endif
77534
77535#ifdef SQLITE_DEBUG
77536#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
77537#else
77538#  define REGISTER_TRACE(R,M)
77539#endif
77540
77541
77542#ifdef VDBE_PROFILE
77543
77544/*
77545** hwtime.h contains inline assembler code for implementing
77546** high-performance timing routines.
77547*/
77548/************** Include hwtime.h in the middle of vdbe.c *********************/
77549/************** Begin file hwtime.h ******************************************/
77550/*
77551** 2008 May 27
77552**
77553** The author disclaims copyright to this source code.  In place of
77554** a legal notice, here is a blessing:
77555**
77556**    May you do good and not evil.
77557**    May you find forgiveness for yourself and forgive others.
77558**    May you share freely, never taking more than you give.
77559**
77560******************************************************************************
77561**
77562** This file contains inline asm code for retrieving "high-performance"
77563** counters for x86 class CPUs.
77564*/
77565#ifndef SQLITE_HWTIME_H
77566#define SQLITE_HWTIME_H
77567
77568/*
77569** The following routine only works on pentium-class (or newer) processors.
77570** It uses the RDTSC opcode to read the cycle count value out of the
77571** processor and returns that value.  This can be used for high-res
77572** profiling.
77573*/
77574#if (defined(__GNUC__) || defined(_MSC_VER)) && \
77575      (defined(i386) || defined(__i386__) || defined(_M_IX86))
77576
77577  #if defined(__GNUC__)
77578
77579  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77580     unsigned int lo, hi;
77581     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
77582     return (sqlite_uint64)hi << 32 | lo;
77583  }
77584
77585  #elif defined(_MSC_VER)
77586
77587  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
77588     __asm {
77589        rdtsc
77590        ret       ; return value at EDX:EAX
77591     }
77592  }
77593
77594  #endif
77595
77596#elif (defined(__GNUC__) && defined(__x86_64__))
77597
77598  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77599      unsigned long val;
77600      __asm__ __volatile__ ("rdtsc" : "=A" (val));
77601      return val;
77602  }
77603
77604#elif (defined(__GNUC__) && defined(__ppc__))
77605
77606  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77607      unsigned long long retval;
77608      unsigned long junk;
77609      __asm__ __volatile__ ("\n\
77610          1:      mftbu   %1\n\
77611                  mftb    %L0\n\
77612                  mftbu   %0\n\
77613                  cmpw    %0,%1\n\
77614                  bne     1b"
77615                  : "=r" (retval), "=r" (junk));
77616      return retval;
77617  }
77618
77619#else
77620
77621  #error Need implementation of sqlite3Hwtime() for your platform.
77622
77623  /*
77624  ** To compile without implementing sqlite3Hwtime() for your platform,
77625  ** you can remove the above #error and use the following
77626  ** stub function.  You will lose timing support for many
77627  ** of the debugging and testing utilities, but it should at
77628  ** least compile and run.
77629  */
77630SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
77631
77632#endif
77633
77634#endif /* !defined(SQLITE_HWTIME_H) */
77635
77636/************** End of hwtime.h **********************************************/
77637/************** Continuing where we left off in vdbe.c ***********************/
77638
77639#endif
77640
77641#ifndef NDEBUG
77642/*
77643** This function is only called from within an assert() expression. It
77644** checks that the sqlite3.nTransaction variable is correctly set to
77645** the number of non-transaction savepoints currently in the
77646** linked list starting at sqlite3.pSavepoint.
77647**
77648** Usage:
77649**
77650**     assert( checkSavepointCount(db) );
77651*/
77652static int checkSavepointCount(sqlite3 *db){
77653  int n = 0;
77654  Savepoint *p;
77655  for(p=db->pSavepoint; p; p=p->pNext) n++;
77656  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
77657  return 1;
77658}
77659#endif
77660
77661/*
77662** Return the register of pOp->p2 after first preparing it to be
77663** overwritten with an integer value.
77664*/
77665static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
77666  sqlite3VdbeMemSetNull(pOut);
77667  pOut->flags = MEM_Int;
77668  return pOut;
77669}
77670static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
77671  Mem *pOut;
77672  assert( pOp->p2>0 );
77673  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77674  pOut = &p->aMem[pOp->p2];
77675  memAboutToChange(p, pOut);
77676  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77677    return out2PrereleaseWithClear(pOut);
77678  }else{
77679    pOut->flags = MEM_Int;
77680    return pOut;
77681  }
77682}
77683
77684
77685/*
77686** Execute as much of a VDBE program as we can.
77687** This is the core of sqlite3_step().
77688*/
77689SQLITE_PRIVATE int sqlite3VdbeExec(
77690  Vdbe *p                    /* The VDBE */
77691){
77692  Op *aOp = p->aOp;          /* Copy of p->aOp */
77693  Op *pOp = aOp;             /* Current operation */
77694#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77695  Op *pOrigOp;               /* Value of pOp at the top of the loop */
77696#endif
77697#ifdef SQLITE_DEBUG
77698  int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
77699#endif
77700  int rc = SQLITE_OK;        /* Value to return */
77701  sqlite3 *db = p->db;       /* The database */
77702  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
77703  u8 encoding = ENC(db);     /* The database encoding */
77704  int iCompare = 0;          /* Result of last OP_Compare operation */
77705  unsigned nVmStep = 0;      /* Number of virtual machine steps */
77706#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77707  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
77708#endif
77709  Mem *aMem = p->aMem;       /* Copy of p->aMem */
77710  Mem *pIn1 = 0;             /* 1st input operand */
77711  Mem *pIn2 = 0;             /* 2nd input operand */
77712  Mem *pIn3 = 0;             /* 3rd input operand */
77713  Mem *pOut = 0;             /* Output operand */
77714  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
77715  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
77716#ifdef VDBE_PROFILE
77717  u64 start;                 /* CPU clock count at start of opcode */
77718#endif
77719  /*** INSERT STACK UNION HERE ***/
77720
77721  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
77722  sqlite3VdbeEnter(p);
77723  if( p->rc==SQLITE_NOMEM ){
77724    /* This happens if a malloc() inside a call to sqlite3_column_text() or
77725    ** sqlite3_column_text16() failed.  */
77726    goto no_mem;
77727  }
77728  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
77729  assert( p->bIsReader || p->readOnly!=0 );
77730  p->rc = SQLITE_OK;
77731  p->iCurrentTime = 0;
77732  assert( p->explain==0 );
77733  p->pResultSet = 0;
77734  db->busyHandler.nBusy = 0;
77735  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77736  sqlite3VdbeIOTraceSql(p);
77737#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77738  if( db->xProgress ){
77739    u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
77740    assert( 0 < db->nProgressOps );
77741    nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
77742  }
77743#endif
77744#ifdef SQLITE_DEBUG
77745  sqlite3BeginBenignMalloc();
77746  if( p->pc==0
77747   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
77748  ){
77749    int i;
77750    int once = 1;
77751    sqlite3VdbePrintSql(p);
77752    if( p->db->flags & SQLITE_VdbeListing ){
77753      printf("VDBE Program Listing:\n");
77754      for(i=0; i<p->nOp; i++){
77755        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
77756      }
77757    }
77758    if( p->db->flags & SQLITE_VdbeEQP ){
77759      for(i=0; i<p->nOp; i++){
77760        if( aOp[i].opcode==OP_Explain ){
77761          if( once ) printf("VDBE Query Plan:\n");
77762          printf("%s\n", aOp[i].p4.z);
77763          once = 0;
77764        }
77765      }
77766    }
77767    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
77768  }
77769  sqlite3EndBenignMalloc();
77770#endif
77771  for(pOp=&aOp[p->pc]; 1; pOp++){
77772    /* Errors are detected by individual opcodes, with an immediate
77773    ** jumps to abort_due_to_error. */
77774    assert( rc==SQLITE_OK );
77775
77776    assert( pOp>=aOp && pOp<&aOp[p->nOp]);
77777#ifdef VDBE_PROFILE
77778    start = sqlite3Hwtime();
77779#endif
77780    nVmStep++;
77781#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77782    if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
77783#endif
77784
77785    /* Only allow tracing if SQLITE_DEBUG is defined.
77786    */
77787#ifdef SQLITE_DEBUG
77788    if( db->flags & SQLITE_VdbeTrace ){
77789      sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
77790    }
77791#endif
77792
77793
77794    /* Check to see if we need to simulate an interrupt.  This only happens
77795    ** if we have a special test build.
77796    */
77797#ifdef SQLITE_TEST
77798    if( sqlite3_interrupt_count>0 ){
77799      sqlite3_interrupt_count--;
77800      if( sqlite3_interrupt_count==0 ){
77801        sqlite3_interrupt(db);
77802      }
77803    }
77804#endif
77805
77806    /* Sanity checking on other operands */
77807#ifdef SQLITE_DEBUG
77808    {
77809      u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77810      if( (opProperty & OPFLG_IN1)!=0 ){
77811        assert( pOp->p1>0 );
77812        assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77813        assert( memIsValid(&aMem[pOp->p1]) );
77814        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77815        REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77816      }
77817      if( (opProperty & OPFLG_IN2)!=0 ){
77818        assert( pOp->p2>0 );
77819        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77820        assert( memIsValid(&aMem[pOp->p2]) );
77821        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
77822        REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
77823      }
77824      if( (opProperty & OPFLG_IN3)!=0 ){
77825        assert( pOp->p3>0 );
77826        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77827        assert( memIsValid(&aMem[pOp->p3]) );
77828        assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
77829        REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
77830      }
77831      if( (opProperty & OPFLG_OUT2)!=0 ){
77832        assert( pOp->p2>0 );
77833        assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77834        memAboutToChange(p, &aMem[pOp->p2]);
77835      }
77836      if( (opProperty & OPFLG_OUT3)!=0 ){
77837        assert( pOp->p3>0 );
77838        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77839        memAboutToChange(p, &aMem[pOp->p3]);
77840      }
77841    }
77842#endif
77843#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77844    pOrigOp = pOp;
77845#endif
77846
77847    switch( pOp->opcode ){
77848
77849/*****************************************************************************
77850** What follows is a massive switch statement where each case implements a
77851** separate instruction in the virtual machine.  If we follow the usual
77852** indentation conventions, each case should be indented by 6 spaces.  But
77853** that is a lot of wasted space on the left margin.  So the code within
77854** the switch statement will break with convention and be flush-left. Another
77855** big comment (similar to this one) will mark the point in the code where
77856** we transition back to normal indentation.
77857**
77858** The formatting of each case is important.  The makefile for SQLite
77859** generates two C files "opcodes.h" and "opcodes.c" by scanning this
77860** file looking for lines that begin with "case OP_".  The opcodes.h files
77861** will be filled with #defines that give unique integer values to each
77862** opcode and the opcodes.c file is filled with an array of strings where
77863** each string is the symbolic name for the corresponding opcode.  If the
77864** case statement is followed by a comment of the form "/# same as ... #/"
77865** that comment is used to determine the particular value of the opcode.
77866**
77867** Other keywords in the comment that follows each case are used to
77868** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
77869** Keywords include: in1, in2, in3, out2, out3.  See
77870** the mkopcodeh.awk script for additional information.
77871**
77872** Documentation about VDBE opcodes is generated by scanning this file
77873** for lines of that contain "Opcode:".  That line and all subsequent
77874** comment lines are used in the generation of the opcode.html documentation
77875** file.
77876**
77877** SUMMARY:
77878**
77879**     Formatting is important to scripts that scan this file.
77880**     Do not deviate from the formatting style currently in use.
77881**
77882*****************************************************************************/
77883
77884/* Opcode:  Goto * P2 * * *
77885**
77886** An unconditional jump to address P2.
77887** The next instruction executed will be
77888** the one at index P2 from the beginning of
77889** the program.
77890**
77891** The P1 parameter is not actually used by this opcode.  However, it
77892** is sometimes set to 1 instead of 0 as a hint to the command-line shell
77893** that this Goto is the bottom of a loop and that the lines from P2 down
77894** to the current line should be indented for EXPLAIN output.
77895*/
77896case OP_Goto: {             /* jump */
77897jump_to_p2_and_check_for_interrupt:
77898  pOp = &aOp[pOp->p2 - 1];
77899
77900  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
77901  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
77902  ** completion.  Check to see if sqlite3_interrupt() has been called
77903  ** or if the progress callback needs to be invoked.
77904  **
77905  ** This code uses unstructured "goto" statements and does not look clean.
77906  ** But that is not due to sloppy coding habits. The code is written this
77907  ** way for performance, to avoid having to run the interrupt and progress
77908  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
77909  ** faster according to "valgrind --tool=cachegrind" */
77910check_for_interrupt:
77911  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77912#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77913  /* Call the progress callback if it is configured and the required number
77914  ** of VDBE ops have been executed (either since this invocation of
77915  ** sqlite3VdbeExec() or since last time the progress callback was called).
77916  ** If the progress callback returns non-zero, exit the virtual machine with
77917  ** a return code SQLITE_ABORT.
77918  */
77919  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
77920    assert( db->nProgressOps!=0 );
77921    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
77922    if( db->xProgress(db->pProgressArg) ){
77923      rc = SQLITE_INTERRUPT;
77924      goto abort_due_to_error;
77925    }
77926  }
77927#endif
77928
77929  break;
77930}
77931
77932/* Opcode:  Gosub P1 P2 * * *
77933**
77934** Write the current address onto register P1
77935** and then jump to address P2.
77936*/
77937case OP_Gosub: {            /* jump */
77938  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
77939  pIn1 = &aMem[pOp->p1];
77940  assert( VdbeMemDynamic(pIn1)==0 );
77941  memAboutToChange(p, pIn1);
77942  pIn1->flags = MEM_Int;
77943  pIn1->u.i = (int)(pOp-aOp);
77944  REGISTER_TRACE(pOp->p1, pIn1);
77945
77946  /* Most jump operations do a goto to this spot in order to update
77947  ** the pOp pointer. */
77948jump_to_p2:
77949  pOp = &aOp[pOp->p2 - 1];
77950  break;
77951}
77952
77953/* Opcode:  Return P1 * * * *
77954**
77955** Jump to the next instruction after the address in register P1.  After
77956** the jump, register P1 becomes undefined.
77957*/
77958case OP_Return: {           /* in1 */
77959  pIn1 = &aMem[pOp->p1];
77960  assert( pIn1->flags==MEM_Int );
77961  pOp = &aOp[pIn1->u.i];
77962  pIn1->flags = MEM_Undefined;
77963  break;
77964}
77965
77966/* Opcode: InitCoroutine P1 P2 P3 * *
77967**
77968** Set up register P1 so that it will Yield to the coroutine
77969** located at address P3.
77970**
77971** If P2!=0 then the coroutine implementation immediately follows
77972** this opcode.  So jump over the coroutine implementation to
77973** address P2.
77974**
77975** See also: EndCoroutine
77976*/
77977case OP_InitCoroutine: {     /* jump */
77978  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
77979  assert( pOp->p2>=0 && pOp->p2<p->nOp );
77980  assert( pOp->p3>=0 && pOp->p3<p->nOp );
77981  pOut = &aMem[pOp->p1];
77982  assert( !VdbeMemDynamic(pOut) );
77983  pOut->u.i = pOp->p3 - 1;
77984  pOut->flags = MEM_Int;
77985  if( pOp->p2 ) goto jump_to_p2;
77986  break;
77987}
77988
77989/* Opcode:  EndCoroutine P1 * * * *
77990**
77991** The instruction at the address in register P1 is a Yield.
77992** Jump to the P2 parameter of that Yield.
77993** After the jump, register P1 becomes undefined.
77994**
77995** See also: InitCoroutine
77996*/
77997case OP_EndCoroutine: {           /* in1 */
77998  VdbeOp *pCaller;
77999  pIn1 = &aMem[pOp->p1];
78000  assert( pIn1->flags==MEM_Int );
78001  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
78002  pCaller = &aOp[pIn1->u.i];
78003  assert( pCaller->opcode==OP_Yield );
78004  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
78005  pOp = &aOp[pCaller->p2 - 1];
78006  pIn1->flags = MEM_Undefined;
78007  break;
78008}
78009
78010/* Opcode:  Yield P1 P2 * * *
78011**
78012** Swap the program counter with the value in register P1.  This
78013** has the effect of yielding to a coroutine.
78014**
78015** If the coroutine that is launched by this instruction ends with
78016** Yield or Return then continue to the next instruction.  But if
78017** the coroutine launched by this instruction ends with
78018** EndCoroutine, then jump to P2 rather than continuing with the
78019** next instruction.
78020**
78021** See also: InitCoroutine
78022*/
78023case OP_Yield: {            /* in1, jump */
78024  int pcDest;
78025  pIn1 = &aMem[pOp->p1];
78026  assert( VdbeMemDynamic(pIn1)==0 );
78027  pIn1->flags = MEM_Int;
78028  pcDest = (int)pIn1->u.i;
78029  pIn1->u.i = (int)(pOp - aOp);
78030  REGISTER_TRACE(pOp->p1, pIn1);
78031  pOp = &aOp[pcDest];
78032  break;
78033}
78034
78035/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
78036** Synopsis:  if r[P3]=null halt
78037**
78038** Check the value in register P3.  If it is NULL then Halt using
78039** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
78040** value in register P3 is not NULL, then this routine is a no-op.
78041** The P5 parameter should be 1.
78042*/
78043case OP_HaltIfNull: {      /* in3 */
78044  pIn3 = &aMem[pOp->p3];
78045  if( (pIn3->flags & MEM_Null)==0 ) break;
78046  /* Fall through into OP_Halt */
78047}
78048
78049/* Opcode:  Halt P1 P2 * P4 P5
78050**
78051** Exit immediately.  All open cursors, etc are closed
78052** automatically.
78053**
78054** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
78055** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
78056** For errors, it can be some other value.  If P1!=0 then P2 will determine
78057** whether or not to rollback the current transaction.  Do not rollback
78058** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
78059** then back out all changes that have occurred during this execution of the
78060** VDBE, but do not rollback the transaction.
78061**
78062** If P4 is not null then it is an error message string.
78063**
78064** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
78065**
78066**    0:  (no change)
78067**    1:  NOT NULL contraint failed: P4
78068**    2:  UNIQUE constraint failed: P4
78069**    3:  CHECK constraint failed: P4
78070**    4:  FOREIGN KEY constraint failed: P4
78071**
78072** If P5 is not zero and P4 is NULL, then everything after the ":" is
78073** omitted.
78074**
78075** There is an implied "Halt 0 0 0" instruction inserted at the very end of
78076** every program.  So a jump past the last instruction of the program
78077** is the same as executing Halt.
78078*/
78079case OP_Halt: {
78080  VdbeFrame *pFrame;
78081  int pcx;
78082
78083  pcx = (int)(pOp - aOp);
78084  if( pOp->p1==SQLITE_OK && p->pFrame ){
78085    /* Halt the sub-program. Return control to the parent frame. */
78086    pFrame = p->pFrame;
78087    p->pFrame = pFrame->pParent;
78088    p->nFrame--;
78089    sqlite3VdbeSetChanges(db, p->nChange);
78090    pcx = sqlite3VdbeFrameRestore(pFrame);
78091    lastRowid = db->lastRowid;
78092    if( pOp->p2==OE_Ignore ){
78093      /* Instruction pcx is the OP_Program that invoked the sub-program
78094      ** currently being halted. If the p2 instruction of this OP_Halt
78095      ** instruction is set to OE_Ignore, then the sub-program is throwing
78096      ** an IGNORE exception. In this case jump to the address specified
78097      ** as the p2 of the calling OP_Program.  */
78098      pcx = p->aOp[pcx].p2-1;
78099    }
78100    aOp = p->aOp;
78101    aMem = p->aMem;
78102    pOp = &aOp[pcx];
78103    break;
78104  }
78105  p->rc = pOp->p1;
78106  p->errorAction = (u8)pOp->p2;
78107  p->pc = pcx;
78108  assert( pOp->p5>=0 && pOp->p5<=4 );
78109  if( p->rc ){
78110    if( pOp->p5 ){
78111      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
78112                                             "FOREIGN KEY" };
78113      testcase( pOp->p5==1 );
78114      testcase( pOp->p5==2 );
78115      testcase( pOp->p5==3 );
78116      testcase( pOp->p5==4 );
78117      sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
78118      if( pOp->p4.z ){
78119        p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
78120      }
78121    }else{
78122      sqlite3VdbeError(p, "%s", pOp->p4.z);
78123    }
78124    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
78125  }
78126  rc = sqlite3VdbeHalt(p);
78127  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
78128  if( rc==SQLITE_BUSY ){
78129    p->rc = SQLITE_BUSY;
78130  }else{
78131    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
78132    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
78133    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
78134  }
78135  goto vdbe_return;
78136}
78137
78138/* Opcode: Integer P1 P2 * * *
78139** Synopsis: r[P2]=P1
78140**
78141** The 32-bit integer value P1 is written into register P2.
78142*/
78143case OP_Integer: {         /* out2 */
78144  pOut = out2Prerelease(p, pOp);
78145  pOut->u.i = pOp->p1;
78146  break;
78147}
78148
78149/* Opcode: Int64 * P2 * P4 *
78150** Synopsis: r[P2]=P4
78151**
78152** P4 is a pointer to a 64-bit integer value.
78153** Write that value into register P2.
78154*/
78155case OP_Int64: {           /* out2 */
78156  pOut = out2Prerelease(p, pOp);
78157  assert( pOp->p4.pI64!=0 );
78158  pOut->u.i = *pOp->p4.pI64;
78159  break;
78160}
78161
78162#ifndef SQLITE_OMIT_FLOATING_POINT
78163/* Opcode: Real * P2 * P4 *
78164** Synopsis: r[P2]=P4
78165**
78166** P4 is a pointer to a 64-bit floating point value.
78167** Write that value into register P2.
78168*/
78169case OP_Real: {            /* same as TK_FLOAT, out2 */
78170  pOut = out2Prerelease(p, pOp);
78171  pOut->flags = MEM_Real;
78172  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
78173  pOut->u.r = *pOp->p4.pReal;
78174  break;
78175}
78176#endif
78177
78178/* Opcode: String8 * P2 * P4 *
78179** Synopsis: r[P2]='P4'
78180**
78181** P4 points to a nul terminated UTF-8 string. This opcode is transformed
78182** into a String opcode before it is executed for the first time.  During
78183** this transformation, the length of string P4 is computed and stored
78184** as the P1 parameter.
78185*/
78186case OP_String8: {         /* same as TK_STRING, out2 */
78187  assert( pOp->p4.z!=0 );
78188  pOut = out2Prerelease(p, pOp);
78189  pOp->opcode = OP_String;
78190  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
78191
78192#ifndef SQLITE_OMIT_UTF16
78193  if( encoding!=SQLITE_UTF8 ){
78194    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
78195    assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
78196    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
78197    assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
78198    assert( VdbeMemDynamic(pOut)==0 );
78199    pOut->szMalloc = 0;
78200    pOut->flags |= MEM_Static;
78201    if( pOp->p4type==P4_DYNAMIC ){
78202      sqlite3DbFree(db, pOp->p4.z);
78203    }
78204    pOp->p4type = P4_DYNAMIC;
78205    pOp->p4.z = pOut->z;
78206    pOp->p1 = pOut->n;
78207  }
78208  testcase( rc==SQLITE_TOOBIG );
78209#endif
78210  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78211    goto too_big;
78212  }
78213  assert( rc==SQLITE_OK );
78214  /* Fall through to the next case, OP_String */
78215}
78216
78217/* Opcode: String P1 P2 P3 P4 P5
78218** Synopsis: r[P2]='P4' (len=P1)
78219**
78220** The string value P4 of length P1 (bytes) is stored in register P2.
78221**
78222** If P3 is not zero and the content of register P3 is equal to P5, then
78223** the datatype of the register P2 is converted to BLOB.  The content is
78224** the same sequence of bytes, it is merely interpreted as a BLOB instead
78225** of a string, as if it had been CAST.  In other words:
78226**
78227** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
78228*/
78229case OP_String: {          /* out2 */
78230  assert( pOp->p4.z!=0 );
78231  pOut = out2Prerelease(p, pOp);
78232  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78233  pOut->z = pOp->p4.z;
78234  pOut->n = pOp->p1;
78235  pOut->enc = encoding;
78236  UPDATE_MAX_BLOBSIZE(pOut);
78237#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
78238  if( pOp->p3>0 ){
78239    assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78240    pIn3 = &aMem[pOp->p3];
78241    assert( pIn3->flags & MEM_Int );
78242    if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
78243  }
78244#endif
78245  break;
78246}
78247
78248/* Opcode: Null P1 P2 P3 * *
78249** Synopsis:  r[P2..P3]=NULL
78250**
78251** Write a NULL into registers P2.  If P3 greater than P2, then also write
78252** NULL into register P3 and every register in between P2 and P3.  If P3
78253** is less than P2 (typically P3 is zero) then only register P2 is
78254** set to NULL.
78255**
78256** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
78257** NULL values will not compare equal even if SQLITE_NULLEQ is set on
78258** OP_Ne or OP_Eq.
78259*/
78260case OP_Null: {           /* out2 */
78261  int cnt;
78262  u16 nullFlag;
78263  pOut = out2Prerelease(p, pOp);
78264  cnt = pOp->p3-pOp->p2;
78265  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78266  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
78267  while( cnt>0 ){
78268    pOut++;
78269    memAboutToChange(p, pOut);
78270    sqlite3VdbeMemSetNull(pOut);
78271    pOut->flags = nullFlag;
78272    cnt--;
78273  }
78274  break;
78275}
78276
78277/* Opcode: SoftNull P1 * * * *
78278** Synopsis:  r[P1]=NULL
78279**
78280** Set register P1 to have the value NULL as seen by the OP_MakeRecord
78281** instruction, but do not free any string or blob memory associated with
78282** the register, so that if the value was a string or blob that was
78283** previously copied using OP_SCopy, the copies will continue to be valid.
78284*/
78285case OP_SoftNull: {
78286  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78287  pOut = &aMem[pOp->p1];
78288  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
78289  break;
78290}
78291
78292/* Opcode: Blob P1 P2 * P4 *
78293** Synopsis: r[P2]=P4 (len=P1)
78294**
78295** P4 points to a blob of data P1 bytes long.  Store this
78296** blob in register P2.
78297*/
78298case OP_Blob: {                /* out2 */
78299  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
78300  pOut = out2Prerelease(p, pOp);
78301  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
78302  pOut->enc = encoding;
78303  UPDATE_MAX_BLOBSIZE(pOut);
78304  break;
78305}
78306
78307/* Opcode: Variable P1 P2 * P4 *
78308** Synopsis: r[P2]=parameter(P1,P4)
78309**
78310** Transfer the values of bound parameter P1 into register P2
78311**
78312** If the parameter is named, then its name appears in P4.
78313** The P4 value is used by sqlite3_bind_parameter_name().
78314*/
78315case OP_Variable: {            /* out2 */
78316  Mem *pVar;       /* Value being transferred */
78317
78318  assert( pOp->p1>0 && pOp->p1<=p->nVar );
78319  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
78320  pVar = &p->aVar[pOp->p1 - 1];
78321  if( sqlite3VdbeMemTooBig(pVar) ){
78322    goto too_big;
78323  }
78324  pOut = out2Prerelease(p, pOp);
78325  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
78326  UPDATE_MAX_BLOBSIZE(pOut);
78327  break;
78328}
78329
78330/* Opcode: Move P1 P2 P3 * *
78331** Synopsis:  r[P2@P3]=r[P1@P3]
78332**
78333** Move the P3 values in register P1..P1+P3-1 over into
78334** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
78335** left holding a NULL.  It is an error for register ranges
78336** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
78337** for P3 to be less than 1.
78338*/
78339case OP_Move: {
78340  int n;           /* Number of registers left to copy */
78341  int p1;          /* Register to copy from */
78342  int p2;          /* Register to copy to */
78343
78344  n = pOp->p3;
78345  p1 = pOp->p1;
78346  p2 = pOp->p2;
78347  assert( n>0 && p1>0 && p2>0 );
78348  assert( p1+n<=p2 || p2+n<=p1 );
78349
78350  pIn1 = &aMem[p1];
78351  pOut = &aMem[p2];
78352  do{
78353    assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
78354    assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
78355    assert( memIsValid(pIn1) );
78356    memAboutToChange(p, pOut);
78357    sqlite3VdbeMemMove(pOut, pIn1);
78358#ifdef SQLITE_DEBUG
78359    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
78360      pOut->pScopyFrom += pOp->p2 - p1;
78361    }
78362#endif
78363    Deephemeralize(pOut);
78364    REGISTER_TRACE(p2++, pOut);
78365    pIn1++;
78366    pOut++;
78367  }while( --n );
78368  break;
78369}
78370
78371/* Opcode: Copy P1 P2 P3 * *
78372** Synopsis: r[P2@P3+1]=r[P1@P3+1]
78373**
78374** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
78375**
78376** This instruction makes a deep copy of the value.  A duplicate
78377** is made of any string or blob constant.  See also OP_SCopy.
78378*/
78379case OP_Copy: {
78380  int n;
78381
78382  n = pOp->p3;
78383  pIn1 = &aMem[pOp->p1];
78384  pOut = &aMem[pOp->p2];
78385  assert( pOut!=pIn1 );
78386  while( 1 ){
78387    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78388    Deephemeralize(pOut);
78389#ifdef SQLITE_DEBUG
78390    pOut->pScopyFrom = 0;
78391#endif
78392    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
78393    if( (n--)==0 ) break;
78394    pOut++;
78395    pIn1++;
78396  }
78397  break;
78398}
78399
78400/* Opcode: SCopy P1 P2 * * *
78401** Synopsis: r[P2]=r[P1]
78402**
78403** Make a shallow copy of register P1 into register P2.
78404**
78405** This instruction makes a shallow copy of the value.  If the value
78406** is a string or blob, then the copy is only a pointer to the
78407** original and hence if the original changes so will the copy.
78408** Worse, if the original is deallocated, the copy becomes invalid.
78409** Thus the program must guarantee that the original will not change
78410** during the lifetime of the copy.  Use OP_Copy to make a complete
78411** copy.
78412*/
78413case OP_SCopy: {            /* out2 */
78414  pIn1 = &aMem[pOp->p1];
78415  pOut = &aMem[pOp->p2];
78416  assert( pOut!=pIn1 );
78417  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78418#ifdef SQLITE_DEBUG
78419  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
78420#endif
78421  break;
78422}
78423
78424/* Opcode: IntCopy P1 P2 * * *
78425** Synopsis: r[P2]=r[P1]
78426**
78427** Transfer the integer value held in register P1 into register P2.
78428**
78429** This is an optimized version of SCopy that works only for integer
78430** values.
78431*/
78432case OP_IntCopy: {            /* out2 */
78433  pIn1 = &aMem[pOp->p1];
78434  assert( (pIn1->flags & MEM_Int)!=0 );
78435  pOut = &aMem[pOp->p2];
78436  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
78437  break;
78438}
78439
78440/* Opcode: ResultRow P1 P2 * * *
78441** Synopsis:  output=r[P1@P2]
78442**
78443** The registers P1 through P1+P2-1 contain a single row of
78444** results. This opcode causes the sqlite3_step() call to terminate
78445** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
78446** structure to provide access to the r(P1)..r(P1+P2-1) values as
78447** the result row.
78448*/
78449case OP_ResultRow: {
78450  Mem *pMem;
78451  int i;
78452  assert( p->nResColumn==pOp->p2 );
78453  assert( pOp->p1>0 );
78454  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
78455
78456#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78457  /* Run the progress counter just before returning.
78458  */
78459  if( db->xProgress!=0
78460   && nVmStep>=nProgressLimit
78461   && db->xProgress(db->pProgressArg)!=0
78462  ){
78463    rc = SQLITE_INTERRUPT;
78464    goto abort_due_to_error;
78465  }
78466#endif
78467
78468  /* If this statement has violated immediate foreign key constraints, do
78469  ** not return the number of rows modified. And do not RELEASE the statement
78470  ** transaction. It needs to be rolled back.  */
78471  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
78472    assert( db->flags&SQLITE_CountRows );
78473    assert( p->usesStmtJournal );
78474    goto abort_due_to_error;
78475  }
78476
78477  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
78478  ** DML statements invoke this opcode to return the number of rows
78479  ** modified to the user. This is the only way that a VM that
78480  ** opens a statement transaction may invoke this opcode.
78481  **
78482  ** In case this is such a statement, close any statement transaction
78483  ** opened by this VM before returning control to the user. This is to
78484  ** ensure that statement-transactions are always nested, not overlapping.
78485  ** If the open statement-transaction is not closed here, then the user
78486  ** may step another VM that opens its own statement transaction. This
78487  ** may lead to overlapping statement transactions.
78488  **
78489  ** The statement transaction is never a top-level transaction.  Hence
78490  ** the RELEASE call below can never fail.
78491  */
78492  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
78493  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
78494  assert( rc==SQLITE_OK );
78495
78496  /* Invalidate all ephemeral cursor row caches */
78497  p->cacheCtr = (p->cacheCtr + 2)|1;
78498
78499  /* Make sure the results of the current row are \000 terminated
78500  ** and have an assigned type.  The results are de-ephemeralized as
78501  ** a side effect.
78502  */
78503  pMem = p->pResultSet = &aMem[pOp->p1];
78504  for(i=0; i<pOp->p2; i++){
78505    assert( memIsValid(&pMem[i]) );
78506    Deephemeralize(&pMem[i]);
78507    assert( (pMem[i].flags & MEM_Ephem)==0
78508            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
78509    sqlite3VdbeMemNulTerminate(&pMem[i]);
78510    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
78511  }
78512  if( db->mallocFailed ) goto no_mem;
78513
78514  if( db->mTrace & SQLITE_TRACE_ROW ){
78515    db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
78516  }
78517
78518  /* Return SQLITE_ROW
78519  */
78520  p->pc = (int)(pOp - aOp) + 1;
78521  rc = SQLITE_ROW;
78522  goto vdbe_return;
78523}
78524
78525/* Opcode: Concat P1 P2 P3 * *
78526** Synopsis: r[P3]=r[P2]+r[P1]
78527**
78528** Add the text in register P1 onto the end of the text in
78529** register P2 and store the result in register P3.
78530** If either the P1 or P2 text are NULL then store NULL in P3.
78531**
78532**   P3 = P2 || P1
78533**
78534** It is illegal for P1 and P3 to be the same register. Sometimes,
78535** if P3 is the same register as P2, the implementation is able
78536** to avoid a memcpy().
78537*/
78538case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
78539  i64 nByte;
78540
78541  pIn1 = &aMem[pOp->p1];
78542  pIn2 = &aMem[pOp->p2];
78543  pOut = &aMem[pOp->p3];
78544  assert( pIn1!=pOut );
78545  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78546    sqlite3VdbeMemSetNull(pOut);
78547    break;
78548  }
78549  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
78550  Stringify(pIn1, encoding);
78551  Stringify(pIn2, encoding);
78552  nByte = pIn1->n + pIn2->n;
78553  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78554    goto too_big;
78555  }
78556  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
78557    goto no_mem;
78558  }
78559  MemSetTypeFlag(pOut, MEM_Str);
78560  if( pOut!=pIn2 ){
78561    memcpy(pOut->z, pIn2->z, pIn2->n);
78562  }
78563  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
78564  pOut->z[nByte]=0;
78565  pOut->z[nByte+1] = 0;
78566  pOut->flags |= MEM_Term;
78567  pOut->n = (int)nByte;
78568  pOut->enc = encoding;
78569  UPDATE_MAX_BLOBSIZE(pOut);
78570  break;
78571}
78572
78573/* Opcode: Add P1 P2 P3 * *
78574** Synopsis:  r[P3]=r[P1]+r[P2]
78575**
78576** Add the value in register P1 to the value in register P2
78577** and store the result in register P3.
78578** If either input is NULL, the result is NULL.
78579*/
78580/* Opcode: Multiply P1 P2 P3 * *
78581** Synopsis:  r[P3]=r[P1]*r[P2]
78582**
78583**
78584** Multiply the value in register P1 by the value in register P2
78585** and store the result in register P3.
78586** If either input is NULL, the result is NULL.
78587*/
78588/* Opcode: Subtract P1 P2 P3 * *
78589** Synopsis:  r[P3]=r[P2]-r[P1]
78590**
78591** Subtract the value in register P1 from the value in register P2
78592** and store the result in register P3.
78593** If either input is NULL, the result is NULL.
78594*/
78595/* Opcode: Divide P1 P2 P3 * *
78596** Synopsis:  r[P3]=r[P2]/r[P1]
78597**
78598** Divide the value in register P1 by the value in register P2
78599** and store the result in register P3 (P3=P2/P1). If the value in
78600** register P1 is zero, then the result is NULL. If either input is
78601** NULL, the result is NULL.
78602*/
78603/* Opcode: Remainder P1 P2 P3 * *
78604** Synopsis:  r[P3]=r[P2]%r[P1]
78605**
78606** Compute the remainder after integer register P2 is divided by
78607** register P1 and store the result in register P3.
78608** If the value in register P1 is zero the result is NULL.
78609** If either operand is NULL, the result is NULL.
78610*/
78611case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
78612case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
78613case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
78614case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
78615case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
78616  char bIntint;   /* Started out as two integer operands */
78617  u16 flags;      /* Combined MEM_* flags from both inputs */
78618  u16 type1;      /* Numeric type of left operand */
78619  u16 type2;      /* Numeric type of right operand */
78620  i64 iA;         /* Integer value of left operand */
78621  i64 iB;         /* Integer value of right operand */
78622  double rA;      /* Real value of left operand */
78623  double rB;      /* Real value of right operand */
78624
78625  pIn1 = &aMem[pOp->p1];
78626  type1 = numericType(pIn1);
78627  pIn2 = &aMem[pOp->p2];
78628  type2 = numericType(pIn2);
78629  pOut = &aMem[pOp->p3];
78630  flags = pIn1->flags | pIn2->flags;
78631  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
78632  if( (type1 & type2 & MEM_Int)!=0 ){
78633    iA = pIn1->u.i;
78634    iB = pIn2->u.i;
78635    bIntint = 1;
78636    switch( pOp->opcode ){
78637      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
78638      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
78639      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
78640      case OP_Divide: {
78641        if( iA==0 ) goto arithmetic_result_is_null;
78642        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
78643        iB /= iA;
78644        break;
78645      }
78646      default: {
78647        if( iA==0 ) goto arithmetic_result_is_null;
78648        if( iA==-1 ) iA = 1;
78649        iB %= iA;
78650        break;
78651      }
78652    }
78653    pOut->u.i = iB;
78654    MemSetTypeFlag(pOut, MEM_Int);
78655  }else{
78656    bIntint = 0;
78657fp_math:
78658    rA = sqlite3VdbeRealValue(pIn1);
78659    rB = sqlite3VdbeRealValue(pIn2);
78660    switch( pOp->opcode ){
78661      case OP_Add:         rB += rA;       break;
78662      case OP_Subtract:    rB -= rA;       break;
78663      case OP_Multiply:    rB *= rA;       break;
78664      case OP_Divide: {
78665        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78666        if( rA==(double)0 ) goto arithmetic_result_is_null;
78667        rB /= rA;
78668        break;
78669      }
78670      default: {
78671        iA = (i64)rA;
78672        iB = (i64)rB;
78673        if( iA==0 ) goto arithmetic_result_is_null;
78674        if( iA==-1 ) iA = 1;
78675        rB = (double)(iB % iA);
78676        break;
78677      }
78678    }
78679#ifdef SQLITE_OMIT_FLOATING_POINT
78680    pOut->u.i = rB;
78681    MemSetTypeFlag(pOut, MEM_Int);
78682#else
78683    if( sqlite3IsNaN(rB) ){
78684      goto arithmetic_result_is_null;
78685    }
78686    pOut->u.r = rB;
78687    MemSetTypeFlag(pOut, MEM_Real);
78688    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
78689      sqlite3VdbeIntegerAffinity(pOut);
78690    }
78691#endif
78692  }
78693  break;
78694
78695arithmetic_result_is_null:
78696  sqlite3VdbeMemSetNull(pOut);
78697  break;
78698}
78699
78700/* Opcode: CollSeq P1 * * P4
78701**
78702** P4 is a pointer to a CollSeq struct. If the next call to a user function
78703** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
78704** be returned. This is used by the built-in min(), max() and nullif()
78705** functions.
78706**
78707** If P1 is not zero, then it is a register that a subsequent min() or
78708** max() aggregate will set to 1 if the current row is not the minimum or
78709** maximum.  The P1 register is initialized to 0 by this instruction.
78710**
78711** The interface used by the implementation of the aforementioned functions
78712** to retrieve the collation sequence set by this opcode is not available
78713** publicly.  Only built-in functions have access to this feature.
78714*/
78715case OP_CollSeq: {
78716  assert( pOp->p4type==P4_COLLSEQ );
78717  if( pOp->p1 ){
78718    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
78719  }
78720  break;
78721}
78722
78723/* Opcode: Function0 P1 P2 P3 P4 P5
78724** Synopsis: r[P3]=func(r[P2@P5])
78725**
78726** Invoke a user function (P4 is a pointer to a FuncDef object that
78727** defines the function) with P5 arguments taken from register P2 and
78728** successors.  The result of the function is stored in register P3.
78729** Register P3 must not be one of the function inputs.
78730**
78731** P1 is a 32-bit bitmask indicating whether or not each argument to the
78732** function was determined to be constant at compile time. If the first
78733** argument was constant then bit 0 of P1 is set. This is used to determine
78734** whether meta data associated with a user function argument using the
78735** sqlite3_set_auxdata() API may be safely retained until the next
78736** invocation of this opcode.
78737**
78738** See also: Function, AggStep, AggFinal
78739*/
78740/* Opcode: Function P1 P2 P3 P4 P5
78741** Synopsis: r[P3]=func(r[P2@P5])
78742**
78743** Invoke a user function (P4 is a pointer to an sqlite3_context object that
78744** contains a pointer to the function to be run) with P5 arguments taken
78745** from register P2 and successors.  The result of the function is stored
78746** in register P3.  Register P3 must not be one of the function inputs.
78747**
78748** P1 is a 32-bit bitmask indicating whether or not each argument to the
78749** function was determined to be constant at compile time. If the first
78750** argument was constant then bit 0 of P1 is set. This is used to determine
78751** whether meta data associated with a user function argument using the
78752** sqlite3_set_auxdata() API may be safely retained until the next
78753** invocation of this opcode.
78754**
78755** SQL functions are initially coded as OP_Function0 with P4 pointing
78756** to a FuncDef object.  But on first evaluation, the P4 operand is
78757** automatically converted into an sqlite3_context object and the operation
78758** changed to this OP_Function opcode.  In this way, the initialization of
78759** the sqlite3_context object occurs only once, rather than once for each
78760** evaluation of the function.
78761**
78762** See also: Function0, AggStep, AggFinal
78763*/
78764case OP_Function0: {
78765  int n;
78766  sqlite3_context *pCtx;
78767
78768  assert( pOp->p4type==P4_FUNCDEF );
78769  n = pOp->p5;
78770  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
78771  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
78772  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78773  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78774  if( pCtx==0 ) goto no_mem;
78775  pCtx->pOut = 0;
78776  pCtx->pFunc = pOp->p4.pFunc;
78777  pCtx->iOp = (int)(pOp - aOp);
78778  pCtx->pVdbe = p;
78779  pCtx->argc = n;
78780  pOp->p4type = P4_FUNCCTX;
78781  pOp->p4.pCtx = pCtx;
78782  pOp->opcode = OP_Function;
78783  /* Fall through into OP_Function */
78784}
78785case OP_Function: {
78786  int i;
78787  sqlite3_context *pCtx;
78788
78789  assert( pOp->p4type==P4_FUNCCTX );
78790  pCtx = pOp->p4.pCtx;
78791
78792  /* If this function is inside of a trigger, the register array in aMem[]
78793  ** might change from one evaluation to the next.  The next block of code
78794  ** checks to see if the register array has changed, and if so it
78795  ** reinitializes the relavant parts of the sqlite3_context object */
78796  pOut = &aMem[pOp->p3];
78797  if( pCtx->pOut != pOut ){
78798    pCtx->pOut = pOut;
78799    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78800  }
78801
78802  memAboutToChange(p, pCtx->pOut);
78803#ifdef SQLITE_DEBUG
78804  for(i=0; i<pCtx->argc; i++){
78805    assert( memIsValid(pCtx->argv[i]) );
78806    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78807  }
78808#endif
78809  MemSetTypeFlag(pCtx->pOut, MEM_Null);
78810  pCtx->fErrorOrAux = 0;
78811  db->lastRowid = lastRowid;
78812  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
78813  lastRowid = db->lastRowid;  /* Remember rowid changes made by xSFunc */
78814
78815  /* If the function returned an error, throw an exception */
78816  if( pCtx->fErrorOrAux ){
78817    if( pCtx->isError ){
78818      sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
78819      rc = pCtx->isError;
78820    }
78821    sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
78822    if( rc ) goto abort_due_to_error;
78823  }
78824
78825  /* Copy the result of the function into register P3 */
78826  if( pOut->flags & (MEM_Str|MEM_Blob) ){
78827    sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
78828    if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
78829  }
78830
78831  REGISTER_TRACE(pOp->p3, pCtx->pOut);
78832  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
78833  break;
78834}
78835
78836/* Opcode: BitAnd P1 P2 P3 * *
78837** Synopsis:  r[P3]=r[P1]&r[P2]
78838**
78839** Take the bit-wise AND of the values in register P1 and P2 and
78840** store the result in register P3.
78841** If either input is NULL, the result is NULL.
78842*/
78843/* Opcode: BitOr P1 P2 P3 * *
78844** Synopsis:  r[P3]=r[P1]|r[P2]
78845**
78846** Take the bit-wise OR of the values in register P1 and P2 and
78847** store the result in register P3.
78848** If either input is NULL, the result is NULL.
78849*/
78850/* Opcode: ShiftLeft P1 P2 P3 * *
78851** Synopsis:  r[P3]=r[P2]<<r[P1]
78852**
78853** Shift the integer value in register P2 to the left by the
78854** number of bits specified by the integer in register P1.
78855** Store the result in register P3.
78856** If either input is NULL, the result is NULL.
78857*/
78858/* Opcode: ShiftRight P1 P2 P3 * *
78859** Synopsis:  r[P3]=r[P2]>>r[P1]
78860**
78861** Shift the integer value in register P2 to the right by the
78862** number of bits specified by the integer in register P1.
78863** Store the result in register P3.
78864** If either input is NULL, the result is NULL.
78865*/
78866case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
78867case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
78868case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
78869case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
78870  i64 iA;
78871  u64 uA;
78872  i64 iB;
78873  u8 op;
78874
78875  pIn1 = &aMem[pOp->p1];
78876  pIn2 = &aMem[pOp->p2];
78877  pOut = &aMem[pOp->p3];
78878  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78879    sqlite3VdbeMemSetNull(pOut);
78880    break;
78881  }
78882  iA = sqlite3VdbeIntValue(pIn2);
78883  iB = sqlite3VdbeIntValue(pIn1);
78884  op = pOp->opcode;
78885  if( op==OP_BitAnd ){
78886    iA &= iB;
78887  }else if( op==OP_BitOr ){
78888    iA |= iB;
78889  }else if( iB!=0 ){
78890    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
78891
78892    /* If shifting by a negative amount, shift in the other direction */
78893    if( iB<0 ){
78894      assert( OP_ShiftRight==OP_ShiftLeft+1 );
78895      op = 2*OP_ShiftLeft + 1 - op;
78896      iB = iB>(-64) ? -iB : 64;
78897    }
78898
78899    if( iB>=64 ){
78900      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
78901    }else{
78902      memcpy(&uA, &iA, sizeof(uA));
78903      if( op==OP_ShiftLeft ){
78904        uA <<= iB;
78905      }else{
78906        uA >>= iB;
78907        /* Sign-extend on a right shift of a negative number */
78908        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
78909      }
78910      memcpy(&iA, &uA, sizeof(iA));
78911    }
78912  }
78913  pOut->u.i = iA;
78914  MemSetTypeFlag(pOut, MEM_Int);
78915  break;
78916}
78917
78918/* Opcode: AddImm  P1 P2 * * *
78919** Synopsis:  r[P1]=r[P1]+P2
78920**
78921** Add the constant P2 to the value in register P1.
78922** The result is always an integer.
78923**
78924** To force any register to be an integer, just add 0.
78925*/
78926case OP_AddImm: {            /* in1 */
78927  pIn1 = &aMem[pOp->p1];
78928  memAboutToChange(p, pIn1);
78929  sqlite3VdbeMemIntegerify(pIn1);
78930  pIn1->u.i += pOp->p2;
78931  break;
78932}
78933
78934/* Opcode: MustBeInt P1 P2 * * *
78935**
78936** Force the value in register P1 to be an integer.  If the value
78937** in P1 is not an integer and cannot be converted into an integer
78938** without data loss, then jump immediately to P2, or if P2==0
78939** raise an SQLITE_MISMATCH exception.
78940*/
78941case OP_MustBeInt: {            /* jump, in1 */
78942  pIn1 = &aMem[pOp->p1];
78943  if( (pIn1->flags & MEM_Int)==0 ){
78944    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
78945    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
78946    if( (pIn1->flags & MEM_Int)==0 ){
78947      if( pOp->p2==0 ){
78948        rc = SQLITE_MISMATCH;
78949        goto abort_due_to_error;
78950      }else{
78951        goto jump_to_p2;
78952      }
78953    }
78954  }
78955  MemSetTypeFlag(pIn1, MEM_Int);
78956  break;
78957}
78958
78959#ifndef SQLITE_OMIT_FLOATING_POINT
78960/* Opcode: RealAffinity P1 * * * *
78961**
78962** If register P1 holds an integer convert it to a real value.
78963**
78964** This opcode is used when extracting information from a column that
78965** has REAL affinity.  Such column values may still be stored as
78966** integers, for space efficiency, but after extraction we want them
78967** to have only a real value.
78968*/
78969case OP_RealAffinity: {                  /* in1 */
78970  pIn1 = &aMem[pOp->p1];
78971  if( pIn1->flags & MEM_Int ){
78972    sqlite3VdbeMemRealify(pIn1);
78973  }
78974  break;
78975}
78976#endif
78977
78978#ifndef SQLITE_OMIT_CAST
78979/* Opcode: Cast P1 P2 * * *
78980** Synopsis: affinity(r[P1])
78981**
78982** Force the value in register P1 to be the type defined by P2.
78983**
78984** <ul>
78985** <li value="97"> TEXT
78986** <li value="98"> BLOB
78987** <li value="99"> NUMERIC
78988** <li value="100"> INTEGER
78989** <li value="101"> REAL
78990** </ul>
78991**
78992** A NULL value is not changed by this routine.  It remains NULL.
78993*/
78994case OP_Cast: {                  /* in1 */
78995  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
78996  testcase( pOp->p2==SQLITE_AFF_TEXT );
78997  testcase( pOp->p2==SQLITE_AFF_BLOB );
78998  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
78999  testcase( pOp->p2==SQLITE_AFF_INTEGER );
79000  testcase( pOp->p2==SQLITE_AFF_REAL );
79001  pIn1 = &aMem[pOp->p1];
79002  memAboutToChange(p, pIn1);
79003  rc = ExpandBlob(pIn1);
79004  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
79005  UPDATE_MAX_BLOBSIZE(pIn1);
79006  if( rc ) goto abort_due_to_error;
79007  break;
79008}
79009#endif /* SQLITE_OMIT_CAST */
79010
79011/* Opcode: Lt P1 P2 P3 P4 P5
79012** Synopsis: if r[P1]<r[P3] goto P2
79013**
79014** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
79015** jump to address P2.
79016**
79017** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
79018** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
79019** bit is clear then fall through if either operand is NULL.
79020**
79021** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79022** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
79023** to coerce both inputs according to this affinity before the
79024** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79025** affinity is used. Note that the affinity conversions are stored
79026** back into the input registers P1 and P3.  So this opcode can cause
79027** persistent changes to registers P1 and P3.
79028**
79029** Once any conversions have taken place, and neither value is NULL,
79030** the values are compared. If both values are blobs then memcmp() is
79031** used to determine the results of the comparison.  If both values
79032** are text, then the appropriate collating function specified in
79033** P4 is  used to do the comparison.  If P4 is not specified then
79034** memcmp() is used to compare text string.  If both values are
79035** numeric, then a numeric comparison is used. If the two values
79036** are of different types, then numbers are considered less than
79037** strings and strings are considered less than blobs.
79038**
79039** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
79040** store a boolean result (either 0, or 1, or NULL) in register P2.
79041**
79042** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
79043** equal to one another, provided that they do not have their MEM_Cleared
79044** bit set.
79045*/
79046/* Opcode: Ne P1 P2 P3 P4 P5
79047** Synopsis: if r[P1]!=r[P3] goto P2
79048**
79049** This works just like the Lt opcode except that the jump is taken if
79050** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
79051** additional information.
79052**
79053** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79054** true or false and is never NULL.  If both operands are NULL then the result
79055** of comparison is false.  If either operand is NULL then the result is true.
79056** If neither operand is NULL the result is the same as it would be if
79057** the SQLITE_NULLEQ flag were omitted from P5.
79058*/
79059/* Opcode: Eq 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 operands in registers P1 and P3 are equal.
79064** See the Lt opcode for additional information.
79065**
79066** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79067** true or false and is never NULL.  If both operands are NULL then the result
79068** of comparison is true.  If either operand is NULL then the result is false.
79069** If neither operand is NULL the result is the same as it would be if
79070** the SQLITE_NULLEQ flag were omitted from P5.
79071*/
79072/* Opcode: Le P1 P2 P3 P4 P5
79073** Synopsis: if r[P1]<=r[P3] goto P2
79074**
79075** This works just like the Lt opcode except that the jump is taken if
79076** the content of register P3 is less than or equal to the content of
79077** register P1.  See the Lt opcode for additional information.
79078*/
79079/* Opcode: Gt P1 P2 P3 P4 P5
79080** Synopsis: if r[P1]>r[P3] goto P2
79081**
79082** This works just like the Lt opcode except that the jump is taken if
79083** the content of register P3 is greater than the content of
79084** register P1.  See the Lt opcode for additional information.
79085*/
79086/* Opcode: Ge P1 P2 P3 P4 P5
79087** Synopsis: if r[P1]>=r[P3] goto P2
79088**
79089** This works just like the Lt opcode except that the jump is taken if
79090** the content of register P3 is greater than or equal to the content of
79091** register P1.  See the Lt opcode for additional information.
79092*/
79093case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
79094case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
79095case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
79096case OP_Le:               /* same as TK_LE, jump, in1, in3 */
79097case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
79098case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
79099  int res;            /* Result of the comparison of pIn1 against pIn3 */
79100  char affinity;      /* Affinity to use for comparison */
79101  u16 flags1;         /* Copy of initial value of pIn1->flags */
79102  u16 flags3;         /* Copy of initial value of pIn3->flags */
79103
79104  pIn1 = &aMem[pOp->p1];
79105  pIn3 = &aMem[pOp->p3];
79106  flags1 = pIn1->flags;
79107  flags3 = pIn3->flags;
79108  if( (flags1 | flags3)&MEM_Null ){
79109    /* One or both operands are NULL */
79110    if( pOp->p5 & SQLITE_NULLEQ ){
79111      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
79112      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
79113      ** or not both operands are null.
79114      */
79115      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
79116      assert( (flags1 & MEM_Cleared)==0 );
79117      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
79118      if( (flags1&MEM_Null)!=0
79119       && (flags3&MEM_Null)!=0
79120       && (flags3&MEM_Cleared)==0
79121      ){
79122        res = 0;  /* Results are equal */
79123      }else{
79124        res = 1;  /* Results are not equal */
79125      }
79126    }else{
79127      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
79128      ** then the result is always NULL.
79129      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
79130      */
79131      if( pOp->p5 & SQLITE_STOREP2 ){
79132        pOut = &aMem[pOp->p2];
79133        memAboutToChange(p, pOut);
79134        MemSetTypeFlag(pOut, MEM_Null);
79135        REGISTER_TRACE(pOp->p2, pOut);
79136      }else{
79137        VdbeBranchTaken(2,3);
79138        if( pOp->p5 & SQLITE_JUMPIFNULL ){
79139          goto jump_to_p2;
79140        }
79141      }
79142      break;
79143    }
79144  }else{
79145    /* Neither operand is NULL.  Do a comparison. */
79146    affinity = pOp->p5 & SQLITE_AFF_MASK;
79147    if( affinity>=SQLITE_AFF_NUMERIC ){
79148      if( (flags1 | flags3)&MEM_Str ){
79149        if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79150          applyNumericAffinity(pIn1,0);
79151          flags3 = pIn3->flags;
79152        }
79153        if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79154          applyNumericAffinity(pIn3,0);
79155        }
79156      }
79157    }else if( affinity==SQLITE_AFF_TEXT ){
79158      if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
79159        testcase( pIn1->flags & MEM_Int );
79160        testcase( pIn1->flags & MEM_Real );
79161        sqlite3VdbeMemStringify(pIn1, encoding, 1);
79162        testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
79163        flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
79164        flags3 = pIn3->flags;
79165      }
79166      if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
79167        testcase( pIn3->flags & MEM_Int );
79168        testcase( pIn3->flags & MEM_Real );
79169        sqlite3VdbeMemStringify(pIn3, encoding, 1);
79170        testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
79171        flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
79172      }
79173    }
79174    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
79175    if( flags1 & MEM_Zero ){
79176      sqlite3VdbeMemExpandBlob(pIn1);
79177      flags1 &= ~MEM_Zero;
79178    }
79179    if( flags3 & MEM_Zero ){
79180      sqlite3VdbeMemExpandBlob(pIn3);
79181      flags3 &= ~MEM_Zero;
79182    }
79183    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
79184  }
79185  switch( pOp->opcode ){
79186    case OP_Eq:    res = res==0;     break;
79187    case OP_Ne:    res = res!=0;     break;
79188    case OP_Lt:    res = res<0;      break;
79189    case OP_Le:    res = res<=0;     break;
79190    case OP_Gt:    res = res>0;      break;
79191    default:       res = res>=0;     break;
79192  }
79193
79194  /* Undo any changes made by applyAffinity() to the input registers. */
79195  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
79196  pIn1->flags = flags1;
79197  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
79198  pIn3->flags = flags3;
79199
79200  if( pOp->p5 & SQLITE_STOREP2 ){
79201    pOut = &aMem[pOp->p2];
79202    memAboutToChange(p, pOut);
79203    MemSetTypeFlag(pOut, MEM_Int);
79204    pOut->u.i = res;
79205    REGISTER_TRACE(pOp->p2, pOut);
79206  }else{
79207    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
79208    if( res ){
79209      goto jump_to_p2;
79210    }
79211  }
79212  break;
79213}
79214
79215/* Opcode: Permutation * * * P4 *
79216**
79217** Set the permutation used by the OP_Compare operator to be the array
79218** of integers in P4.
79219**
79220** The permutation is only valid until the next OP_Compare that has
79221** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
79222** occur immediately prior to the OP_Compare.
79223**
79224** The first integer in the P4 integer array is the length of the array
79225** and does not become part of the permutation.
79226*/
79227case OP_Permutation: {
79228  assert( pOp->p4type==P4_INTARRAY );
79229  assert( pOp->p4.ai );
79230  aPermute = pOp->p4.ai + 1;
79231  break;
79232}
79233
79234/* Opcode: Compare P1 P2 P3 P4 P5
79235** Synopsis: r[P1@P3] <-> r[P2@P3]
79236**
79237** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
79238** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
79239** the comparison for use by the next OP_Jump instruct.
79240**
79241** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
79242** determined by the most recent OP_Permutation operator.  If the
79243** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
79244** order.
79245**
79246** P4 is a KeyInfo structure that defines collating sequences and sort
79247** orders for the comparison.  The permutation applies to registers
79248** only.  The KeyInfo elements are used sequentially.
79249**
79250** The comparison is a sort comparison, so NULLs compare equal,
79251** NULLs are less than numbers, numbers are less than strings,
79252** and strings are less than blobs.
79253*/
79254case OP_Compare: {
79255  int n;
79256  int i;
79257  int p1;
79258  int p2;
79259  const KeyInfo *pKeyInfo;
79260  int idx;
79261  CollSeq *pColl;    /* Collating sequence to use on this term */
79262  int bRev;          /* True for DESCENDING sort order */
79263
79264  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
79265  n = pOp->p3;
79266  pKeyInfo = pOp->p4.pKeyInfo;
79267  assert( n>0 );
79268  assert( pKeyInfo!=0 );
79269  p1 = pOp->p1;
79270  p2 = pOp->p2;
79271#if SQLITE_DEBUG
79272  if( aPermute ){
79273    int k, mx = 0;
79274    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
79275    assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
79276    assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
79277  }else{
79278    assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
79279    assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
79280  }
79281#endif /* SQLITE_DEBUG */
79282  for(i=0; i<n; i++){
79283    idx = aPermute ? aPermute[i] : i;
79284    assert( memIsValid(&aMem[p1+idx]) );
79285    assert( memIsValid(&aMem[p2+idx]) );
79286    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
79287    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
79288    assert( i<pKeyInfo->nField );
79289    pColl = pKeyInfo->aColl[i];
79290    bRev = pKeyInfo->aSortOrder[i];
79291    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
79292    if( iCompare ){
79293      if( bRev ) iCompare = -iCompare;
79294      break;
79295    }
79296  }
79297  aPermute = 0;
79298  break;
79299}
79300
79301/* Opcode: Jump P1 P2 P3 * *
79302**
79303** Jump to the instruction at address P1, P2, or P3 depending on whether
79304** in the most recent OP_Compare instruction the P1 vector was less than
79305** equal to, or greater than the P2 vector, respectively.
79306*/
79307case OP_Jump: {             /* jump */
79308  if( iCompare<0 ){
79309    VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
79310  }else if( iCompare==0 ){
79311    VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
79312  }else{
79313    VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
79314  }
79315  break;
79316}
79317
79318/* Opcode: And P1 P2 P3 * *
79319** Synopsis: r[P3]=(r[P1] && r[P2])
79320**
79321** Take the logical AND of the values in registers P1 and P2 and
79322** write the result into register P3.
79323**
79324** If either P1 or P2 is 0 (false) then the result is 0 even if
79325** the other input is NULL.  A NULL and true or two NULLs give
79326** a NULL output.
79327*/
79328/* Opcode: Or P1 P2 P3 * *
79329** Synopsis: r[P3]=(r[P1] || r[P2])
79330**
79331** Take the logical OR of the values in register P1 and P2 and
79332** store the answer in register P3.
79333**
79334** If either P1 or P2 is nonzero (true) then the result is 1 (true)
79335** even if the other input is NULL.  A NULL and false or two NULLs
79336** give a NULL output.
79337*/
79338case OP_And:              /* same as TK_AND, in1, in2, out3 */
79339case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
79340  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79341  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79342
79343  pIn1 = &aMem[pOp->p1];
79344  if( pIn1->flags & MEM_Null ){
79345    v1 = 2;
79346  }else{
79347    v1 = sqlite3VdbeIntValue(pIn1)!=0;
79348  }
79349  pIn2 = &aMem[pOp->p2];
79350  if( pIn2->flags & MEM_Null ){
79351    v2 = 2;
79352  }else{
79353    v2 = sqlite3VdbeIntValue(pIn2)!=0;
79354  }
79355  if( pOp->opcode==OP_And ){
79356    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
79357    v1 = and_logic[v1*3+v2];
79358  }else{
79359    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
79360    v1 = or_logic[v1*3+v2];
79361  }
79362  pOut = &aMem[pOp->p3];
79363  if( v1==2 ){
79364    MemSetTypeFlag(pOut, MEM_Null);
79365  }else{
79366    pOut->u.i = v1;
79367    MemSetTypeFlag(pOut, MEM_Int);
79368  }
79369  break;
79370}
79371
79372/* Opcode: Not P1 P2 * * *
79373** Synopsis: r[P2]= !r[P1]
79374**
79375** Interpret the value in register P1 as a boolean value.  Store the
79376** boolean complement in register P2.  If the value in register P1 is
79377** NULL, then a NULL is stored in P2.
79378*/
79379case OP_Not: {                /* same as TK_NOT, in1, out2 */
79380  pIn1 = &aMem[pOp->p1];
79381  pOut = &aMem[pOp->p2];
79382  sqlite3VdbeMemSetNull(pOut);
79383  if( (pIn1->flags & MEM_Null)==0 ){
79384    pOut->flags = MEM_Int;
79385    pOut->u.i = !sqlite3VdbeIntValue(pIn1);
79386  }
79387  break;
79388}
79389
79390/* Opcode: BitNot P1 P2 * * *
79391** Synopsis: r[P1]= ~r[P1]
79392**
79393** Interpret the content of register P1 as an integer.  Store the
79394** ones-complement of the P1 value into register P2.  If P1 holds
79395** a NULL then store a NULL in P2.
79396*/
79397case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
79398  pIn1 = &aMem[pOp->p1];
79399  pOut = &aMem[pOp->p2];
79400  sqlite3VdbeMemSetNull(pOut);
79401  if( (pIn1->flags & MEM_Null)==0 ){
79402    pOut->flags = MEM_Int;
79403    pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
79404  }
79405  break;
79406}
79407
79408/* Opcode: Once P1 P2 * * *
79409**
79410** Check the "once" flag number P1. If it is set, jump to instruction P2.
79411** Otherwise, set the flag and fall through to the next instruction.
79412** In other words, this opcode causes all following opcodes up through P2
79413** (but not including P2) to run just once and to be skipped on subsequent
79414** times through the loop.
79415**
79416** All "once" flags are initially cleared whenever a prepared statement
79417** first begins to run.
79418*/
79419case OP_Once: {             /* jump */
79420  assert( pOp->p1<p->nOnceFlag );
79421  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
79422  if( p->aOnceFlag[pOp->p1] ){
79423    goto jump_to_p2;
79424  }else{
79425    p->aOnceFlag[pOp->p1] = 1;
79426  }
79427  break;
79428}
79429
79430/* Opcode: If P1 P2 P3 * *
79431**
79432** Jump to P2 if the value in register P1 is true.  The value
79433** is considered true if it is numeric and non-zero.  If the value
79434** in P1 is NULL then take the jump if and only if P3 is non-zero.
79435*/
79436/* Opcode: IfNot P1 P2 P3 * *
79437**
79438** Jump to P2 if the value in register P1 is False.  The value
79439** is considered false if it has a numeric value of zero.  If the value
79440** in P1 is NULL then take the jump if and only if P3 is non-zero.
79441*/
79442case OP_If:                 /* jump, in1 */
79443case OP_IfNot: {            /* jump, in1 */
79444  int c;
79445  pIn1 = &aMem[pOp->p1];
79446  if( pIn1->flags & MEM_Null ){
79447    c = pOp->p3;
79448  }else{
79449#ifdef SQLITE_OMIT_FLOATING_POINT
79450    c = sqlite3VdbeIntValue(pIn1)!=0;
79451#else
79452    c = sqlite3VdbeRealValue(pIn1)!=0.0;
79453#endif
79454    if( pOp->opcode==OP_IfNot ) c = !c;
79455  }
79456  VdbeBranchTaken(c!=0, 2);
79457  if( c ){
79458    goto jump_to_p2;
79459  }
79460  break;
79461}
79462
79463/* Opcode: IsNull P1 P2 * * *
79464** Synopsis:  if r[P1]==NULL goto P2
79465**
79466** Jump to P2 if the value in register P1 is NULL.
79467*/
79468case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
79469  pIn1 = &aMem[pOp->p1];
79470  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
79471  if( (pIn1->flags & MEM_Null)!=0 ){
79472    goto jump_to_p2;
79473  }
79474  break;
79475}
79476
79477/* Opcode: NotNull P1 P2 * * *
79478** Synopsis: if r[P1]!=NULL goto P2
79479**
79480** Jump to P2 if the value in register P1 is not NULL.
79481*/
79482case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
79483  pIn1 = &aMem[pOp->p1];
79484  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
79485  if( (pIn1->flags & MEM_Null)==0 ){
79486    goto jump_to_p2;
79487  }
79488  break;
79489}
79490
79491/* Opcode: Column P1 P2 P3 P4 P5
79492** Synopsis:  r[P3]=PX
79493**
79494** Interpret the data that cursor P1 points to as a structure built using
79495** the MakeRecord instruction.  (See the MakeRecord opcode for additional
79496** information about the format of the data.)  Extract the P2-th column
79497** from this record.  If there are less that (P2+1)
79498** values in the record, extract a NULL.
79499**
79500** The value extracted is stored in register P3.
79501**
79502** If the column contains fewer than P2 fields, then extract a NULL.  Or,
79503** if the P4 argument is a P4_MEM use the value of the P4 argument as
79504** the result.
79505**
79506** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
79507** then the cache of the cursor is reset prior to extracting the column.
79508** The first OP_Column against a pseudo-table after the value of the content
79509** register has changed should have this bit set.
79510**
79511** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
79512** the result is guaranteed to only be used as the argument of a length()
79513** or typeof() function, respectively.  The loading of large blobs can be
79514** skipped for length() and all content loading can be skipped for typeof().
79515*/
79516case OP_Column: {
79517  int p2;            /* column number to retrieve */
79518  VdbeCursor *pC;    /* The VDBE cursor */
79519  BtCursor *pCrsr;   /* The BTree cursor */
79520  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
79521  int len;           /* The length of the serialized data for the column */
79522  int i;             /* Loop counter */
79523  Mem *pDest;        /* Where to write the extracted value */
79524  Mem sMem;          /* For storing the record being decoded */
79525  const u8 *zData;   /* Part of the record being decoded */
79526  const u8 *zHdr;    /* Next unparsed byte of the header */
79527  const u8 *zEndHdr; /* Pointer to first byte after the header */
79528  u32 offset;        /* Offset into the data */
79529  u64 offset64;      /* 64-bit offset */
79530  u32 avail;         /* Number of bytes of available data */
79531  u32 t;             /* A type code from the record header */
79532  Mem *pReg;         /* PseudoTable input register */
79533
79534  pC = p->apCsr[pOp->p1];
79535  p2 = pOp->p2;
79536
79537  /* If the cursor cache is stale, bring it up-to-date */
79538  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
79539  if( rc ) goto abort_due_to_error;
79540
79541  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79542  pDest = &aMem[pOp->p3];
79543  memAboutToChange(p, pDest);
79544  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
79545  assert( pC!=0 );
79546  assert( p2<pC->nField );
79547  aOffset = pC->aOffset;
79548  assert( pC->eCurType!=CURTYPE_VTAB );
79549  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
79550  assert( pC->eCurType!=CURTYPE_SORTER );
79551  pCrsr = pC->uc.pCursor;
79552
79553  if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
79554    if( pC->nullRow ){
79555      if( pC->eCurType==CURTYPE_PSEUDO ){
79556        assert( pC->uc.pseudoTableReg>0 );
79557        pReg = &aMem[pC->uc.pseudoTableReg];
79558        assert( pReg->flags & MEM_Blob );
79559        assert( memIsValid(pReg) );
79560        pC->payloadSize = pC->szRow = avail = pReg->n;
79561        pC->aRow = (u8*)pReg->z;
79562      }else{
79563        sqlite3VdbeMemSetNull(pDest);
79564        goto op_column_out;
79565      }
79566    }else{
79567      assert( pC->eCurType==CURTYPE_BTREE );
79568      assert( pCrsr );
79569      assert( sqlite3BtreeCursorIsValid(pCrsr) );
79570      pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
79571      pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
79572      assert( avail<=65536 );  /* Maximum page size is 64KiB */
79573      if( pC->payloadSize <= (u32)avail ){
79574        pC->szRow = pC->payloadSize;
79575      }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
79576        goto too_big;
79577      }else{
79578        pC->szRow = avail;
79579      }
79580    }
79581    pC->cacheStatus = p->cacheCtr;
79582    pC->iHdrOffset = getVarint32(pC->aRow, offset);
79583    pC->nHdrParsed = 0;
79584    aOffset[0] = offset;
79585
79586
79587    if( avail<offset ){      /*OPTIMIZATION-IF-FALSE*/
79588      /* pC->aRow does not have to hold the entire row, but it does at least
79589      ** need to cover the header of the record.  If pC->aRow does not contain
79590      ** the complete header, then set it to zero, forcing the header to be
79591      ** dynamically allocated. */
79592      pC->aRow = 0;
79593      pC->szRow = 0;
79594
79595      /* Make sure a corrupt database has not given us an oversize header.
79596      ** Do this now to avoid an oversize memory allocation.
79597      **
79598      ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
79599      ** types use so much data space that there can only be 4096 and 32 of
79600      ** them, respectively.  So the maximum header length results from a
79601      ** 3-byte type for each of the maximum of 32768 columns plus three
79602      ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
79603      */
79604      if( offset > 98307 || offset > pC->payloadSize ){
79605        rc = SQLITE_CORRUPT_BKPT;
79606        goto abort_due_to_error;
79607      }
79608    }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
79609      /* The following goto is an optimization.  It can be omitted and
79610      ** everything will still work.  But OP_Column is measurably faster
79611      ** by skipping the subsequent conditional, which is always true.
79612      */
79613      zData = pC->aRow;
79614      assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
79615      goto op_column_read_header;
79616    }
79617  }
79618
79619  /* Make sure at least the first p2+1 entries of the header have been
79620  ** parsed and valid information is in aOffset[] and pC->aType[].
79621  */
79622  if( pC->nHdrParsed<=p2 ){
79623    /* If there is more header available for parsing in the record, try
79624    ** to extract additional fields up through the p2+1-th field
79625    */
79626    if( pC->iHdrOffset<aOffset[0] ){
79627      /* Make sure zData points to enough of the record to cover the header. */
79628      if( pC->aRow==0 ){
79629        memset(&sMem, 0, sizeof(sMem));
79630        rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
79631        if( rc!=SQLITE_OK ) goto abort_due_to_error;
79632        zData = (u8*)sMem.z;
79633      }else{
79634        zData = pC->aRow;
79635      }
79636
79637      /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
79638    op_column_read_header:
79639      i = pC->nHdrParsed;
79640      offset64 = aOffset[i];
79641      zHdr = zData + pC->iHdrOffset;
79642      zEndHdr = zData + aOffset[0];
79643      do{
79644        if( (t = zHdr[0])<0x80 ){
79645          zHdr++;
79646          offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
79647        }else{
79648          zHdr += sqlite3GetVarint32(zHdr, &t);
79649          offset64 += sqlite3VdbeSerialTypeLen(t);
79650        }
79651        pC->aType[i++] = t;
79652        aOffset[i] = (u32)(offset64 & 0xffffffff);
79653      }while( i<=p2 && zHdr<zEndHdr );
79654
79655      /* The record is corrupt if any of the following are true:
79656      ** (1) the bytes of the header extend past the declared header size
79657      ** (2) the entire header was used but not all data was used
79658      ** (3) the end of the data extends beyond the end of the record.
79659      */
79660      if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
79661       || (offset64 > pC->payloadSize)
79662      ){
79663        if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79664        rc = SQLITE_CORRUPT_BKPT;
79665        goto abort_due_to_error;
79666      }
79667
79668      pC->nHdrParsed = i;
79669      pC->iHdrOffset = (u32)(zHdr - zData);
79670      if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79671    }else{
79672      t = 0;
79673    }
79674
79675    /* If after trying to extract new entries from the header, nHdrParsed is
79676    ** still not up to p2, that means that the record has fewer than p2
79677    ** columns.  So the result will be either the default value or a NULL.
79678    */
79679    if( pC->nHdrParsed<=p2 ){
79680      if( pOp->p4type==P4_MEM ){
79681        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
79682      }else{
79683        sqlite3VdbeMemSetNull(pDest);
79684      }
79685      goto op_column_out;
79686    }
79687  }else{
79688    t = pC->aType[p2];
79689  }
79690
79691  /* Extract the content for the p2+1-th column.  Control can only
79692  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
79693  ** all valid.
79694  */
79695  assert( p2<pC->nHdrParsed );
79696  assert( rc==SQLITE_OK );
79697  assert( sqlite3VdbeCheckMemInvariants(pDest) );
79698  if( VdbeMemDynamic(pDest) ){
79699    sqlite3VdbeMemSetNull(pDest);
79700  }
79701  assert( t==pC->aType[p2] );
79702  if( pC->szRow>=aOffset[p2+1] ){
79703    /* This is the common case where the desired content fits on the original
79704    ** page - where the content is not on an overflow page */
79705    zData = pC->aRow + aOffset[p2];
79706    if( t<12 ){
79707      sqlite3VdbeSerialGet(zData, t, pDest);
79708    }else{
79709      /* If the column value is a string, we need a persistent value, not
79710      ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
79711      ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
79712      */
79713      static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
79714      pDest->n = len = (t-12)/2;
79715      pDest->enc = encoding;
79716      if( pDest->szMalloc < len+2 ){
79717        pDest->flags = MEM_Null;
79718        if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
79719      }else{
79720        pDest->z = pDest->zMalloc;
79721      }
79722      memcpy(pDest->z, zData, len);
79723      pDest->z[len] = 0;
79724      pDest->z[len+1] = 0;
79725      pDest->flags = aFlag[t&1];
79726    }
79727  }else{
79728    pDest->enc = encoding;
79729    /* This branch happens only when content is on overflow pages */
79730    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
79731          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
79732     || (len = sqlite3VdbeSerialTypeLen(t))==0
79733    ){
79734      /* Content is irrelevant for
79735      **    1. the typeof() function,
79736      **    2. the length(X) function if X is a blob, and
79737      **    3. if the content length is zero.
79738      ** So we might as well use bogus content rather than reading
79739      ** content from disk. */
79740      static u8 aZero[8];  /* This is the bogus content */
79741      sqlite3VdbeSerialGet(aZero, t, pDest);
79742    }else{
79743      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
79744                                   pDest);
79745      if( rc!=SQLITE_OK ) goto abort_due_to_error;
79746      sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
79747      pDest->flags &= ~MEM_Ephem;
79748    }
79749  }
79750
79751op_column_out:
79752  UPDATE_MAX_BLOBSIZE(pDest);
79753  REGISTER_TRACE(pOp->p3, pDest);
79754  break;
79755}
79756
79757/* Opcode: Affinity P1 P2 * P4 *
79758** Synopsis: affinity(r[P1@P2])
79759**
79760** Apply affinities to a range of P2 registers starting with P1.
79761**
79762** P4 is a string that is P2 characters long. The nth character of the
79763** string indicates the column affinity that should be used for the nth
79764** memory cell in the range.
79765*/
79766case OP_Affinity: {
79767  const char *zAffinity;   /* The affinity to be applied */
79768  char cAff;               /* A single character of affinity */
79769
79770  zAffinity = pOp->p4.z;
79771  assert( zAffinity!=0 );
79772  assert( zAffinity[pOp->p2]==0 );
79773  pIn1 = &aMem[pOp->p1];
79774  while( (cAff = *(zAffinity++))!=0 ){
79775    assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
79776    assert( memIsValid(pIn1) );
79777    applyAffinity(pIn1, cAff, encoding);
79778    pIn1++;
79779  }
79780  break;
79781}
79782
79783/* Opcode: MakeRecord P1 P2 P3 P4 *
79784** Synopsis: r[P3]=mkrec(r[P1@P2])
79785**
79786** Convert P2 registers beginning with P1 into the [record format]
79787** use as a data record in a database table or as a key
79788** in an index.  The OP_Column opcode can decode the record later.
79789**
79790** P4 may be a string that is P2 characters long.  The nth character of the
79791** string indicates the column affinity that should be used for the nth
79792** field of the index key.
79793**
79794** The mapping from character to affinity is given by the SQLITE_AFF_
79795** macros defined in sqliteInt.h.
79796**
79797** If P4 is NULL then all index fields have the affinity BLOB.
79798*/
79799case OP_MakeRecord: {
79800  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
79801  Mem *pRec;             /* The new record */
79802  u64 nData;             /* Number of bytes of data space */
79803  int nHdr;              /* Number of bytes of header space */
79804  i64 nByte;             /* Data space required for this record */
79805  i64 nZero;             /* Number of zero bytes at the end of the record */
79806  int nVarint;           /* Number of bytes in a varint */
79807  u32 serial_type;       /* Type field */
79808  Mem *pData0;           /* First field to be combined into the record */
79809  Mem *pLast;            /* Last field of the record */
79810  int nField;            /* Number of fields in the record */
79811  char *zAffinity;       /* The affinity string for the record */
79812  int file_format;       /* File format to use for encoding */
79813  int i;                 /* Space used in zNewRecord[] header */
79814  int j;                 /* Space used in zNewRecord[] content */
79815  u32 len;               /* Length of a field */
79816
79817  /* Assuming the record contains N fields, the record format looks
79818  ** like this:
79819  **
79820  ** ------------------------------------------------------------------------
79821  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
79822  ** ------------------------------------------------------------------------
79823  **
79824  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
79825  ** and so forth.
79826  **
79827  ** Each type field is a varint representing the serial type of the
79828  ** corresponding data element (see sqlite3VdbeSerialType()). The
79829  ** hdr-size field is also a varint which is the offset from the beginning
79830  ** of the record to data0.
79831  */
79832  nData = 0;         /* Number of bytes of data space */
79833  nHdr = 0;          /* Number of bytes of header space */
79834  nZero = 0;         /* Number of zero bytes at the end of the record */
79835  nField = pOp->p1;
79836  zAffinity = pOp->p4.z;
79837  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
79838  pData0 = &aMem[nField];
79839  nField = pOp->p2;
79840  pLast = &pData0[nField-1];
79841  file_format = p->minWriteFileFormat;
79842
79843  /* Identify the output register */
79844  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
79845  pOut = &aMem[pOp->p3];
79846  memAboutToChange(p, pOut);
79847
79848  /* Apply the requested affinity to all inputs
79849  */
79850  assert( pData0<=pLast );
79851  if( zAffinity ){
79852    pRec = pData0;
79853    do{
79854      applyAffinity(pRec++, *(zAffinity++), encoding);
79855      assert( zAffinity[0]==0 || pRec<=pLast );
79856    }while( zAffinity[0] );
79857  }
79858
79859  /* Loop through the elements that will make up the record to figure
79860  ** out how much space is required for the new record.
79861  */
79862  pRec = pLast;
79863  do{
79864    assert( memIsValid(pRec) );
79865    pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
79866    if( pRec->flags & MEM_Zero ){
79867      if( nData ){
79868        if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
79869      }else{
79870        nZero += pRec->u.nZero;
79871        len -= pRec->u.nZero;
79872      }
79873    }
79874    nData += len;
79875    testcase( serial_type==127 );
79876    testcase( serial_type==128 );
79877    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
79878    if( pRec==pData0 ) break;
79879    pRec--;
79880  }while(1);
79881
79882  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
79883  ** which determines the total number of bytes in the header. The varint
79884  ** value is the size of the header in bytes including the size varint
79885  ** itself. */
79886  testcase( nHdr==126 );
79887  testcase( nHdr==127 );
79888  if( nHdr<=126 ){
79889    /* The common case */
79890    nHdr += 1;
79891  }else{
79892    /* Rare case of a really large header */
79893    nVarint = sqlite3VarintLen(nHdr);
79894    nHdr += nVarint;
79895    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
79896  }
79897  nByte = nHdr+nData;
79898  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79899    goto too_big;
79900  }
79901
79902  /* Make sure the output register has a buffer large enough to store
79903  ** the new record. The output register (pOp->p3) is not allowed to
79904  ** be one of the input registers (because the following call to
79905  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
79906  */
79907  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
79908    goto no_mem;
79909  }
79910  zNewRecord = (u8 *)pOut->z;
79911
79912  /* Write the record */
79913  i = putVarint32(zNewRecord, nHdr);
79914  j = nHdr;
79915  assert( pData0<=pLast );
79916  pRec = pData0;
79917  do{
79918    serial_type = pRec->uTemp;
79919    /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
79920    ** additional varints, one per column. */
79921    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
79922    /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
79923    ** immediately follow the header. */
79924    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
79925  }while( (++pRec)<=pLast );
79926  assert( i==nHdr );
79927  assert( j==nByte );
79928
79929  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79930  pOut->n = (int)nByte;
79931  pOut->flags = MEM_Blob;
79932  if( nZero ){
79933    pOut->u.nZero = nZero;
79934    pOut->flags |= MEM_Zero;
79935  }
79936  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
79937  REGISTER_TRACE(pOp->p3, pOut);
79938  UPDATE_MAX_BLOBSIZE(pOut);
79939  break;
79940}
79941
79942/* Opcode: Count P1 P2 * * *
79943** Synopsis: r[P2]=count()
79944**
79945** Store the number of entries (an integer value) in the table or index
79946** opened by cursor P1 in register P2
79947*/
79948#ifndef SQLITE_OMIT_BTREECOUNT
79949case OP_Count: {         /* out2 */
79950  i64 nEntry;
79951  BtCursor *pCrsr;
79952
79953  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
79954  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
79955  assert( pCrsr );
79956  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
79957  rc = sqlite3BtreeCount(pCrsr, &nEntry);
79958  if( rc ) goto abort_due_to_error;
79959  pOut = out2Prerelease(p, pOp);
79960  pOut->u.i = nEntry;
79961  break;
79962}
79963#endif
79964
79965/* Opcode: Savepoint P1 * * P4 *
79966**
79967** Open, release or rollback the savepoint named by parameter P4, depending
79968** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
79969** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
79970*/
79971case OP_Savepoint: {
79972  int p1;                         /* Value of P1 operand */
79973  char *zName;                    /* Name of savepoint */
79974  int nName;
79975  Savepoint *pNew;
79976  Savepoint *pSavepoint;
79977  Savepoint *pTmp;
79978  int iSavepoint;
79979  int ii;
79980
79981  p1 = pOp->p1;
79982  zName = pOp->p4.z;
79983
79984  /* Assert that the p1 parameter is valid. Also that if there is no open
79985  ** transaction, then there cannot be any savepoints.
79986  */
79987  assert( db->pSavepoint==0 || db->autoCommit==0 );
79988  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
79989  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
79990  assert( checkSavepointCount(db) );
79991  assert( p->bIsReader );
79992
79993  if( p1==SAVEPOINT_BEGIN ){
79994    if( db->nVdbeWrite>0 ){
79995      /* A new savepoint cannot be created if there are active write
79996      ** statements (i.e. open read/write incremental blob handles).
79997      */
79998      sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
79999      rc = SQLITE_BUSY;
80000    }else{
80001      nName = sqlite3Strlen30(zName);
80002
80003#ifndef SQLITE_OMIT_VIRTUALTABLE
80004      /* This call is Ok even if this savepoint is actually a transaction
80005      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
80006      ** If this is a transaction savepoint being opened, it is guaranteed
80007      ** that the db->aVTrans[] array is empty.  */
80008      assert( db->autoCommit==0 || db->nVTrans==0 );
80009      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
80010                                db->nStatement+db->nSavepoint);
80011      if( rc!=SQLITE_OK ) goto abort_due_to_error;
80012#endif
80013
80014      /* Create a new savepoint structure. */
80015      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
80016      if( pNew ){
80017        pNew->zName = (char *)&pNew[1];
80018        memcpy(pNew->zName, zName, nName+1);
80019
80020        /* If there is no open transaction, then mark this as a special
80021        ** "transaction savepoint". */
80022        if( db->autoCommit ){
80023          db->autoCommit = 0;
80024          db->isTransactionSavepoint = 1;
80025        }else{
80026          db->nSavepoint++;
80027        }
80028
80029        /* Link the new savepoint into the database handle's list. */
80030        pNew->pNext = db->pSavepoint;
80031        db->pSavepoint = pNew;
80032        pNew->nDeferredCons = db->nDeferredCons;
80033        pNew->nDeferredImmCons = db->nDeferredImmCons;
80034      }
80035    }
80036  }else{
80037    iSavepoint = 0;
80038
80039    /* Find the named savepoint. If there is no such savepoint, then an
80040    ** an error is returned to the user.  */
80041    for(
80042      pSavepoint = db->pSavepoint;
80043      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
80044      pSavepoint = pSavepoint->pNext
80045    ){
80046      iSavepoint++;
80047    }
80048    if( !pSavepoint ){
80049      sqlite3VdbeError(p, "no such savepoint: %s", zName);
80050      rc = SQLITE_ERROR;
80051    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
80052      /* It is not possible to release (commit) a savepoint if there are
80053      ** active write statements.
80054      */
80055      sqlite3VdbeError(p, "cannot release savepoint - "
80056                          "SQL statements in progress");
80057      rc = SQLITE_BUSY;
80058    }else{
80059
80060      /* Determine whether or not this is a transaction savepoint. If so,
80061      ** and this is a RELEASE command, then the current transaction
80062      ** is committed.
80063      */
80064      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
80065      if( isTransaction && p1==SAVEPOINT_RELEASE ){
80066        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80067          goto vdbe_return;
80068        }
80069        db->autoCommit = 1;
80070        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80071          p->pc = (int)(pOp - aOp);
80072          db->autoCommit = 0;
80073          p->rc = rc = SQLITE_BUSY;
80074          goto vdbe_return;
80075        }
80076        db->isTransactionSavepoint = 0;
80077        rc = p->rc;
80078      }else{
80079        int isSchemaChange;
80080        iSavepoint = db->nSavepoint - iSavepoint - 1;
80081        if( p1==SAVEPOINT_ROLLBACK ){
80082          isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
80083          for(ii=0; ii<db->nDb; ii++){
80084            rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
80085                                       SQLITE_ABORT_ROLLBACK,
80086                                       isSchemaChange==0);
80087            if( rc!=SQLITE_OK ) goto abort_due_to_error;
80088          }
80089        }else{
80090          isSchemaChange = 0;
80091        }
80092        for(ii=0; ii<db->nDb; ii++){
80093          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
80094          if( rc!=SQLITE_OK ){
80095            goto abort_due_to_error;
80096          }
80097        }
80098        if( isSchemaChange ){
80099          sqlite3ExpirePreparedStatements(db);
80100          sqlite3ResetAllSchemasOfConnection(db);
80101          db->flags = (db->flags | SQLITE_InternChanges);
80102        }
80103      }
80104
80105      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
80106      ** savepoints nested inside of the savepoint being operated on. */
80107      while( db->pSavepoint!=pSavepoint ){
80108        pTmp = db->pSavepoint;
80109        db->pSavepoint = pTmp->pNext;
80110        sqlite3DbFree(db, pTmp);
80111        db->nSavepoint--;
80112      }
80113
80114      /* If it is a RELEASE, then destroy the savepoint being operated on
80115      ** too. If it is a ROLLBACK TO, then set the number of deferred
80116      ** constraint violations present in the database to the value stored
80117      ** when the savepoint was created.  */
80118      if( p1==SAVEPOINT_RELEASE ){
80119        assert( pSavepoint==db->pSavepoint );
80120        db->pSavepoint = pSavepoint->pNext;
80121        sqlite3DbFree(db, pSavepoint);
80122        if( !isTransaction ){
80123          db->nSavepoint--;
80124        }
80125      }else{
80126        db->nDeferredCons = pSavepoint->nDeferredCons;
80127        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
80128      }
80129
80130      if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
80131        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
80132        if( rc!=SQLITE_OK ) goto abort_due_to_error;
80133      }
80134    }
80135  }
80136  if( rc ) goto abort_due_to_error;
80137
80138  break;
80139}
80140
80141/* Opcode: AutoCommit P1 P2 * * *
80142**
80143** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
80144** back any currently active btree transactions. If there are any active
80145** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
80146** there are active writing VMs or active VMs that use shared cache.
80147**
80148** This instruction causes the VM to halt.
80149*/
80150case OP_AutoCommit: {
80151  int desiredAutoCommit;
80152  int iRollback;
80153
80154  desiredAutoCommit = pOp->p1;
80155  iRollback = pOp->p2;
80156  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
80157  assert( desiredAutoCommit==1 || iRollback==0 );
80158  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
80159  assert( p->bIsReader );
80160
80161  if( desiredAutoCommit!=db->autoCommit ){
80162    if( iRollback ){
80163      assert( desiredAutoCommit==1 );
80164      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
80165      db->autoCommit = 1;
80166    }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
80167      /* If this instruction implements a COMMIT and other VMs are writing
80168      ** return an error indicating that the other VMs must complete first.
80169      */
80170      sqlite3VdbeError(p, "cannot commit transaction - "
80171                          "SQL statements in progress");
80172      rc = SQLITE_BUSY;
80173      goto abort_due_to_error;
80174    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80175      goto vdbe_return;
80176    }else{
80177      db->autoCommit = (u8)desiredAutoCommit;
80178    }
80179    if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80180      p->pc = (int)(pOp - aOp);
80181      db->autoCommit = (u8)(1-desiredAutoCommit);
80182      p->rc = rc = SQLITE_BUSY;
80183      goto vdbe_return;
80184    }
80185    assert( db->nStatement==0 );
80186    sqlite3CloseSavepoints(db);
80187    if( p->rc==SQLITE_OK ){
80188      rc = SQLITE_DONE;
80189    }else{
80190      rc = SQLITE_ERROR;
80191    }
80192    goto vdbe_return;
80193  }else{
80194    sqlite3VdbeError(p,
80195        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
80196        (iRollback)?"cannot rollback - no transaction is active":
80197                   "cannot commit - no transaction is active"));
80198
80199    rc = SQLITE_ERROR;
80200    goto abort_due_to_error;
80201  }
80202  break;
80203}
80204
80205/* Opcode: Transaction P1 P2 P3 P4 P5
80206**
80207** Begin a transaction on database P1 if a transaction is not already
80208** active.
80209** If P2 is non-zero, then a write-transaction is started, or if a
80210** read-transaction is already active, it is upgraded to a write-transaction.
80211** If P2 is zero, then a read-transaction is started.
80212**
80213** P1 is the index of the database file on which the transaction is
80214** started.  Index 0 is the main database file and index 1 is the
80215** file used for temporary tables.  Indices of 2 or more are used for
80216** attached databases.
80217**
80218** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
80219** true (this flag is set if the Vdbe may modify more than one row and may
80220** throw an ABORT exception), a statement transaction may also be opened.
80221** More specifically, a statement transaction is opened iff the database
80222** connection is currently not in autocommit mode, or if there are other
80223** active statements. A statement transaction allows the changes made by this
80224** VDBE to be rolled back after an error without having to roll back the
80225** entire transaction. If no error is encountered, the statement transaction
80226** will automatically commit when the VDBE halts.
80227**
80228** If P5!=0 then this opcode also checks the schema cookie against P3
80229** and the schema generation counter against P4.
80230** The cookie changes its value whenever the database schema changes.
80231** This operation is used to detect when that the cookie has changed
80232** and that the current process needs to reread the schema.  If the schema
80233** cookie in P3 differs from the schema cookie in the database header or
80234** if the schema generation counter in P4 differs from the current
80235** generation counter, then an SQLITE_SCHEMA error is raised and execution
80236** halts.  The sqlite3_step() wrapper function might then reprepare the
80237** statement and rerun it from the beginning.
80238*/
80239case OP_Transaction: {
80240  Btree *pBt;
80241  int iMeta;
80242  int iGen;
80243
80244  assert( p->bIsReader );
80245  assert( p->readOnly==0 || pOp->p2==0 );
80246  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80247  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80248  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
80249    rc = SQLITE_READONLY;
80250    goto abort_due_to_error;
80251  }
80252  pBt = db->aDb[pOp->p1].pBt;
80253
80254  if( pBt ){
80255    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
80256    testcase( rc==SQLITE_BUSY_SNAPSHOT );
80257    testcase( rc==SQLITE_BUSY_RECOVERY );
80258    if( (rc&0xff)==SQLITE_BUSY ){
80259      p->pc = (int)(pOp - aOp);
80260      p->rc = rc;
80261      goto vdbe_return;
80262    }
80263    if( rc!=SQLITE_OK ){
80264      goto abort_due_to_error;
80265    }
80266
80267    if( pOp->p2 && p->usesStmtJournal
80268     && (db->autoCommit==0 || db->nVdbeRead>1)
80269    ){
80270      assert( sqlite3BtreeIsInTrans(pBt) );
80271      if( p->iStatement==0 ){
80272        assert( db->nStatement>=0 && db->nSavepoint>=0 );
80273        db->nStatement++;
80274        p->iStatement = db->nSavepoint + db->nStatement;
80275      }
80276
80277      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
80278      if( rc==SQLITE_OK ){
80279        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
80280      }
80281
80282      /* Store the current value of the database handles deferred constraint
80283      ** counter. If the statement transaction needs to be rolled back,
80284      ** the value of this counter needs to be restored too.  */
80285      p->nStmtDefCons = db->nDeferredCons;
80286      p->nStmtDefImmCons = db->nDeferredImmCons;
80287    }
80288
80289    /* Gather the schema version number for checking:
80290    ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
80291    ** each time a query is executed to ensure that the internal cache of the
80292    ** schema used when compiling the SQL query matches the schema of the
80293    ** database against which the compiled query is actually executed.
80294    */
80295    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
80296    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
80297  }else{
80298    iGen = iMeta = 0;
80299  }
80300  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
80301  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
80302    sqlite3DbFree(db, p->zErrMsg);
80303    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
80304    /* If the schema-cookie from the database file matches the cookie
80305    ** stored with the in-memory representation of the schema, do
80306    ** not reload the schema from the database file.
80307    **
80308    ** If virtual-tables are in use, this is not just an optimization.
80309    ** Often, v-tables store their data in other SQLite tables, which
80310    ** are queried from within xNext() and other v-table methods using
80311    ** prepared queries. If such a query is out-of-date, we do not want to
80312    ** discard the database schema, as the user code implementing the
80313    ** v-table would have to be ready for the sqlite3_vtab structure itself
80314    ** to be invalidated whenever sqlite3_step() is called from within
80315    ** a v-table method.
80316    */
80317    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
80318      sqlite3ResetOneSchema(db, pOp->p1);
80319    }
80320    p->expired = 1;
80321    rc = SQLITE_SCHEMA;
80322  }
80323  if( rc ) goto abort_due_to_error;
80324  break;
80325}
80326
80327/* Opcode: ReadCookie P1 P2 P3 * *
80328**
80329** Read cookie number P3 from database P1 and write it into register P2.
80330** P3==1 is the schema version.  P3==2 is the database format.
80331** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
80332** the main database file and P1==1 is the database file used to store
80333** temporary tables.
80334**
80335** There must be a read-lock on the database (either a transaction
80336** must be started or there must be an open cursor) before
80337** executing this instruction.
80338*/
80339case OP_ReadCookie: {               /* out2 */
80340  int iMeta;
80341  int iDb;
80342  int iCookie;
80343
80344  assert( p->bIsReader );
80345  iDb = pOp->p1;
80346  iCookie = pOp->p3;
80347  assert( pOp->p3<SQLITE_N_BTREE_META );
80348  assert( iDb>=0 && iDb<db->nDb );
80349  assert( db->aDb[iDb].pBt!=0 );
80350  assert( DbMaskTest(p->btreeMask, iDb) );
80351
80352  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
80353  pOut = out2Prerelease(p, pOp);
80354  pOut->u.i = iMeta;
80355  break;
80356}
80357
80358/* Opcode: SetCookie P1 P2 P3 * *
80359**
80360** Write the integer value P3 into cookie number P2 of database P1.
80361** P2==1 is the schema version.  P2==2 is the database format.
80362** P2==3 is the recommended pager cache
80363** size, and so forth.  P1==0 is the main database file and P1==1 is the
80364** database file used to store temporary tables.
80365**
80366** A transaction must be started before executing this opcode.
80367*/
80368case OP_SetCookie: {
80369  Db *pDb;
80370  assert( pOp->p2<SQLITE_N_BTREE_META );
80371  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80372  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80373  assert( p->readOnly==0 );
80374  pDb = &db->aDb[pOp->p1];
80375  assert( pDb->pBt!=0 );
80376  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
80377  /* See note about index shifting on OP_ReadCookie */
80378  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
80379  if( pOp->p2==BTREE_SCHEMA_VERSION ){
80380    /* When the schema cookie changes, record the new cookie internally */
80381    pDb->pSchema->schema_cookie = pOp->p3;
80382    db->flags |= SQLITE_InternChanges;
80383  }else if( pOp->p2==BTREE_FILE_FORMAT ){
80384    /* Record changes in the file format */
80385    pDb->pSchema->file_format = pOp->p3;
80386  }
80387  if( pOp->p1==1 ){
80388    /* Invalidate all prepared statements whenever the TEMP database
80389    ** schema is changed.  Ticket #1644 */
80390    sqlite3ExpirePreparedStatements(db);
80391    p->expired = 0;
80392  }
80393  if( rc ) goto abort_due_to_error;
80394  break;
80395}
80396
80397/* Opcode: OpenRead P1 P2 P3 P4 P5
80398** Synopsis: root=P2 iDb=P3
80399**
80400** Open a read-only cursor for the database table whose root page is
80401** P2 in a database file.  The database file is determined by P3.
80402** P3==0 means the main database, P3==1 means the database used for
80403** temporary tables, and P3>1 means used the corresponding attached
80404** database.  Give the new cursor an identifier of P1.  The P1
80405** values need not be contiguous but all P1 values should be small integers.
80406** It is an error for P1 to be negative.
80407**
80408** If P5!=0 then use the content of register P2 as the root page, not
80409** the value of P2 itself.
80410**
80411** There will be a read lock on the database whenever there is an
80412** open cursor.  If the database was unlocked prior to this instruction
80413** then a read lock is acquired as part of this instruction.  A read
80414** lock allows other processes to read the database but prohibits
80415** any other process from modifying the database.  The read lock is
80416** released when all cursors are closed.  If this instruction attempts
80417** to get a read lock but fails, the script terminates with an
80418** SQLITE_BUSY error code.
80419**
80420** The P4 value may be either an integer (P4_INT32) or a pointer to
80421** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80422** structure, then said structure defines the content and collating
80423** sequence of the index being opened. Otherwise, if P4 is an integer
80424** value, it is set to the number of columns in the table.
80425**
80426** See also: OpenWrite, ReopenIdx
80427*/
80428/* Opcode: ReopenIdx P1 P2 P3 P4 P5
80429** Synopsis: root=P2 iDb=P3
80430**
80431** The ReopenIdx opcode works exactly like ReadOpen except that it first
80432** checks to see if the cursor on P1 is already open with a root page
80433** number of P2 and if it is this opcode becomes a no-op.  In other words,
80434** if the cursor is already open, do not reopen it.
80435**
80436** The ReopenIdx opcode may only be used with P5==0 and with P4 being
80437** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
80438** every other ReopenIdx or OpenRead for the same cursor number.
80439**
80440** See the OpenRead opcode documentation for additional information.
80441*/
80442/* Opcode: OpenWrite P1 P2 P3 P4 P5
80443** Synopsis: root=P2 iDb=P3
80444**
80445** Open a read/write cursor named P1 on the table or index whose root
80446** page is P2.  Or if P5!=0 use the content of register P2 to find the
80447** root page.
80448**
80449** The P4 value may be either an integer (P4_INT32) or a pointer to
80450** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80451** structure, then said structure defines the content and collating
80452** sequence of the index being opened. Otherwise, if P4 is an integer
80453** value, it is set to the number of columns in the table, or to the
80454** largest index of any column of the table that is actually used.
80455**
80456** This instruction works just like OpenRead except that it opens the cursor
80457** in read/write mode.  For a given table, there can be one or more read-only
80458** cursors or a single read/write cursor but not both.
80459**
80460** See also OpenRead.
80461*/
80462case OP_ReopenIdx: {
80463  int nField;
80464  KeyInfo *pKeyInfo;
80465  int p2;
80466  int iDb;
80467  int wrFlag;
80468  Btree *pX;
80469  VdbeCursor *pCur;
80470  Db *pDb;
80471
80472  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80473  assert( pOp->p4type==P4_KEYINFO );
80474  pCur = p->apCsr[pOp->p1];
80475  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
80476    assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
80477    goto open_cursor_set_hints;
80478  }
80479  /* If the cursor is not currently open or is open on a different
80480  ** index, then fall through into OP_OpenRead to force a reopen */
80481case OP_OpenRead:
80482case OP_OpenWrite:
80483
80484  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80485  assert( p->bIsReader );
80486  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
80487          || p->readOnly==0 );
80488
80489  if( p->expired ){
80490    rc = SQLITE_ABORT_ROLLBACK;
80491    goto abort_due_to_error;
80492  }
80493
80494  nField = 0;
80495  pKeyInfo = 0;
80496  p2 = pOp->p2;
80497  iDb = pOp->p3;
80498  assert( iDb>=0 && iDb<db->nDb );
80499  assert( DbMaskTest(p->btreeMask, iDb) );
80500  pDb = &db->aDb[iDb];
80501  pX = pDb->pBt;
80502  assert( pX!=0 );
80503  if( pOp->opcode==OP_OpenWrite ){
80504    assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
80505    wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
80506    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80507    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
80508      p->minWriteFileFormat = pDb->pSchema->file_format;
80509    }
80510  }else{
80511    wrFlag = 0;
80512  }
80513  if( pOp->p5 & OPFLAG_P2ISREG ){
80514    assert( p2>0 );
80515    assert( p2<=(p->nMem+1 - p->nCursor) );
80516    pIn2 = &aMem[p2];
80517    assert( memIsValid(pIn2) );
80518    assert( (pIn2->flags & MEM_Int)!=0 );
80519    sqlite3VdbeMemIntegerify(pIn2);
80520    p2 = (int)pIn2->u.i;
80521    /* The p2 value always comes from a prior OP_CreateTable opcode and
80522    ** that opcode will always set the p2 value to 2 or more or else fail.
80523    ** If there were a failure, the prepared statement would have halted
80524    ** before reaching this instruction. */
80525    assert( p2>=2 );
80526  }
80527  if( pOp->p4type==P4_KEYINFO ){
80528    pKeyInfo = pOp->p4.pKeyInfo;
80529    assert( pKeyInfo->enc==ENC(db) );
80530    assert( pKeyInfo->db==db );
80531    nField = pKeyInfo->nField+pKeyInfo->nXField;
80532  }else if( pOp->p4type==P4_INT32 ){
80533    nField = pOp->p4.i;
80534  }
80535  assert( pOp->p1>=0 );
80536  assert( nField>=0 );
80537  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
80538  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
80539  if( pCur==0 ) goto no_mem;
80540  pCur->nullRow = 1;
80541  pCur->isOrdered = 1;
80542  pCur->pgnoRoot = p2;
80543#ifdef SQLITE_DEBUG
80544  pCur->wrFlag = wrFlag;
80545#endif
80546  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
80547  pCur->pKeyInfo = pKeyInfo;
80548  /* Set the VdbeCursor.isTable variable. Previous versions of
80549  ** SQLite used to check if the root-page flags were sane at this point
80550  ** and report database corruption if they were not, but this check has
80551  ** since moved into the btree layer.  */
80552  pCur->isTable = pOp->p4type!=P4_KEYINFO;
80553
80554open_cursor_set_hints:
80555  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
80556  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
80557  testcase( pOp->p5 & OPFLAG_BULKCSR );
80558#ifdef SQLITE_ENABLE_CURSOR_HINTS
80559  testcase( pOp->p2 & OPFLAG_SEEKEQ );
80560#endif
80561  sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
80562                               (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
80563  if( rc ) goto abort_due_to_error;
80564  break;
80565}
80566
80567/* Opcode: OpenEphemeral P1 P2 * P4 P5
80568** Synopsis: nColumn=P2
80569**
80570** Open a new cursor P1 to a transient table.
80571** The cursor is always opened read/write even if
80572** the main database is read-only.  The ephemeral
80573** table is deleted automatically when the cursor is closed.
80574**
80575** P2 is the number of columns in the ephemeral table.
80576** The cursor points to a BTree table if P4==0 and to a BTree index
80577** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
80578** that defines the format of keys in the index.
80579**
80580** The P5 parameter can be a mask of the BTREE_* flags defined
80581** in btree.h.  These flags control aspects of the operation of
80582** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
80583** added automatically.
80584*/
80585/* Opcode: OpenAutoindex P1 P2 * P4 *
80586** Synopsis: nColumn=P2
80587**
80588** This opcode works the same as OP_OpenEphemeral.  It has a
80589** different name to distinguish its use.  Tables created using
80590** by this opcode will be used for automatically created transient
80591** indices in joins.
80592*/
80593case OP_OpenAutoindex:
80594case OP_OpenEphemeral: {
80595  VdbeCursor *pCx;
80596  KeyInfo *pKeyInfo;
80597
80598  static const int vfsFlags =
80599      SQLITE_OPEN_READWRITE |
80600      SQLITE_OPEN_CREATE |
80601      SQLITE_OPEN_EXCLUSIVE |
80602      SQLITE_OPEN_DELETEONCLOSE |
80603      SQLITE_OPEN_TRANSIENT_DB;
80604  assert( pOp->p1>=0 );
80605  assert( pOp->p2>=0 );
80606  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
80607  if( pCx==0 ) goto no_mem;
80608  pCx->nullRow = 1;
80609  pCx->isEphemeral = 1;
80610  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
80611                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
80612  if( rc==SQLITE_OK ){
80613    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
80614  }
80615  if( rc==SQLITE_OK ){
80616    /* If a transient index is required, create it by calling
80617    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
80618    ** opening it. If a transient table is required, just use the
80619    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
80620    */
80621    if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
80622      int pgno;
80623      assert( pOp->p4type==P4_KEYINFO );
80624      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
80625      if( rc==SQLITE_OK ){
80626        assert( pgno==MASTER_ROOT+1 );
80627        assert( pKeyInfo->db==db );
80628        assert( pKeyInfo->enc==ENC(db) );
80629        pCx->pKeyInfo = pKeyInfo;
80630        rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
80631                                pKeyInfo, pCx->uc.pCursor);
80632      }
80633      pCx->isTable = 0;
80634    }else{
80635      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
80636                              0, pCx->uc.pCursor);
80637      pCx->isTable = 1;
80638    }
80639  }
80640  if( rc ) goto abort_due_to_error;
80641  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
80642  break;
80643}
80644
80645/* Opcode: SorterOpen P1 P2 P3 P4 *
80646**
80647** This opcode works like OP_OpenEphemeral except that it opens
80648** a transient index that is specifically designed to sort large
80649** tables using an external merge-sort algorithm.
80650**
80651** If argument P3 is non-zero, then it indicates that the sorter may
80652** assume that a stable sort considering the first P3 fields of each
80653** key is sufficient to produce the required results.
80654*/
80655case OP_SorterOpen: {
80656  VdbeCursor *pCx;
80657
80658  assert( pOp->p1>=0 );
80659  assert( pOp->p2>=0 );
80660  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
80661  if( pCx==0 ) goto no_mem;
80662  pCx->pKeyInfo = pOp->p4.pKeyInfo;
80663  assert( pCx->pKeyInfo->db==db );
80664  assert( pCx->pKeyInfo->enc==ENC(db) );
80665  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
80666  if( rc ) goto abort_due_to_error;
80667  break;
80668}
80669
80670/* Opcode: SequenceTest P1 P2 * * *
80671** Synopsis: if( cursor[P1].ctr++ ) pc = P2
80672**
80673** P1 is a sorter cursor. If the sequence counter is currently zero, jump
80674** to P2. Regardless of whether or not the jump is taken, increment the
80675** the sequence value.
80676*/
80677case OP_SequenceTest: {
80678  VdbeCursor *pC;
80679  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80680  pC = p->apCsr[pOp->p1];
80681  assert( isSorter(pC) );
80682  if( (pC->seqCount++)==0 ){
80683    goto jump_to_p2;
80684  }
80685  break;
80686}
80687
80688/* Opcode: OpenPseudo P1 P2 P3 * *
80689** Synopsis: P3 columns in r[P2]
80690**
80691** Open a new cursor that points to a fake table that contains a single
80692** row of data.  The content of that one row is the content of memory
80693** register P2.  In other words, cursor P1 becomes an alias for the
80694** MEM_Blob content contained in register P2.
80695**
80696** A pseudo-table created by this opcode is used to hold a single
80697** row output from the sorter so that the row can be decomposed into
80698** individual columns using the OP_Column opcode.  The OP_Column opcode
80699** is the only cursor opcode that works with a pseudo-table.
80700**
80701** P3 is the number of fields in the records that will be stored by
80702** the pseudo-table.
80703*/
80704case OP_OpenPseudo: {
80705  VdbeCursor *pCx;
80706
80707  assert( pOp->p1>=0 );
80708  assert( pOp->p3>=0 );
80709  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
80710  if( pCx==0 ) goto no_mem;
80711  pCx->nullRow = 1;
80712  pCx->uc.pseudoTableReg = pOp->p2;
80713  pCx->isTable = 1;
80714  assert( pOp->p5==0 );
80715  break;
80716}
80717
80718/* Opcode: Close P1 * * * *
80719**
80720** Close a cursor previously opened as P1.  If P1 is not
80721** currently open, this instruction is a no-op.
80722*/
80723case OP_Close: {
80724  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80725  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
80726  p->apCsr[pOp->p1] = 0;
80727  break;
80728}
80729
80730#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
80731/* Opcode: ColumnsUsed P1 * * P4 *
80732**
80733** This opcode (which only exists if SQLite was compiled with
80734** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
80735** table or index for cursor P1 are used.  P4 is a 64-bit integer
80736** (P4_INT64) in which the first 63 bits are one for each of the
80737** first 63 columns of the table or index that are actually used
80738** by the cursor.  The high-order bit is set if any column after
80739** the 64th is used.
80740*/
80741case OP_ColumnsUsed: {
80742  VdbeCursor *pC;
80743  pC = p->apCsr[pOp->p1];
80744  assert( pC->eCurType==CURTYPE_BTREE );
80745  pC->maskUsed = *(u64*)pOp->p4.pI64;
80746  break;
80747}
80748#endif
80749
80750/* Opcode: SeekGE P1 P2 P3 P4 *
80751** Synopsis: key=r[P3@P4]
80752**
80753** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80754** use the value in register P3 as the key.  If cursor P1 refers
80755** to an SQL index, then P3 is the first in an array of P4 registers
80756** that are used as an unpacked index key.
80757**
80758** Reposition cursor P1 so that  it points to the smallest entry that
80759** is greater than or equal to the key value. If there are no records
80760** greater than or equal to the key and P2 is not zero, then jump to P2.
80761**
80762** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80763** opcode will always land on a record that equally equals the key, or
80764** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
80765** opcode must be followed by an IdxLE opcode with the same arguments.
80766** The IdxLE opcode will be skipped if this opcode succeeds, but the
80767** IdxLE opcode will be used on subsequent loop iterations.
80768**
80769** This opcode leaves the cursor configured to move in forward order,
80770** from the beginning toward the end.  In other words, the cursor is
80771** configured to use Next, not Prev.
80772**
80773** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
80774*/
80775/* Opcode: SeekGT P1 P2 P3 P4 *
80776** Synopsis: key=r[P3@P4]
80777**
80778** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80779** use the value in register P3 as a key. If cursor P1 refers
80780** to an SQL index, then P3 is the first in an array of P4 registers
80781** that are used as an unpacked index key.
80782**
80783** Reposition cursor P1 so that  it points to the smallest entry that
80784** is greater than the key value. If there are no records greater than
80785** the key and P2 is not zero, then jump to P2.
80786**
80787** This opcode leaves the cursor configured to move in forward order,
80788** from the beginning toward the end.  In other words, the cursor is
80789** configured to use Next, not Prev.
80790**
80791** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
80792*/
80793/* Opcode: SeekLT P1 P2 P3 P4 *
80794** Synopsis: key=r[P3@P4]
80795**
80796** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80797** use the value in register P3 as a key. If cursor P1 refers
80798** to an SQL index, then P3 is the first in an array of P4 registers
80799** that are used as an unpacked index key.
80800**
80801** Reposition cursor P1 so that  it points to the largest entry that
80802** is less than the key value. If there are no records less than
80803** the key and P2 is not zero, then jump to P2.
80804**
80805** This opcode leaves the cursor configured to move in reverse order,
80806** from the end toward the beginning.  In other words, the cursor is
80807** configured to use Prev, not Next.
80808**
80809** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
80810*/
80811/* Opcode: SeekLE P1 P2 P3 P4 *
80812** Synopsis: key=r[P3@P4]
80813**
80814** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80815** use the value in register P3 as a key. If cursor P1 refers
80816** to an SQL index, then P3 is the first in an array of P4 registers
80817** that are used as an unpacked index key.
80818**
80819** Reposition cursor P1 so that it points to the largest entry that
80820** is less than or equal to the key value. If there are no records
80821** less than or equal to the key and P2 is not zero, then jump to P2.
80822**
80823** This opcode leaves the cursor configured to move in reverse order,
80824** from the end toward the beginning.  In other words, the cursor is
80825** configured to use Prev, not Next.
80826**
80827** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80828** opcode will always land on a record that equally equals the key, or
80829** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
80830** opcode must be followed by an IdxGE opcode with the same arguments.
80831** The IdxGE opcode will be skipped if this opcode succeeds, but the
80832** IdxGE opcode will be used on subsequent loop iterations.
80833**
80834** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
80835*/
80836case OP_SeekLT:         /* jump, in3 */
80837case OP_SeekLE:         /* jump, in3 */
80838case OP_SeekGE:         /* jump, in3 */
80839case OP_SeekGT: {       /* jump, in3 */
80840  int res;           /* Comparison result */
80841  int oc;            /* Opcode */
80842  VdbeCursor *pC;    /* The cursor to seek */
80843  UnpackedRecord r;  /* The key to seek for */
80844  int nField;        /* Number of columns or fields in the key */
80845  i64 iKey;          /* The rowid we are to seek to */
80846  int eqOnly;        /* Only interested in == results */
80847
80848  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80849  assert( pOp->p2!=0 );
80850  pC = p->apCsr[pOp->p1];
80851  assert( pC!=0 );
80852  assert( pC->eCurType==CURTYPE_BTREE );
80853  assert( OP_SeekLE == OP_SeekLT+1 );
80854  assert( OP_SeekGE == OP_SeekLT+2 );
80855  assert( OP_SeekGT == OP_SeekLT+3 );
80856  assert( pC->isOrdered );
80857  assert( pC->uc.pCursor!=0 );
80858  oc = pOp->opcode;
80859  eqOnly = 0;
80860  pC->nullRow = 0;
80861#ifdef SQLITE_DEBUG
80862  pC->seekOp = pOp->opcode;
80863#endif
80864
80865  if( pC->isTable ){
80866    /* The BTREE_SEEK_EQ flag is only set on index cursors */
80867    assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 );
80868
80869    /* The input value in P3 might be of any type: integer, real, string,
80870    ** blob, or NULL.  But it needs to be an integer before we can do
80871    ** the seek, so convert it. */
80872    pIn3 = &aMem[pOp->p3];
80873    if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80874      applyNumericAffinity(pIn3, 0);
80875    }
80876    iKey = sqlite3VdbeIntValue(pIn3);
80877
80878    /* If the P3 value could not be converted into an integer without
80879    ** loss of information, then special processing is required... */
80880    if( (pIn3->flags & MEM_Int)==0 ){
80881      if( (pIn3->flags & MEM_Real)==0 ){
80882        /* If the P3 value cannot be converted into any kind of a number,
80883        ** then the seek is not possible, so jump to P2 */
80884        VdbeBranchTaken(1,2); goto jump_to_p2;
80885        break;
80886      }
80887
80888      /* If the approximation iKey is larger than the actual real search
80889      ** term, substitute >= for > and < for <=. e.g. if the search term
80890      ** is 4.9 and the integer approximation 5:
80891      **
80892      **        (x >  4.9)    ->     (x >= 5)
80893      **        (x <= 4.9)    ->     (x <  5)
80894      */
80895      if( pIn3->u.r<(double)iKey ){
80896        assert( OP_SeekGE==(OP_SeekGT-1) );
80897        assert( OP_SeekLT==(OP_SeekLE-1) );
80898        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
80899        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
80900      }
80901
80902      /* If the approximation iKey is smaller than the actual real search
80903      ** term, substitute <= for < and > for >=.  */
80904      else if( pIn3->u.r>(double)iKey ){
80905        assert( OP_SeekLE==(OP_SeekLT+1) );
80906        assert( OP_SeekGT==(OP_SeekGE+1) );
80907        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
80908        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
80909      }
80910    }
80911    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
80912    pC->movetoTarget = iKey;  /* Used by OP_Delete */
80913    if( rc!=SQLITE_OK ){
80914      goto abort_due_to_error;
80915    }
80916  }else{
80917    /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
80918    ** OP_SeekLE opcodes are allowed, and these must be immediately followed
80919    ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
80920    */
80921    if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
80922      eqOnly = 1;
80923      assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
80924      assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80925      assert( pOp[1].p1==pOp[0].p1 );
80926      assert( pOp[1].p2==pOp[0].p2 );
80927      assert( pOp[1].p3==pOp[0].p3 );
80928      assert( pOp[1].p4.i==pOp[0].p4.i );
80929    }
80930
80931    nField = pOp->p4.i;
80932    assert( pOp->p4type==P4_INT32 );
80933    assert( nField>0 );
80934    r.pKeyInfo = pC->pKeyInfo;
80935    r.nField = (u16)nField;
80936
80937    /* The next line of code computes as follows, only faster:
80938    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
80939    **     r.default_rc = -1;
80940    **   }else{
80941    **     r.default_rc = +1;
80942    **   }
80943    */
80944    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
80945    assert( oc!=OP_SeekGT || r.default_rc==-1 );
80946    assert( oc!=OP_SeekLE || r.default_rc==-1 );
80947    assert( oc!=OP_SeekGE || r.default_rc==+1 );
80948    assert( oc!=OP_SeekLT || r.default_rc==+1 );
80949
80950    r.aMem = &aMem[pOp->p3];
80951#ifdef SQLITE_DEBUG
80952    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
80953#endif
80954    ExpandBlob(r.aMem);
80955    r.eqSeen = 0;
80956    rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
80957    if( rc!=SQLITE_OK ){
80958      goto abort_due_to_error;
80959    }
80960    if( eqOnly && r.eqSeen==0 ){
80961      assert( res!=0 );
80962      goto seek_not_found;
80963    }
80964  }
80965  pC->deferredMoveto = 0;
80966  pC->cacheStatus = CACHE_STALE;
80967#ifdef SQLITE_TEST
80968  sqlite3_search_count++;
80969#endif
80970  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
80971    if( res<0 || (res==0 && oc==OP_SeekGT) ){
80972      res = 0;
80973      rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
80974      if( rc!=SQLITE_OK ) goto abort_due_to_error;
80975    }else{
80976      res = 0;
80977    }
80978  }else{
80979    assert( oc==OP_SeekLT || oc==OP_SeekLE );
80980    if( res>0 || (res==0 && oc==OP_SeekLT) ){
80981      res = 0;
80982      rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
80983      if( rc!=SQLITE_OK ) goto abort_due_to_error;
80984    }else{
80985      /* res might be negative because the table is empty.  Check to
80986      ** see if this is the case.
80987      */
80988      res = sqlite3BtreeEof(pC->uc.pCursor);
80989    }
80990  }
80991seek_not_found:
80992  assert( pOp->p2>0 );
80993  VdbeBranchTaken(res!=0,2);
80994  if( res ){
80995    goto jump_to_p2;
80996  }else if( eqOnly ){
80997    assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80998    pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
80999  }
81000  break;
81001}
81002
81003
81004/* Opcode: Found P1 P2 P3 P4 *
81005** Synopsis: key=r[P3@P4]
81006**
81007** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81008** P4>0 then register P3 is the first of P4 registers that form an unpacked
81009** record.
81010**
81011** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81012** is a prefix of any entry in P1 then a jump is made to P2 and
81013** P1 is left pointing at the matching entry.
81014**
81015** This operation leaves the cursor in a state where it can be
81016** advanced in the forward direction.  The Next instruction will work,
81017** but not the Prev instruction.
81018**
81019** See also: NotFound, NoConflict, NotExists. SeekGe
81020*/
81021/* Opcode: NotFound P1 P2 P3 P4 *
81022** Synopsis: key=r[P3@P4]
81023**
81024** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81025** P4>0 then register P3 is the first of P4 registers that form an unpacked
81026** record.
81027**
81028** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81029** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
81030** does contain an entry whose prefix matches the P3/P4 record then control
81031** falls through to the next instruction and P1 is left pointing at the
81032** matching entry.
81033**
81034** This operation leaves the cursor in a state where it cannot be
81035** advanced in either direction.  In other words, the Next and Prev
81036** opcodes do not work after this operation.
81037**
81038** See also: Found, NotExists, NoConflict
81039*/
81040/* Opcode: NoConflict P1 P2 P3 P4 *
81041** Synopsis: key=r[P3@P4]
81042**
81043** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81044** P4>0 then register P3 is the first of P4 registers that form an unpacked
81045** record.
81046**
81047** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81048** contains any NULL value, jump immediately to P2.  If all terms of the
81049** record are not-NULL then a check is done to determine if any row in the
81050** P1 index btree has a matching key prefix.  If there are no matches, jump
81051** immediately to P2.  If there is a match, fall through and leave the P1
81052** cursor pointing to the matching row.
81053**
81054** This opcode is similar to OP_NotFound with the exceptions that the
81055** branch is always taken if any part of the search key input is NULL.
81056**
81057** This operation leaves the cursor in a state where it cannot be
81058** advanced in either direction.  In other words, the Next and Prev
81059** opcodes do not work after this operation.
81060**
81061** See also: NotFound, Found, NotExists
81062*/
81063case OP_NoConflict:     /* jump, in3 */
81064case OP_NotFound:       /* jump, in3 */
81065case OP_Found: {        /* jump, in3 */
81066  int alreadyExists;
81067  int takeJump;
81068  int ii;
81069  VdbeCursor *pC;
81070  int res;
81071  char *pFree;
81072  UnpackedRecord *pIdxKey;
81073  UnpackedRecord r;
81074  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
81075
81076#ifdef SQLITE_TEST
81077  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
81078#endif
81079
81080  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81081  assert( pOp->p4type==P4_INT32 );
81082  pC = p->apCsr[pOp->p1];
81083  assert( pC!=0 );
81084#ifdef SQLITE_DEBUG
81085  pC->seekOp = pOp->opcode;
81086#endif
81087  pIn3 = &aMem[pOp->p3];
81088  assert( pC->eCurType==CURTYPE_BTREE );
81089  assert( pC->uc.pCursor!=0 );
81090  assert( pC->isTable==0 );
81091  pFree = 0;
81092  if( pOp->p4.i>0 ){
81093    r.pKeyInfo = pC->pKeyInfo;
81094    r.nField = (u16)pOp->p4.i;
81095    r.aMem = pIn3;
81096    for(ii=0; ii<r.nField; ii++){
81097      assert( memIsValid(&r.aMem[ii]) );
81098      ExpandBlob(&r.aMem[ii]);
81099#ifdef SQLITE_DEBUG
81100      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
81101#endif
81102    }
81103    pIdxKey = &r;
81104  }else{
81105    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
81106        pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
81107    );
81108    if( pIdxKey==0 ) goto no_mem;
81109    assert( pIn3->flags & MEM_Blob );
81110    ExpandBlob(pIn3);
81111    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
81112  }
81113  pIdxKey->default_rc = 0;
81114  takeJump = 0;
81115  if( pOp->opcode==OP_NoConflict ){
81116    /* For the OP_NoConflict opcode, take the jump if any of the
81117    ** input fields are NULL, since any key with a NULL will not
81118    ** conflict */
81119    for(ii=0; ii<pIdxKey->nField; ii++){
81120      if( pIdxKey->aMem[ii].flags & MEM_Null ){
81121        takeJump = 1;
81122        break;
81123      }
81124    }
81125  }
81126  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
81127  sqlite3DbFree(db, pFree);
81128  if( rc!=SQLITE_OK ){
81129    goto abort_due_to_error;
81130  }
81131  pC->seekResult = res;
81132  alreadyExists = (res==0);
81133  pC->nullRow = 1-alreadyExists;
81134  pC->deferredMoveto = 0;
81135  pC->cacheStatus = CACHE_STALE;
81136  if( pOp->opcode==OP_Found ){
81137    VdbeBranchTaken(alreadyExists!=0,2);
81138    if( alreadyExists ) goto jump_to_p2;
81139  }else{
81140    VdbeBranchTaken(takeJump||alreadyExists==0,2);
81141    if( takeJump || !alreadyExists ) goto jump_to_p2;
81142  }
81143  break;
81144}
81145
81146/* Opcode: SeekRowid P1 P2 P3 * *
81147** Synopsis: intkey=r[P3]
81148**
81149** P1 is the index of a cursor open on an SQL table btree (with integer
81150** keys).  If register P3 does not contain an integer or if P1 does not
81151** contain a record with rowid P3 then jump immediately to P2.
81152** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
81153** a record with rowid P3 then
81154** leave the cursor pointing at that record and fall through to the next
81155** instruction.
81156**
81157** The OP_NotExists opcode performs the same operation, but with OP_NotExists
81158** the P3 register must be guaranteed to contain an integer value.  With this
81159** opcode, register P3 might not contain an integer.
81160**
81161** The OP_NotFound opcode performs the same operation on index btrees
81162** (with arbitrary multi-value keys).
81163**
81164** This opcode leaves the cursor in a state where it cannot be advanced
81165** in either direction.  In other words, the Next and Prev opcodes will
81166** not work following this opcode.
81167**
81168** See also: Found, NotFound, NoConflict, SeekRowid
81169*/
81170/* Opcode: NotExists P1 P2 P3 * *
81171** Synopsis: intkey=r[P3]
81172**
81173** P1 is the index of a cursor open on an SQL table btree (with integer
81174** keys).  P3 is an integer rowid.  If P1 does not contain a record with
81175** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
81176** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
81177** leave the cursor pointing at that record and fall through to the next
81178** instruction.
81179**
81180** The OP_SeekRowid opcode performs the same operation but also allows the
81181** P3 register to contain a non-integer value, in which case the jump is
81182** always taken.  This opcode requires that P3 always contain an integer.
81183**
81184** The OP_NotFound opcode performs the same operation on index btrees
81185** (with arbitrary multi-value keys).
81186**
81187** This opcode leaves the cursor in a state where it cannot be advanced
81188** in either direction.  In other words, the Next and Prev opcodes will
81189** not work following this opcode.
81190**
81191** See also: Found, NotFound, NoConflict, SeekRowid
81192*/
81193case OP_SeekRowid: {        /* jump, in3 */
81194  VdbeCursor *pC;
81195  BtCursor *pCrsr;
81196  int res;
81197  u64 iKey;
81198
81199  pIn3 = &aMem[pOp->p3];
81200  if( (pIn3->flags & MEM_Int)==0 ){
81201    applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
81202    if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
81203  }
81204  /* Fall through into OP_NotExists */
81205case OP_NotExists:          /* jump, in3 */
81206  pIn3 = &aMem[pOp->p3];
81207  assert( pIn3->flags & MEM_Int );
81208  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81209  pC = p->apCsr[pOp->p1];
81210  assert( pC!=0 );
81211#ifdef SQLITE_DEBUG
81212  pC->seekOp = 0;
81213#endif
81214  assert( pC->isTable );
81215  assert( pC->eCurType==CURTYPE_BTREE );
81216  pCrsr = pC->uc.pCursor;
81217  assert( pCrsr!=0 );
81218  res = 0;
81219  iKey = pIn3->u.i;
81220  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
81221  assert( rc==SQLITE_OK || res==0 );
81222  pC->movetoTarget = iKey;  /* Used by OP_Delete */
81223  pC->nullRow = 0;
81224  pC->cacheStatus = CACHE_STALE;
81225  pC->deferredMoveto = 0;
81226  VdbeBranchTaken(res!=0,2);
81227  pC->seekResult = res;
81228  if( res!=0 ){
81229    assert( rc==SQLITE_OK );
81230    if( pOp->p2==0 ){
81231      rc = SQLITE_CORRUPT_BKPT;
81232    }else{
81233      goto jump_to_p2;
81234    }
81235  }
81236  if( rc ) goto abort_due_to_error;
81237  break;
81238}
81239
81240/* Opcode: Sequence P1 P2 * * *
81241** Synopsis: r[P2]=cursor[P1].ctr++
81242**
81243** Find the next available sequence number for cursor P1.
81244** Write the sequence number into register P2.
81245** The sequence number on the cursor is incremented after this
81246** instruction.
81247*/
81248case OP_Sequence: {           /* out2 */
81249  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81250  assert( p->apCsr[pOp->p1]!=0 );
81251  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
81252  pOut = out2Prerelease(p, pOp);
81253  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
81254  break;
81255}
81256
81257
81258/* Opcode: NewRowid P1 P2 P3 * *
81259** Synopsis: r[P2]=rowid
81260**
81261** Get a new integer record number (a.k.a "rowid") used as the key to a table.
81262** The record number is not previously used as a key in the database
81263** table that cursor P1 points to.  The new record number is written
81264** written to register P2.
81265**
81266** If P3>0 then P3 is a register in the root frame of this VDBE that holds
81267** the largest previously generated record number. No new record numbers are
81268** allowed to be less than this value. When this value reaches its maximum,
81269** an SQLITE_FULL error is generated. The P3 register is updated with the '
81270** generated record number. This P3 mechanism is used to help implement the
81271** AUTOINCREMENT feature.
81272*/
81273case OP_NewRowid: {           /* out2 */
81274  i64 v;                 /* The new rowid */
81275  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
81276  int res;               /* Result of an sqlite3BtreeLast() */
81277  int cnt;               /* Counter to limit the number of searches */
81278  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
81279  VdbeFrame *pFrame;     /* Root frame of VDBE */
81280
81281  v = 0;
81282  res = 0;
81283  pOut = out2Prerelease(p, pOp);
81284  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81285  pC = p->apCsr[pOp->p1];
81286  assert( pC!=0 );
81287  assert( pC->eCurType==CURTYPE_BTREE );
81288  assert( pC->uc.pCursor!=0 );
81289  {
81290    /* The next rowid or record number (different terms for the same
81291    ** thing) is obtained in a two-step algorithm.
81292    **
81293    ** First we attempt to find the largest existing rowid and add one
81294    ** to that.  But if the largest existing rowid is already the maximum
81295    ** positive integer, we have to fall through to the second
81296    ** probabilistic algorithm
81297    **
81298    ** The second algorithm is to select a rowid at random and see if
81299    ** it already exists in the table.  If it does not exist, we have
81300    ** succeeded.  If the random rowid does exist, we select a new one
81301    ** and try again, up to 100 times.
81302    */
81303    assert( pC->isTable );
81304
81305#ifdef SQLITE_32BIT_ROWID
81306#   define MAX_ROWID 0x7fffffff
81307#else
81308    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
81309    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
81310    ** to provide the constant while making all compilers happy.
81311    */
81312#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
81313#endif
81314
81315    if( !pC->useRandomRowid ){
81316      rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
81317      if( rc!=SQLITE_OK ){
81318        goto abort_due_to_error;
81319      }
81320      if( res ){
81321        v = 1;   /* IMP: R-61914-48074 */
81322      }else{
81323        assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
81324        v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81325        if( v>=MAX_ROWID ){
81326          pC->useRandomRowid = 1;
81327        }else{
81328          v++;   /* IMP: R-29538-34987 */
81329        }
81330      }
81331    }
81332
81333#ifndef SQLITE_OMIT_AUTOINCREMENT
81334    if( pOp->p3 ){
81335      /* Assert that P3 is a valid memory cell. */
81336      assert( pOp->p3>0 );
81337      if( p->pFrame ){
81338        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
81339        /* Assert that P3 is a valid memory cell. */
81340        assert( pOp->p3<=pFrame->nMem );
81341        pMem = &pFrame->aMem[pOp->p3];
81342      }else{
81343        /* Assert that P3 is a valid memory cell. */
81344        assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
81345        pMem = &aMem[pOp->p3];
81346        memAboutToChange(p, pMem);
81347      }
81348      assert( memIsValid(pMem) );
81349
81350      REGISTER_TRACE(pOp->p3, pMem);
81351      sqlite3VdbeMemIntegerify(pMem);
81352      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
81353      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
81354        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
81355        goto abort_due_to_error;
81356      }
81357      if( v<pMem->u.i+1 ){
81358        v = pMem->u.i + 1;
81359      }
81360      pMem->u.i = v;
81361    }
81362#endif
81363    if( pC->useRandomRowid ){
81364      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
81365      ** largest possible integer (9223372036854775807) then the database
81366      ** engine starts picking positive candidate ROWIDs at random until
81367      ** it finds one that is not previously used. */
81368      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
81369                             ** an AUTOINCREMENT table. */
81370      cnt = 0;
81371      do{
81372        sqlite3_randomness(sizeof(v), &v);
81373        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
81374      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
81375                                                 0, &res))==SQLITE_OK)
81376            && (res==0)
81377            && (++cnt<100));
81378      if( rc ) goto abort_due_to_error;
81379      if( res==0 ){
81380        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
81381        goto abort_due_to_error;
81382      }
81383      assert( v>0 );  /* EV: R-40812-03570 */
81384    }
81385    pC->deferredMoveto = 0;
81386    pC->cacheStatus = CACHE_STALE;
81387  }
81388  pOut->u.i = v;
81389  break;
81390}
81391
81392/* Opcode: Insert P1 P2 P3 P4 P5
81393** Synopsis: intkey=r[P3] data=r[P2]
81394**
81395** Write an entry into the table of cursor P1.  A new entry is
81396** created if it doesn't already exist or the data for an existing
81397** entry is overwritten.  The data is the value MEM_Blob stored in register
81398** number P2. The key is stored in register P3. The key must
81399** be a MEM_Int.
81400**
81401** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
81402** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
81403** then rowid is stored for subsequent return by the
81404** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
81405**
81406** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
81407** the last seek operation (OP_NotExists or OP_SeekRowid) was a success,
81408** then this
81409** operation will not attempt to find the appropriate row before doing
81410** the insert but will instead overwrite the row that the cursor is
81411** currently pointing to.  Presumably, the prior OP_NotExists or
81412** OP_SeekRowid opcode
81413** has already positioned the cursor correctly.  This is an optimization
81414** that boosts performance by avoiding redundant seeks.
81415**
81416** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
81417** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
81418** is part of an INSERT operation.  The difference is only important to
81419** the update hook.
81420**
81421** Parameter P4 may point to a Table structure, or may be NULL. If it is
81422** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
81423** following a successful insert.
81424**
81425** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
81426** allocated, then ownership of P2 is transferred to the pseudo-cursor
81427** and register P2 becomes ephemeral.  If the cursor is changed, the
81428** value of register P2 will then change.  Make sure this does not
81429** cause any problems.)
81430**
81431** This instruction only works on tables.  The equivalent instruction
81432** for indices is OP_IdxInsert.
81433*/
81434/* Opcode: InsertInt P1 P2 P3 P4 P5
81435** Synopsis:  intkey=P3 data=r[P2]
81436**
81437** This works exactly like OP_Insert except that the key is the
81438** integer value P3, not the value of the integer stored in register P3.
81439*/
81440case OP_Insert:
81441case OP_InsertInt: {
81442  Mem *pData;       /* MEM cell holding data for the record to be inserted */
81443  Mem *pKey;        /* MEM cell holding key  for the record */
81444  VdbeCursor *pC;   /* Cursor to table into which insert is written */
81445  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
81446  const char *zDb;  /* database name - used by the update hook */
81447  Table *pTab;      /* Table structure - used by update and pre-update hooks */
81448  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
81449  BtreePayload x;   /* Payload to be inserted */
81450
81451  op = 0;
81452  pData = &aMem[pOp->p2];
81453  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81454  assert( memIsValid(pData) );
81455  pC = p->apCsr[pOp->p1];
81456  assert( pC!=0 );
81457  assert( pC->eCurType==CURTYPE_BTREE );
81458  assert( pC->uc.pCursor!=0 );
81459  assert( pC->isTable );
81460  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
81461  REGISTER_TRACE(pOp->p2, pData);
81462
81463  if( pOp->opcode==OP_Insert ){
81464    pKey = &aMem[pOp->p3];
81465    assert( pKey->flags & MEM_Int );
81466    assert( memIsValid(pKey) );
81467    REGISTER_TRACE(pOp->p3, pKey);
81468    x.nKey = pKey->u.i;
81469  }else{
81470    assert( pOp->opcode==OP_InsertInt );
81471    x.nKey = pOp->p3;
81472  }
81473
81474  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81475    assert( pC->isTable );
81476    assert( pC->iDb>=0 );
81477    zDb = db->aDb[pC->iDb].zName;
81478    pTab = pOp->p4.pTab;
81479    assert( HasRowid(pTab) );
81480    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
81481  }else{
81482    pTab = 0; /* Not needed.  Silence a comiler warning. */
81483    zDb = 0;  /* Not needed.  Silence a compiler warning. */
81484  }
81485
81486#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81487  /* Invoke the pre-update hook, if any */
81488  if( db->xPreUpdateCallback
81489   && pOp->p4type==P4_TABLE
81490   && !(pOp->p5 & OPFLAG_ISUPDATE)
81491  ){
81492    sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
81493  }
81494#endif
81495
81496  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81497  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey;
81498  if( pData->flags & MEM_Null ){
81499    x.pData = 0;
81500    x.nData = 0;
81501  }else{
81502    assert( pData->flags & (MEM_Blob|MEM_Str) );
81503    x.pData = pData->z;
81504    x.nData = pData->n;
81505  }
81506  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
81507  if( pData->flags & MEM_Zero ){
81508    x.nZero = pData->u.nZero;
81509  }else{
81510    x.nZero = 0;
81511  }
81512  x.pKey = 0;
81513  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
81514                          (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
81515  );
81516  pC->deferredMoveto = 0;
81517  pC->cacheStatus = CACHE_STALE;
81518
81519  /* Invoke the update-hook if required. */
81520  if( rc ) goto abort_due_to_error;
81521  if( db->xUpdateCallback && op ){
81522    db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
81523  }
81524  break;
81525}
81526
81527/* Opcode: Delete P1 P2 P3 P4 P5
81528**
81529** Delete the record at which the P1 cursor is currently pointing.
81530**
81531** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
81532** the cursor will be left pointing at  either the next or the previous
81533** record in the table. If it is left pointing at the next record, then
81534** the next Next instruction will be a no-op. As a result, in this case
81535** it is ok to delete a record from within a Next loop. If
81536** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
81537** left in an undefined state.
81538**
81539** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
81540** delete one of several associated with deleting a table row and all its
81541** associated index entries.  Exactly one of those deletes is the "primary"
81542** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
81543** marked with the AUXDELETE flag.
81544**
81545** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
81546** change count is incremented (otherwise not).
81547**
81548** P1 must not be pseudo-table.  It has to be a real table with
81549** multiple rows.
81550**
81551** If P4 is not NULL then it points to a Table struture. In this case either
81552** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81553** have been positioned using OP_NotFound prior to invoking this opcode in
81554** this case. Specifically, if one is configured, the pre-update hook is
81555** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81556** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81557**
81558** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81559** of the memory cell that contains the value that the rowid of the row will
81560** be set to by the update.
81561*/
81562case OP_Delete: {
81563  VdbeCursor *pC;
81564  const char *zDb;
81565  Table *pTab;
81566  int opflags;
81567
81568  opflags = pOp->p2;
81569  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81570  pC = p->apCsr[pOp->p1];
81571  assert( pC!=0 );
81572  assert( pC->eCurType==CURTYPE_BTREE );
81573  assert( pC->uc.pCursor!=0 );
81574  assert( pC->deferredMoveto==0 );
81575
81576#ifdef SQLITE_DEBUG
81577  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81578    /* If p5 is zero, the seek operation that positioned the cursor prior to
81579    ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81580    ** the row that is being deleted */
81581    i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81582    assert( pC->movetoTarget==iKey );
81583  }
81584#endif
81585
81586  /* If the update-hook or pre-update-hook will be invoked, set zDb to
81587  ** the name of the db to pass as to it. Also set local pTab to a copy
81588  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81589  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81590  ** VdbeCursor.movetoTarget to the current rowid.  */
81591  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81592    assert( pC->iDb>=0 );
81593    assert( pOp->p4.pTab!=0 );
81594    zDb = db->aDb[pC->iDb].zName;
81595    pTab = pOp->p4.pTab;
81596    if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81597      pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81598    }
81599  }else{
81600    zDb = 0;   /* Not needed.  Silence a compiler warning. */
81601    pTab = 0;  /* Not needed.  Silence a compiler warning. */
81602  }
81603
81604#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81605  /* Invoke the pre-update-hook if required. */
81606  if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81607    assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81608    sqlite3VdbePreUpdateHook(p, pC,
81609        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81610        zDb, pTab, pC->movetoTarget,
81611        pOp->p3
81612    );
81613  }
81614  if( opflags & OPFLAG_ISNOOP ) break;
81615#endif
81616
81617  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
81618  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81619  assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
81620  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
81621
81622#ifdef SQLITE_DEBUG
81623  if( p->pFrame==0 ){
81624    if( pC->isEphemeral==0
81625        && (pOp->p5 & OPFLAG_AUXDELETE)==0
81626        && (pC->wrFlag & OPFLAG_FORDELETE)==0
81627      ){
81628      nExtraDelete++;
81629    }
81630    if( pOp->p2 & OPFLAG_NCHANGE ){
81631      nExtraDelete--;
81632    }
81633  }
81634#endif
81635
81636  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81637  pC->cacheStatus = CACHE_STALE;
81638  if( rc ) goto abort_due_to_error;
81639
81640  /* Invoke the update-hook if required. */
81641  if( opflags & OPFLAG_NCHANGE ){
81642    p->nChange++;
81643    if( db->xUpdateCallback && HasRowid(pTab) ){
81644      db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81645          pC->movetoTarget);
81646      assert( pC->iDb>=0 );
81647    }
81648  }
81649
81650  break;
81651}
81652/* Opcode: ResetCount * * * * *
81653**
81654** The value of the change counter is copied to the database handle
81655** change counter (returned by subsequent calls to sqlite3_changes()).
81656** Then the VMs internal change counter resets to 0.
81657** This is used by trigger programs.
81658*/
81659case OP_ResetCount: {
81660  sqlite3VdbeSetChanges(db, p->nChange);
81661  p->nChange = 0;
81662  break;
81663}
81664
81665/* Opcode: SorterCompare P1 P2 P3 P4
81666** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
81667**
81668** P1 is a sorter cursor. This instruction compares a prefix of the
81669** record blob in register P3 against a prefix of the entry that
81670** the sorter cursor currently points to.  Only the first P4 fields
81671** of r[P3] and the sorter record are compared.
81672**
81673** If either P3 or the sorter contains a NULL in one of their significant
81674** fields (not counting the P4 fields at the end which are ignored) then
81675** the comparison is assumed to be equal.
81676**
81677** Fall through to next instruction if the two records compare equal to
81678** each other.  Jump to P2 if they are different.
81679*/
81680case OP_SorterCompare: {
81681  VdbeCursor *pC;
81682  int res;
81683  int nKeyCol;
81684
81685  pC = p->apCsr[pOp->p1];
81686  assert( isSorter(pC) );
81687  assert( pOp->p4type==P4_INT32 );
81688  pIn3 = &aMem[pOp->p3];
81689  nKeyCol = pOp->p4.i;
81690  res = 0;
81691  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
81692  VdbeBranchTaken(res!=0,2);
81693  if( rc ) goto abort_due_to_error;
81694  if( res ) goto jump_to_p2;
81695  break;
81696};
81697
81698/* Opcode: SorterData P1 P2 P3 * *
81699** Synopsis: r[P2]=data
81700**
81701** Write into register P2 the current sorter data for sorter cursor P1.
81702** Then clear the column header cache on cursor P3.
81703**
81704** This opcode is normally use to move a record out of the sorter and into
81705** a register that is the source for a pseudo-table cursor created using
81706** OpenPseudo.  That pseudo-table cursor is the one that is identified by
81707** parameter P3.  Clearing the P3 column cache as part of this opcode saves
81708** us from having to issue a separate NullRow instruction to clear that cache.
81709*/
81710case OP_SorterData: {
81711  VdbeCursor *pC;
81712
81713  pOut = &aMem[pOp->p2];
81714  pC = p->apCsr[pOp->p1];
81715  assert( isSorter(pC) );
81716  rc = sqlite3VdbeSorterRowkey(pC, pOut);
81717  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
81718  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81719  if( rc ) goto abort_due_to_error;
81720  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
81721  break;
81722}
81723
81724/* Opcode: RowData P1 P2 * * *
81725** Synopsis: r[P2]=data
81726**
81727** Write into register P2 the complete row data for cursor P1.
81728** There is no interpretation of the data.
81729** It is just copied onto the P2 register exactly as
81730** it is found in the database file.
81731**
81732** If the P1 cursor must be pointing to a valid row (not a NULL row)
81733** of a real table, not a pseudo-table.
81734*/
81735/* Opcode: RowKey P1 P2 * * *
81736** Synopsis: r[P2]=key
81737**
81738** Write into register P2 the complete row key for cursor P1.
81739** There is no interpretation of the data.
81740** The key is copied onto the P2 register exactly as
81741** it is found in the database file.
81742**
81743** If the P1 cursor must be pointing to a valid row (not a NULL row)
81744** of a real table, not a pseudo-table.
81745*/
81746case OP_RowKey:
81747case OP_RowData: {
81748  VdbeCursor *pC;
81749  BtCursor *pCrsr;
81750  u32 n;
81751
81752  pOut = &aMem[pOp->p2];
81753  memAboutToChange(p, pOut);
81754
81755  /* Note that RowKey and RowData are really exactly the same instruction */
81756  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81757  pC = p->apCsr[pOp->p1];
81758  assert( pC!=0 );
81759  assert( pC->eCurType==CURTYPE_BTREE );
81760  assert( isSorter(pC)==0 );
81761  assert( pC->isTable || pOp->opcode!=OP_RowData );
81762  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
81763  assert( pC->nullRow==0 );
81764  assert( pC->uc.pCursor!=0 );
81765  pCrsr = pC->uc.pCursor;
81766
81767  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
81768  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
81769  ** that might invalidate the cursor.
81770  ** If this where not the case, on of the following assert()s
81771  ** would fail.  Should this ever change (because of changes in the code
81772  ** generator) then the fix would be to insert a call to
81773  ** sqlite3VdbeCursorMoveto().
81774  */
81775  assert( pC->deferredMoveto==0 );
81776  assert( sqlite3BtreeCursorIsValid(pCrsr) );
81777#if 0  /* Not required due to the previous to assert() statements */
81778  rc = sqlite3VdbeCursorMoveto(pC);
81779  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81780#endif
81781
81782  n = sqlite3BtreePayloadSize(pCrsr);
81783  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
81784    goto too_big;
81785  }
81786  testcase( n==0 );
81787  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
81788    goto no_mem;
81789  }
81790  pOut->n = n;
81791  MemSetTypeFlag(pOut, MEM_Blob);
81792  if( pC->isTable==0 ){
81793    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
81794  }else{
81795    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
81796  }
81797  if( rc ) goto abort_due_to_error;
81798  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
81799  UPDATE_MAX_BLOBSIZE(pOut);
81800  REGISTER_TRACE(pOp->p2, pOut);
81801  break;
81802}
81803
81804/* Opcode: Rowid P1 P2 * * *
81805** Synopsis: r[P2]=rowid
81806**
81807** Store in register P2 an integer which is the key of the table entry that
81808** P1 is currently point to.
81809**
81810** P1 can be either an ordinary table or a virtual table.  There used to
81811** be a separate OP_VRowid opcode for use with virtual tables, but this
81812** one opcode now works for both table types.
81813*/
81814case OP_Rowid: {                 /* out2 */
81815  VdbeCursor *pC;
81816  i64 v;
81817  sqlite3_vtab *pVtab;
81818  const sqlite3_module *pModule;
81819
81820  pOut = out2Prerelease(p, pOp);
81821  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81822  pC = p->apCsr[pOp->p1];
81823  assert( pC!=0 );
81824  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
81825  if( pC->nullRow ){
81826    pOut->flags = MEM_Null;
81827    break;
81828  }else if( pC->deferredMoveto ){
81829    v = pC->movetoTarget;
81830#ifndef SQLITE_OMIT_VIRTUALTABLE
81831  }else if( pC->eCurType==CURTYPE_VTAB ){
81832    assert( pC->uc.pVCur!=0 );
81833    pVtab = pC->uc.pVCur->pVtab;
81834    pModule = pVtab->pModule;
81835    assert( pModule->xRowid );
81836    rc = pModule->xRowid(pC->uc.pVCur, &v);
81837    sqlite3VtabImportErrmsg(p, pVtab);
81838    if( rc ) goto abort_due_to_error;
81839#endif /* SQLITE_OMIT_VIRTUALTABLE */
81840  }else{
81841    assert( pC->eCurType==CURTYPE_BTREE );
81842    assert( pC->uc.pCursor!=0 );
81843    rc = sqlite3VdbeCursorRestore(pC);
81844    if( rc ) goto abort_due_to_error;
81845    if( pC->nullRow ){
81846      pOut->flags = MEM_Null;
81847      break;
81848    }
81849    v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81850  }
81851  pOut->u.i = v;
81852  break;
81853}
81854
81855/* Opcode: NullRow P1 * * * *
81856**
81857** Move the cursor P1 to a null row.  Any OP_Column operations
81858** that occur while the cursor is on the null row will always
81859** write a NULL.
81860*/
81861case OP_NullRow: {
81862  VdbeCursor *pC;
81863
81864  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81865  pC = p->apCsr[pOp->p1];
81866  assert( pC!=0 );
81867  pC->nullRow = 1;
81868  pC->cacheStatus = CACHE_STALE;
81869  if( pC->eCurType==CURTYPE_BTREE ){
81870    assert( pC->uc.pCursor!=0 );
81871    sqlite3BtreeClearCursor(pC->uc.pCursor);
81872  }
81873  break;
81874}
81875
81876/* Opcode: Last P1 P2 P3 * *
81877**
81878** The next use of the Rowid or Column or Prev instruction for P1
81879** will refer to the last entry in the database table or index.
81880** If the table or index is empty and P2>0, then jump immediately to P2.
81881** If P2 is 0 or if the table or index is not empty, fall through
81882** to the following instruction.
81883**
81884** This opcode leaves the cursor configured to move in reverse order,
81885** from the end toward the beginning.  In other words, the cursor is
81886** configured to use Prev, not Next.
81887*/
81888case OP_Last: {        /* jump */
81889  VdbeCursor *pC;
81890  BtCursor *pCrsr;
81891  int res;
81892
81893  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81894  pC = p->apCsr[pOp->p1];
81895  assert( pC!=0 );
81896  assert( pC->eCurType==CURTYPE_BTREE );
81897  pCrsr = pC->uc.pCursor;
81898  res = 0;
81899  assert( pCrsr!=0 );
81900  rc = sqlite3BtreeLast(pCrsr, &res);
81901  pC->nullRow = (u8)res;
81902  pC->deferredMoveto = 0;
81903  pC->cacheStatus = CACHE_STALE;
81904  pC->seekResult = pOp->p3;
81905#ifdef SQLITE_DEBUG
81906  pC->seekOp = OP_Last;
81907#endif
81908  if( rc ) goto abort_due_to_error;
81909  if( pOp->p2>0 ){
81910    VdbeBranchTaken(res!=0,2);
81911    if( res ) goto jump_to_p2;
81912  }
81913  break;
81914}
81915
81916
81917/* Opcode: Sort P1 P2 * * *
81918**
81919** This opcode does exactly the same thing as OP_Rewind except that
81920** it increments an undocumented global variable used for testing.
81921**
81922** Sorting is accomplished by writing records into a sorting index,
81923** then rewinding that index and playing it back from beginning to
81924** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
81925** rewinding so that the global variable will be incremented and
81926** regression tests can determine whether or not the optimizer is
81927** correctly optimizing out sorts.
81928*/
81929case OP_SorterSort:    /* jump */
81930case OP_Sort: {        /* jump */
81931#ifdef SQLITE_TEST
81932  sqlite3_sort_count++;
81933  sqlite3_search_count--;
81934#endif
81935  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
81936  /* Fall through into OP_Rewind */
81937}
81938/* Opcode: Rewind P1 P2 * * *
81939**
81940** The next use of the Rowid or Column or Next instruction for P1
81941** will refer to the first entry in the database table or index.
81942** If the table or index is empty, jump immediately to P2.
81943** If the table or index is not empty, fall through to the following
81944** instruction.
81945**
81946** This opcode leaves the cursor configured to move in forward order,
81947** from the beginning toward the end.  In other words, the cursor is
81948** configured to use Next, not Prev.
81949*/
81950case OP_Rewind: {        /* jump */
81951  VdbeCursor *pC;
81952  BtCursor *pCrsr;
81953  int res;
81954
81955  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81956  pC = p->apCsr[pOp->p1];
81957  assert( pC!=0 );
81958  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
81959  res = 1;
81960#ifdef SQLITE_DEBUG
81961  pC->seekOp = OP_Rewind;
81962#endif
81963  if( isSorter(pC) ){
81964    rc = sqlite3VdbeSorterRewind(pC, &res);
81965  }else{
81966    assert( pC->eCurType==CURTYPE_BTREE );
81967    pCrsr = pC->uc.pCursor;
81968    assert( pCrsr );
81969    rc = sqlite3BtreeFirst(pCrsr, &res);
81970    pC->deferredMoveto = 0;
81971    pC->cacheStatus = CACHE_STALE;
81972  }
81973  if( rc ) goto abort_due_to_error;
81974  pC->nullRow = (u8)res;
81975  assert( pOp->p2>0 && pOp->p2<p->nOp );
81976  VdbeBranchTaken(res!=0,2);
81977  if( res ) goto jump_to_p2;
81978  break;
81979}
81980
81981/* Opcode: Next P1 P2 P3 P4 P5
81982**
81983** Advance cursor P1 so that it points to the next key/data pair in its
81984** table or index.  If there are no more key/value pairs then fall through
81985** to the following instruction.  But if the cursor advance was successful,
81986** jump immediately to P2.
81987**
81988** The Next opcode is only valid following an SeekGT, SeekGE, or
81989** OP_Rewind opcode used to position the cursor.  Next is not allowed
81990** to follow SeekLT, SeekLE, or OP_Last.
81991**
81992** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
81993** been opened prior to this opcode or the program will segfault.
81994**
81995** The P3 value is a hint to the btree implementation. If P3==1, that
81996** means P1 is an SQL index and that this instruction could have been
81997** omitted if that index had been unique.  P3 is usually 0.  P3 is
81998** always either 0 or 1.
81999**
82000** P4 is always of type P4_ADVANCE. The function pointer points to
82001** sqlite3BtreeNext().
82002**
82003** If P5 is positive and the jump is taken, then event counter
82004** number P5-1 in the prepared statement is incremented.
82005**
82006** See also: Prev, NextIfOpen
82007*/
82008/* Opcode: NextIfOpen P1 P2 P3 P4 P5
82009**
82010** This opcode works just like Next except that if cursor P1 is not
82011** open it behaves a no-op.
82012*/
82013/* Opcode: Prev P1 P2 P3 P4 P5
82014**
82015** Back up cursor P1 so that it points to the previous key/data pair in its
82016** table or index.  If there is no previous key/value pairs then fall through
82017** to the following instruction.  But if the cursor backup was successful,
82018** jump immediately to P2.
82019**
82020**
82021** The Prev opcode is only valid following an SeekLT, SeekLE, or
82022** OP_Last opcode used to position the cursor.  Prev is not allowed
82023** to follow SeekGT, SeekGE, or OP_Rewind.
82024**
82025** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
82026** not open then the behavior is undefined.
82027**
82028** The P3 value is a hint to the btree implementation. If P3==1, that
82029** means P1 is an SQL index and that this instruction could have been
82030** omitted if that index had been unique.  P3 is usually 0.  P3 is
82031** always either 0 or 1.
82032**
82033** P4 is always of type P4_ADVANCE. The function pointer points to
82034** sqlite3BtreePrevious().
82035**
82036** If P5 is positive and the jump is taken, then event counter
82037** number P5-1 in the prepared statement is incremented.
82038*/
82039/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
82040**
82041** This opcode works just like Prev except that if cursor P1 is not
82042** open it behaves a no-op.
82043*/
82044case OP_SorterNext: {  /* jump */
82045  VdbeCursor *pC;
82046  int res;
82047
82048  pC = p->apCsr[pOp->p1];
82049  assert( isSorter(pC) );
82050  res = 0;
82051  rc = sqlite3VdbeSorterNext(db, pC, &res);
82052  goto next_tail;
82053case OP_PrevIfOpen:    /* jump */
82054case OP_NextIfOpen:    /* jump */
82055  if( p->apCsr[pOp->p1]==0 ) break;
82056  /* Fall through */
82057case OP_Prev:          /* jump */
82058case OP_Next:          /* jump */
82059  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82060  assert( pOp->p5<ArraySize(p->aCounter) );
82061  pC = p->apCsr[pOp->p1];
82062  res = pOp->p3;
82063  assert( pC!=0 );
82064  assert( pC->deferredMoveto==0 );
82065  assert( pC->eCurType==CURTYPE_BTREE );
82066  assert( res==0 || (res==1 && pC->isTable==0) );
82067  testcase( res==1 );
82068  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
82069  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
82070  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
82071  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
82072
82073  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
82074  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
82075  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
82076       || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
82077       || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
82078  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
82079       || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
82080       || pC->seekOp==OP_Last );
82081
82082  rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
82083next_tail:
82084  pC->cacheStatus = CACHE_STALE;
82085  VdbeBranchTaken(res==0,2);
82086  if( rc ) goto abort_due_to_error;
82087  if( res==0 ){
82088    pC->nullRow = 0;
82089    p->aCounter[pOp->p5]++;
82090#ifdef SQLITE_TEST
82091    sqlite3_search_count++;
82092#endif
82093    goto jump_to_p2_and_check_for_interrupt;
82094  }else{
82095    pC->nullRow = 1;
82096  }
82097  goto check_for_interrupt;
82098}
82099
82100/* Opcode: IdxInsert P1 P2 P3 * P5
82101** Synopsis: key=r[P2]
82102**
82103** Register P2 holds an SQL index key made using the
82104** MakeRecord instructions.  This opcode writes that key
82105** into the index P1.  Data for the entry is nil.
82106**
82107** P3 is a flag that provides a hint to the b-tree layer that this
82108** insert is likely to be an append.
82109**
82110** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
82111** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
82112** then the change counter is unchanged.
82113**
82114** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
82115** just done a seek to the spot where the new entry is to be inserted.
82116** This flag avoids doing an extra seek.
82117**
82118** This instruction only works for indices.  The equivalent instruction
82119** for tables is OP_Insert.
82120*/
82121case OP_SorterInsert:       /* in2 */
82122case OP_IdxInsert: {        /* in2 */
82123  VdbeCursor *pC;
82124  BtreePayload x;
82125
82126  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82127  pC = p->apCsr[pOp->p1];
82128  assert( pC!=0 );
82129  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
82130  pIn2 = &aMem[pOp->p2];
82131  assert( pIn2->flags & MEM_Blob );
82132  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
82133  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
82134  assert( pC->isTable==0 );
82135  rc = ExpandBlob(pIn2);
82136  if( rc ) goto abort_due_to_error;
82137  if( pOp->opcode==OP_SorterInsert ){
82138    rc = sqlite3VdbeSorterWrite(pC, pIn2);
82139  }else{
82140    x.nKey = pIn2->n;
82141    x.pKey = pIn2->z;
82142    x.nData = 0;
82143    x.nZero = 0;
82144    x.pData = 0;
82145    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3,
82146        ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
82147        );
82148    assert( pC->deferredMoveto==0 );
82149    pC->cacheStatus = CACHE_STALE;
82150  }
82151  if( rc) goto abort_due_to_error;
82152  break;
82153}
82154
82155/* Opcode: IdxDelete P1 P2 P3 * *
82156** Synopsis: key=r[P2@P3]
82157**
82158** The content of P3 registers starting at register P2 form
82159** an unpacked index key. This opcode removes that entry from the
82160** index opened by cursor P1.
82161*/
82162case OP_IdxDelete: {
82163  VdbeCursor *pC;
82164  BtCursor *pCrsr;
82165  int res;
82166  UnpackedRecord r;
82167
82168  assert( pOp->p3>0 );
82169  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
82170  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82171  pC = p->apCsr[pOp->p1];
82172  assert( pC!=0 );
82173  assert( pC->eCurType==CURTYPE_BTREE );
82174  pCrsr = pC->uc.pCursor;
82175  assert( pCrsr!=0 );
82176  assert( pOp->p5==0 );
82177  r.pKeyInfo = pC->pKeyInfo;
82178  r.nField = (u16)pOp->p3;
82179  r.default_rc = 0;
82180  r.aMem = &aMem[pOp->p2];
82181  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
82182  if( rc ) goto abort_due_to_error;
82183  if( res==0 ){
82184    rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
82185    if( rc ) goto abort_due_to_error;
82186  }
82187  assert( pC->deferredMoveto==0 );
82188  pC->cacheStatus = CACHE_STALE;
82189  break;
82190}
82191
82192/* Opcode: Seek P1 * P3 P4 *
82193** Synopsis:  Move P3 to P1.rowid
82194**
82195** P1 is an open index cursor and P3 is a cursor on the corresponding
82196** table.  This opcode does a deferred seek of the P3 table cursor
82197** to the row that corresponds to the current row of P1.
82198**
82199** This is a deferred seek.  Nothing actually happens until
82200** the cursor is used to read a record.  That way, if no reads
82201** occur, no unnecessary I/O happens.
82202**
82203** P4 may be an array of integers (type P4_INTARRAY) containing
82204** one entry for each column in the P3 table.  If array entry a(i)
82205** is non-zero, then reading column a(i)-1 from cursor P3 is
82206** equivalent to performing the deferred seek and then reading column i
82207** from P1.  This information is stored in P3 and used to redirect
82208** reads against P3 over to P1, thus possibly avoiding the need to
82209** seek and read cursor P3.
82210*/
82211/* Opcode: IdxRowid P1 P2 * * *
82212** Synopsis: r[P2]=rowid
82213**
82214** Write into register P2 an integer which is the last entry in the record at
82215** the end of the index key pointed to by cursor P1.  This integer should be
82216** the rowid of the table entry to which this index entry points.
82217**
82218** See also: Rowid, MakeRecord.
82219*/
82220case OP_Seek:
82221case OP_IdxRowid: {              /* out2 */
82222  VdbeCursor *pC;                /* The P1 index cursor */
82223  VdbeCursor *pTabCur;           /* The P2 table cursor (OP_Seek only) */
82224  i64 rowid;                     /* Rowid that P1 current points to */
82225
82226  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82227  pC = p->apCsr[pOp->p1];
82228  assert( pC!=0 );
82229  assert( pC->eCurType==CURTYPE_BTREE );
82230  assert( pC->uc.pCursor!=0 );
82231  assert( pC->isTable==0 );
82232  assert( pC->deferredMoveto==0 );
82233  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
82234
82235  /* The IdxRowid and Seek opcodes are combined because of the commonality
82236  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
82237  rc = sqlite3VdbeCursorRestore(pC);
82238
82239  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
82240  ** out from under the cursor.  That will never happens for an IdxRowid
82241  ** or Seek opcode */
82242  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
82243
82244  if( !pC->nullRow ){
82245    rowid = 0;  /* Not needed.  Only used to silence a warning. */
82246    rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
82247    if( rc!=SQLITE_OK ){
82248      goto abort_due_to_error;
82249    }
82250    if( pOp->opcode==OP_Seek ){
82251      assert( pOp->p3>=0 && pOp->p3<p->nCursor );
82252      pTabCur = p->apCsr[pOp->p3];
82253      assert( pTabCur!=0 );
82254      assert( pTabCur->eCurType==CURTYPE_BTREE );
82255      assert( pTabCur->uc.pCursor!=0 );
82256      assert( pTabCur->isTable );
82257      pTabCur->nullRow = 0;
82258      pTabCur->movetoTarget = rowid;
82259      pTabCur->deferredMoveto = 1;
82260      assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
82261      pTabCur->aAltMap = pOp->p4.ai;
82262      pTabCur->pAltCursor = pC;
82263    }else{
82264      pOut = out2Prerelease(p, pOp);
82265      pOut->u.i = rowid;
82266      pOut->flags = MEM_Int;
82267    }
82268  }else{
82269    assert( pOp->opcode==OP_IdxRowid );
82270    sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
82271  }
82272  break;
82273}
82274
82275/* Opcode: IdxGE P1 P2 P3 P4 P5
82276** Synopsis: key=r[P3@P4]
82277**
82278** The P4 register values beginning with P3 form an unpacked index
82279** key that omits the PRIMARY KEY.  Compare this key value against the index
82280** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82281** fields at the end.
82282**
82283** If the P1 index entry is greater than or equal to the key value
82284** then jump to P2.  Otherwise fall through to the next instruction.
82285*/
82286/* Opcode: IdxGT P1 P2 P3 P4 P5
82287** Synopsis: key=r[P3@P4]
82288**
82289** The P4 register values beginning with P3 form an unpacked index
82290** key that omits the PRIMARY KEY.  Compare this key value against the index
82291** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82292** fields at the end.
82293**
82294** If the P1 index entry is greater than the key value
82295** then jump to P2.  Otherwise fall through to the next instruction.
82296*/
82297/* Opcode: IdxLT P1 P2 P3 P4 P5
82298** Synopsis: key=r[P3@P4]
82299**
82300** The P4 register values beginning with P3 form an unpacked index
82301** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
82302** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82303** ROWID on the P1 index.
82304**
82305** If the P1 index entry is less than the key value then jump to P2.
82306** Otherwise fall through to the next instruction.
82307*/
82308/* Opcode: IdxLE P1 P2 P3 P4 P5
82309** Synopsis: key=r[P3@P4]
82310**
82311** The P4 register values beginning with P3 form an unpacked index
82312** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
82313** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82314** ROWID on the P1 index.
82315**
82316** If the P1 index entry is less than or equal to the key value then jump
82317** to P2. Otherwise fall through to the next instruction.
82318*/
82319case OP_IdxLE:          /* jump */
82320case OP_IdxGT:          /* jump */
82321case OP_IdxLT:          /* jump */
82322case OP_IdxGE:  {       /* jump */
82323  VdbeCursor *pC;
82324  int res;
82325  UnpackedRecord r;
82326
82327  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82328  pC = p->apCsr[pOp->p1];
82329  assert( pC!=0 );
82330  assert( pC->isOrdered );
82331  assert( pC->eCurType==CURTYPE_BTREE );
82332  assert( pC->uc.pCursor!=0);
82333  assert( pC->deferredMoveto==0 );
82334  assert( pOp->p5==0 || pOp->p5==1 );
82335  assert( pOp->p4type==P4_INT32 );
82336  r.pKeyInfo = pC->pKeyInfo;
82337  r.nField = (u16)pOp->p4.i;
82338  if( pOp->opcode<OP_IdxLT ){
82339    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
82340    r.default_rc = -1;
82341  }else{
82342    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
82343    r.default_rc = 0;
82344  }
82345  r.aMem = &aMem[pOp->p3];
82346#ifdef SQLITE_DEBUG
82347  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82348#endif
82349  res = 0;  /* Not needed.  Only used to silence a warning. */
82350  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
82351  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
82352  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
82353    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
82354    res = -res;
82355  }else{
82356    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
82357    res++;
82358  }
82359  VdbeBranchTaken(res>0,2);
82360  if( rc ) goto abort_due_to_error;
82361  if( res>0 ) goto jump_to_p2;
82362  break;
82363}
82364
82365/* Opcode: Destroy P1 P2 P3 * *
82366**
82367** Delete an entire database table or index whose root page in the database
82368** file is given by P1.
82369**
82370** The table being destroyed is in the main database file if P3==0.  If
82371** P3==1 then the table to be clear is in the auxiliary database file
82372** that is used to store tables create using CREATE TEMPORARY TABLE.
82373**
82374** If AUTOVACUUM is enabled then it is possible that another root page
82375** might be moved into the newly deleted root page in order to keep all
82376** root pages contiguous at the beginning of the database.  The former
82377** value of the root page that moved - its value before the move occurred -
82378** is stored in register P2.  If no page
82379** movement was required (because the table being dropped was already
82380** the last one in the database) then a zero is stored in register P2.
82381** If AUTOVACUUM is disabled then a zero is stored in register P2.
82382**
82383** See also: Clear
82384*/
82385case OP_Destroy: {     /* out2 */
82386  int iMoved;
82387  int iDb;
82388
82389  assert( p->readOnly==0 );
82390  assert( pOp->p1>1 );
82391  pOut = out2Prerelease(p, pOp);
82392  pOut->flags = MEM_Null;
82393  if( db->nVdbeRead > db->nVDestroy+1 ){
82394    rc = SQLITE_LOCKED;
82395    p->errorAction = OE_Abort;
82396    goto abort_due_to_error;
82397  }else{
82398    iDb = pOp->p3;
82399    assert( DbMaskTest(p->btreeMask, iDb) );
82400    iMoved = 0;  /* Not needed.  Only to silence a warning. */
82401    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
82402    pOut->flags = MEM_Int;
82403    pOut->u.i = iMoved;
82404    if( rc ) goto abort_due_to_error;
82405#ifndef SQLITE_OMIT_AUTOVACUUM
82406    if( iMoved!=0 ){
82407      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
82408      /* All OP_Destroy operations occur on the same btree */
82409      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
82410      resetSchemaOnFault = iDb+1;
82411    }
82412#endif
82413  }
82414  break;
82415}
82416
82417/* Opcode: Clear P1 P2 P3
82418**
82419** Delete all contents of the database table or index whose root page
82420** in the database file is given by P1.  But, unlike Destroy, do not
82421** remove the table or index from the database file.
82422**
82423** The table being clear is in the main database file if P2==0.  If
82424** P2==1 then the table to be clear is in the auxiliary database file
82425** that is used to store tables create using CREATE TEMPORARY TABLE.
82426**
82427** If the P3 value is non-zero, then the table referred to must be an
82428** intkey table (an SQL table, not an index). In this case the row change
82429** count is incremented by the number of rows in the table being cleared.
82430** If P3 is greater than zero, then the value stored in register P3 is
82431** also incremented by the number of rows in the table being cleared.
82432**
82433** See also: Destroy
82434*/
82435case OP_Clear: {
82436  int nChange;
82437
82438  nChange = 0;
82439  assert( p->readOnly==0 );
82440  assert( DbMaskTest(p->btreeMask, pOp->p2) );
82441  rc = sqlite3BtreeClearTable(
82442      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
82443  );
82444  if( pOp->p3 ){
82445    p->nChange += nChange;
82446    if( pOp->p3>0 ){
82447      assert( memIsValid(&aMem[pOp->p3]) );
82448      memAboutToChange(p, &aMem[pOp->p3]);
82449      aMem[pOp->p3].u.i += nChange;
82450    }
82451  }
82452  if( rc ) goto abort_due_to_error;
82453  break;
82454}
82455
82456/* Opcode: ResetSorter P1 * * * *
82457**
82458** Delete all contents from the ephemeral table or sorter
82459** that is open on cursor P1.
82460**
82461** This opcode only works for cursors used for sorting and
82462** opened with OP_OpenEphemeral or OP_SorterOpen.
82463*/
82464case OP_ResetSorter: {
82465  VdbeCursor *pC;
82466
82467  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82468  pC = p->apCsr[pOp->p1];
82469  assert( pC!=0 );
82470  if( isSorter(pC) ){
82471    sqlite3VdbeSorterReset(db, pC->uc.pSorter);
82472  }else{
82473    assert( pC->eCurType==CURTYPE_BTREE );
82474    assert( pC->isEphemeral );
82475    rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
82476    if( rc ) goto abort_due_to_error;
82477  }
82478  break;
82479}
82480
82481/* Opcode: CreateTable P1 P2 * * *
82482** Synopsis: r[P2]=root iDb=P1
82483**
82484** Allocate a new table in the main database file if P1==0 or in the
82485** auxiliary database file if P1==1 or in an attached database if
82486** P1>1.  Write the root page number of the new table into
82487** register P2
82488**
82489** The difference between a table and an index is this:  A table must
82490** have a 4-byte integer key and can have arbitrary data.  An index
82491** has an arbitrary key but no data.
82492**
82493** See also: CreateIndex
82494*/
82495/* Opcode: CreateIndex P1 P2 * * *
82496** Synopsis: r[P2]=root iDb=P1
82497**
82498** Allocate a new index in the main database file if P1==0 or in the
82499** auxiliary database file if P1==1 or in an attached database if
82500** P1>1.  Write the root page number of the new table into
82501** register P2.
82502**
82503** See documentation on OP_CreateTable for additional information.
82504*/
82505case OP_CreateIndex:            /* out2 */
82506case OP_CreateTable: {          /* out2 */
82507  int pgno;
82508  int flags;
82509  Db *pDb;
82510
82511  pOut = out2Prerelease(p, pOp);
82512  pgno = 0;
82513  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82514  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82515  assert( p->readOnly==0 );
82516  pDb = &db->aDb[pOp->p1];
82517  assert( pDb->pBt!=0 );
82518  if( pOp->opcode==OP_CreateTable ){
82519    /* flags = BTREE_INTKEY; */
82520    flags = BTREE_INTKEY;
82521  }else{
82522    flags = BTREE_BLOBKEY;
82523  }
82524  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
82525  if( rc ) goto abort_due_to_error;
82526  pOut->u.i = pgno;
82527  break;
82528}
82529
82530/* Opcode: ParseSchema P1 * * P4 *
82531**
82532** Read and parse all entries from the SQLITE_MASTER table of database P1
82533** that match the WHERE clause P4.
82534**
82535** This opcode invokes the parser to create a new virtual machine,
82536** then runs the new virtual machine.  It is thus a re-entrant opcode.
82537*/
82538case OP_ParseSchema: {
82539  int iDb;
82540  const char *zMaster;
82541  char *zSql;
82542  InitData initData;
82543
82544  /* Any prepared statement that invokes this opcode will hold mutexes
82545  ** on every btree.  This is a prerequisite for invoking
82546  ** sqlite3InitCallback().
82547  */
82548#ifdef SQLITE_DEBUG
82549  for(iDb=0; iDb<db->nDb; iDb++){
82550    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
82551  }
82552#endif
82553
82554  iDb = pOp->p1;
82555  assert( iDb>=0 && iDb<db->nDb );
82556  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
82557  /* Used to be a conditional */ {
82558    zMaster = SCHEMA_TABLE(iDb);
82559    initData.db = db;
82560    initData.iDb = pOp->p1;
82561    initData.pzErrMsg = &p->zErrMsg;
82562    zSql = sqlite3MPrintf(db,
82563       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
82564       db->aDb[iDb].zName, zMaster, pOp->p4.z);
82565    if( zSql==0 ){
82566      rc = SQLITE_NOMEM_BKPT;
82567    }else{
82568      assert( db->init.busy==0 );
82569      db->init.busy = 1;
82570      initData.rc = SQLITE_OK;
82571      assert( !db->mallocFailed );
82572      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
82573      if( rc==SQLITE_OK ) rc = initData.rc;
82574      sqlite3DbFree(db, zSql);
82575      db->init.busy = 0;
82576    }
82577  }
82578  if( rc ){
82579    sqlite3ResetAllSchemasOfConnection(db);
82580    if( rc==SQLITE_NOMEM ){
82581      goto no_mem;
82582    }
82583    goto abort_due_to_error;
82584  }
82585  break;
82586}
82587
82588#if !defined(SQLITE_OMIT_ANALYZE)
82589/* Opcode: LoadAnalysis P1 * * * *
82590**
82591** Read the sqlite_stat1 table for database P1 and load the content
82592** of that table into the internal index hash table.  This will cause
82593** the analysis to be used when preparing all subsequent queries.
82594*/
82595case OP_LoadAnalysis: {
82596  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82597  rc = sqlite3AnalysisLoad(db, pOp->p1);
82598  if( rc ) goto abort_due_to_error;
82599  break;
82600}
82601#endif /* !defined(SQLITE_OMIT_ANALYZE) */
82602
82603/* Opcode: DropTable P1 * * P4 *
82604**
82605** Remove the internal (in-memory) data structures that describe
82606** the table named P4 in database P1.  This is called after a table
82607** is dropped from disk (using the Destroy opcode) in order to keep
82608** the internal representation of the
82609** schema consistent with what is on disk.
82610*/
82611case OP_DropTable: {
82612  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
82613  break;
82614}
82615
82616/* Opcode: DropIndex P1 * * P4 *
82617**
82618** Remove the internal (in-memory) data structures that describe
82619** the index named P4 in database P1.  This is called after an index
82620** is dropped from disk (using the Destroy opcode)
82621** in order to keep the internal representation of the
82622** schema consistent with what is on disk.
82623*/
82624case OP_DropIndex: {
82625  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
82626  break;
82627}
82628
82629/* Opcode: DropTrigger P1 * * P4 *
82630**
82631** Remove the internal (in-memory) data structures that describe
82632** the trigger named P4 in database P1.  This is called after a trigger
82633** is dropped from disk (using the Destroy opcode) in order to keep
82634** the internal representation of the
82635** schema consistent with what is on disk.
82636*/
82637case OP_DropTrigger: {
82638  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
82639  break;
82640}
82641
82642
82643#ifndef SQLITE_OMIT_INTEGRITY_CHECK
82644/* Opcode: IntegrityCk P1 P2 P3 P4 P5
82645**
82646** Do an analysis of the currently open database.  Store in
82647** register P1 the text of an error message describing any problems.
82648** If no problems are found, store a NULL in register P1.
82649**
82650** The register P3 contains the maximum number of allowed errors.
82651** At most reg(P3) errors will be reported.
82652** In other words, the analysis stops as soon as reg(P1) errors are
82653** seen.  Reg(P1) is updated with the number of errors remaining.
82654**
82655** The root page numbers of all tables in the database are integers
82656** stored in P4_INTARRAY argument.
82657**
82658** If P5 is not zero, the check is done on the auxiliary database
82659** file, not the main database file.
82660**
82661** This opcode is used to implement the integrity_check pragma.
82662*/
82663case OP_IntegrityCk: {
82664  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
82665  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
82666  int nErr;       /* Number of errors reported */
82667  char *z;        /* Text of the error report */
82668  Mem *pnErr;     /* Register keeping track of errors remaining */
82669
82670  assert( p->bIsReader );
82671  nRoot = pOp->p2;
82672  aRoot = pOp->p4.ai;
82673  assert( nRoot>0 );
82674  assert( aRoot[nRoot]==0 );
82675  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82676  pnErr = &aMem[pOp->p3];
82677  assert( (pnErr->flags & MEM_Int)!=0 );
82678  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
82679  pIn1 = &aMem[pOp->p1];
82680  assert( pOp->p5<db->nDb );
82681  assert( DbMaskTest(p->btreeMask, pOp->p5) );
82682  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
82683                                 (int)pnErr->u.i, &nErr);
82684  pnErr->u.i -= nErr;
82685  sqlite3VdbeMemSetNull(pIn1);
82686  if( nErr==0 ){
82687    assert( z==0 );
82688  }else if( z==0 ){
82689    goto no_mem;
82690  }else{
82691    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
82692  }
82693  UPDATE_MAX_BLOBSIZE(pIn1);
82694  sqlite3VdbeChangeEncoding(pIn1, encoding);
82695  break;
82696}
82697#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
82698
82699/* Opcode: RowSetAdd P1 P2 * * *
82700** Synopsis:  rowset(P1)=r[P2]
82701**
82702** Insert the integer value held by register P2 into a boolean index
82703** held in register P1.
82704**
82705** An assertion fails if P2 is not an integer.
82706*/
82707case OP_RowSetAdd: {       /* in1, in2 */
82708  pIn1 = &aMem[pOp->p1];
82709  pIn2 = &aMem[pOp->p2];
82710  assert( (pIn2->flags & MEM_Int)!=0 );
82711  if( (pIn1->flags & MEM_RowSet)==0 ){
82712    sqlite3VdbeMemSetRowSet(pIn1);
82713    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82714  }
82715  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
82716  break;
82717}
82718
82719/* Opcode: RowSetRead P1 P2 P3 * *
82720** Synopsis:  r[P3]=rowset(P1)
82721**
82722** Extract the smallest value from boolean index P1 and put that value into
82723** register P3.  Or, if boolean index P1 is initially empty, leave P3
82724** unchanged and jump to instruction P2.
82725*/
82726case OP_RowSetRead: {       /* jump, in1, out3 */
82727  i64 val;
82728
82729  pIn1 = &aMem[pOp->p1];
82730  if( (pIn1->flags & MEM_RowSet)==0
82731   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
82732  ){
82733    /* The boolean index is empty */
82734    sqlite3VdbeMemSetNull(pIn1);
82735    VdbeBranchTaken(1,2);
82736    goto jump_to_p2_and_check_for_interrupt;
82737  }else{
82738    /* A value was pulled from the index */
82739    VdbeBranchTaken(0,2);
82740    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
82741  }
82742  goto check_for_interrupt;
82743}
82744
82745/* Opcode: RowSetTest P1 P2 P3 P4
82746** Synopsis: if r[P3] in rowset(P1) goto P2
82747**
82748** Register P3 is assumed to hold a 64-bit integer value. If register P1
82749** contains a RowSet object and that RowSet object contains
82750** the value held in P3, jump to register P2. Otherwise, insert the
82751** integer in P3 into the RowSet and continue on to the
82752** next opcode.
82753**
82754** The RowSet object is optimized for the case where successive sets
82755** of integers, where each set contains no duplicates. Each set
82756** of values is identified by a unique P4 value. The first set
82757** must have P4==0, the final set P4=-1.  P4 must be either -1 or
82758** non-negative.  For non-negative values of P4 only the lower 4
82759** bits are significant.
82760**
82761** This allows optimizations: (a) when P4==0 there is no need to test
82762** the rowset object for P3, as it is guaranteed not to contain it,
82763** (b) when P4==-1 there is no need to insert the value, as it will
82764** never be tested for, and (c) when a value that is part of set X is
82765** inserted, there is no need to search to see if the same value was
82766** previously inserted as part of set X (only if it was previously
82767** inserted as part of some other set).
82768*/
82769case OP_RowSetTest: {                     /* jump, in1, in3 */
82770  int iSet;
82771  int exists;
82772
82773  pIn1 = &aMem[pOp->p1];
82774  pIn3 = &aMem[pOp->p3];
82775  iSet = pOp->p4.i;
82776  assert( pIn3->flags&MEM_Int );
82777
82778  /* If there is anything other than a rowset object in memory cell P1,
82779  ** delete it now and initialize P1 with an empty rowset
82780  */
82781  if( (pIn1->flags & MEM_RowSet)==0 ){
82782    sqlite3VdbeMemSetRowSet(pIn1);
82783    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82784  }
82785
82786  assert( pOp->p4type==P4_INT32 );
82787  assert( iSet==-1 || iSet>=0 );
82788  if( iSet ){
82789    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
82790    VdbeBranchTaken(exists!=0,2);
82791    if( exists ) goto jump_to_p2;
82792  }
82793  if( iSet>=0 ){
82794    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
82795  }
82796  break;
82797}
82798
82799
82800#ifndef SQLITE_OMIT_TRIGGER
82801
82802/* Opcode: Program P1 P2 P3 P4 P5
82803**
82804** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
82805**
82806** P1 contains the address of the memory cell that contains the first memory
82807** cell in an array of values used as arguments to the sub-program. P2
82808** contains the address to jump to if the sub-program throws an IGNORE
82809** exception using the RAISE() function. Register P3 contains the address
82810** of a memory cell in this (the parent) VM that is used to allocate the
82811** memory required by the sub-vdbe at runtime.
82812**
82813** P4 is a pointer to the VM containing the trigger program.
82814**
82815** If P5 is non-zero, then recursive program invocation is enabled.
82816*/
82817case OP_Program: {        /* jump */
82818  int nMem;               /* Number of memory registers for sub-program */
82819  int nByte;              /* Bytes of runtime space required for sub-program */
82820  Mem *pRt;               /* Register to allocate runtime space */
82821  Mem *pMem;              /* Used to iterate through memory cells */
82822  Mem *pEnd;              /* Last memory cell in new array */
82823  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
82824  SubProgram *pProgram;   /* Sub-program to execute */
82825  void *t;                /* Token identifying trigger */
82826
82827  pProgram = pOp->p4.pProgram;
82828  pRt = &aMem[pOp->p3];
82829  assert( pProgram->nOp>0 );
82830
82831  /* If the p5 flag is clear, then recursive invocation of triggers is
82832  ** disabled for backwards compatibility (p5 is set if this sub-program
82833  ** is really a trigger, not a foreign key action, and the flag set
82834  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
82835  **
82836  ** It is recursive invocation of triggers, at the SQL level, that is
82837  ** disabled. In some cases a single trigger may generate more than one
82838  ** SubProgram (if the trigger may be executed with more than one different
82839  ** ON CONFLICT algorithm). SubProgram structures associated with a
82840  ** single trigger all have the same value for the SubProgram.token
82841  ** variable.  */
82842  if( pOp->p5 ){
82843    t = pProgram->token;
82844    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
82845    if( pFrame ) break;
82846  }
82847
82848  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
82849    rc = SQLITE_ERROR;
82850    sqlite3VdbeError(p, "too many levels of trigger recursion");
82851    goto abort_due_to_error;
82852  }
82853
82854  /* Register pRt is used to store the memory required to save the state
82855  ** of the current program, and the memory required at runtime to execute
82856  ** the trigger program. If this trigger has been fired before, then pRt
82857  ** is already allocated. Otherwise, it must be initialized.  */
82858  if( (pRt->flags&MEM_Frame)==0 ){
82859    /* SubProgram.nMem is set to the number of memory cells used by the
82860    ** program stored in SubProgram.aOp. As well as these, one memory
82861    ** cell is required for each cursor used by the program. Set local
82862    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
82863    */
82864    nMem = pProgram->nMem + pProgram->nCsr;
82865    assert( nMem>0 );
82866    if( pProgram->nCsr==0 ) nMem++;
82867    nByte = ROUND8(sizeof(VdbeFrame))
82868              + nMem * sizeof(Mem)
82869              + pProgram->nCsr * sizeof(VdbeCursor *)
82870              + pProgram->nOnce * sizeof(u8);
82871    pFrame = sqlite3DbMallocZero(db, nByte);
82872    if( !pFrame ){
82873      goto no_mem;
82874    }
82875    sqlite3VdbeMemRelease(pRt);
82876    pRt->flags = MEM_Frame;
82877    pRt->u.pFrame = pFrame;
82878
82879    pFrame->v = p;
82880    pFrame->nChildMem = nMem;
82881    pFrame->nChildCsr = pProgram->nCsr;
82882    pFrame->pc = (int)(pOp - aOp);
82883    pFrame->aMem = p->aMem;
82884    pFrame->nMem = p->nMem;
82885    pFrame->apCsr = p->apCsr;
82886    pFrame->nCursor = p->nCursor;
82887    pFrame->aOp = p->aOp;
82888    pFrame->nOp = p->nOp;
82889    pFrame->token = pProgram->token;
82890    pFrame->aOnceFlag = p->aOnceFlag;
82891    pFrame->nOnceFlag = p->nOnceFlag;
82892#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82893    pFrame->anExec = p->anExec;
82894#endif
82895
82896    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
82897    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
82898      pMem->flags = MEM_Undefined;
82899      pMem->db = db;
82900    }
82901  }else{
82902    pFrame = pRt->u.pFrame;
82903    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
82904        || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
82905    assert( pProgram->nCsr==pFrame->nChildCsr );
82906    assert( (int)(pOp - aOp)==pFrame->pc );
82907  }
82908
82909  p->nFrame++;
82910  pFrame->pParent = p->pFrame;
82911  pFrame->lastRowid = lastRowid;
82912  pFrame->nChange = p->nChange;
82913  pFrame->nDbChange = p->db->nChange;
82914  assert( pFrame->pAuxData==0 );
82915  pFrame->pAuxData = p->pAuxData;
82916  p->pAuxData = 0;
82917  p->nChange = 0;
82918  p->pFrame = pFrame;
82919  p->aMem = aMem = VdbeFrameMem(pFrame);
82920  p->nMem = pFrame->nChildMem;
82921  p->nCursor = (u16)pFrame->nChildCsr;
82922  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
82923  p->aOp = aOp = pProgram->aOp;
82924  p->nOp = pProgram->nOp;
82925  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
82926  p->nOnceFlag = pProgram->nOnce;
82927#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82928  p->anExec = 0;
82929#endif
82930  pOp = &aOp[-1];
82931  memset(p->aOnceFlag, 0, p->nOnceFlag);
82932
82933  break;
82934}
82935
82936/* Opcode: Param P1 P2 * * *
82937**
82938** This opcode is only ever present in sub-programs called via the
82939** OP_Program instruction. Copy a value currently stored in a memory
82940** cell of the calling (parent) frame to cell P2 in the current frames
82941** address space. This is used by trigger programs to access the new.*
82942** and old.* values.
82943**
82944** The address of the cell in the parent frame is determined by adding
82945** the value of the P1 argument to the value of the P1 argument to the
82946** calling OP_Program instruction.
82947*/
82948case OP_Param: {           /* out2 */
82949  VdbeFrame *pFrame;
82950  Mem *pIn;
82951  pOut = out2Prerelease(p, pOp);
82952  pFrame = p->pFrame;
82953  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
82954  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
82955  break;
82956}
82957
82958#endif /* #ifndef SQLITE_OMIT_TRIGGER */
82959
82960#ifndef SQLITE_OMIT_FOREIGN_KEY
82961/* Opcode: FkCounter P1 P2 * * *
82962** Synopsis: fkctr[P1]+=P2
82963**
82964** Increment a "constraint counter" by P2 (P2 may be negative or positive).
82965** If P1 is non-zero, the database constraint counter is incremented
82966** (deferred foreign key constraints). Otherwise, if P1 is zero, the
82967** statement counter is incremented (immediate foreign key constraints).
82968*/
82969case OP_FkCounter: {
82970  if( db->flags & SQLITE_DeferFKs ){
82971    db->nDeferredImmCons += pOp->p2;
82972  }else if( pOp->p1 ){
82973    db->nDeferredCons += pOp->p2;
82974  }else{
82975    p->nFkConstraint += pOp->p2;
82976  }
82977  break;
82978}
82979
82980/* Opcode: FkIfZero P1 P2 * * *
82981** Synopsis: if fkctr[P1]==0 goto P2
82982**
82983** This opcode tests if a foreign key constraint-counter is currently zero.
82984** If so, jump to instruction P2. Otherwise, fall through to the next
82985** instruction.
82986**
82987** If P1 is non-zero, then the jump is taken if the database constraint-counter
82988** is zero (the one that counts deferred constraint violations). If P1 is
82989** zero, the jump is taken if the statement constraint-counter is zero
82990** (immediate foreign key constraint violations).
82991*/
82992case OP_FkIfZero: {         /* jump */
82993  if( pOp->p1 ){
82994    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
82995    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
82996  }else{
82997    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
82998    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
82999  }
83000  break;
83001}
83002#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
83003
83004#ifndef SQLITE_OMIT_AUTOINCREMENT
83005/* Opcode: MemMax P1 P2 * * *
83006** Synopsis: r[P1]=max(r[P1],r[P2])
83007**
83008** P1 is a register in the root frame of this VM (the root frame is
83009** different from the current frame if this instruction is being executed
83010** within a sub-program). Set the value of register P1 to the maximum of
83011** its current value and the value in register P2.
83012**
83013** This instruction throws an error if the memory cell is not initially
83014** an integer.
83015*/
83016case OP_MemMax: {        /* in2 */
83017  VdbeFrame *pFrame;
83018  if( p->pFrame ){
83019    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83020    pIn1 = &pFrame->aMem[pOp->p1];
83021  }else{
83022    pIn1 = &aMem[pOp->p1];
83023  }
83024  assert( memIsValid(pIn1) );
83025  sqlite3VdbeMemIntegerify(pIn1);
83026  pIn2 = &aMem[pOp->p2];
83027  sqlite3VdbeMemIntegerify(pIn2);
83028  if( pIn1->u.i<pIn2->u.i){
83029    pIn1->u.i = pIn2->u.i;
83030  }
83031  break;
83032}
83033#endif /* SQLITE_OMIT_AUTOINCREMENT */
83034
83035/* Opcode: IfPos P1 P2 P3 * *
83036** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
83037**
83038** Register P1 must contain an integer.
83039** If the value of register P1 is 1 or greater, subtract P3 from the
83040** value in P1 and jump to P2.
83041**
83042** If the initial value of register P1 is less than 1, then the
83043** value is unchanged and control passes through to the next instruction.
83044*/
83045case OP_IfPos: {        /* jump, in1 */
83046  pIn1 = &aMem[pOp->p1];
83047  assert( pIn1->flags&MEM_Int );
83048  VdbeBranchTaken( pIn1->u.i>0, 2);
83049  if( pIn1->u.i>0 ){
83050    pIn1->u.i -= pOp->p3;
83051    goto jump_to_p2;
83052  }
83053  break;
83054}
83055
83056/* Opcode: OffsetLimit P1 P2 P3 * *
83057** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
83058**
83059** This opcode performs a commonly used computation associated with
83060** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
83061** holds the offset counter.  The opcode computes the combined value
83062** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
83063** value computed is the total number of rows that will need to be
83064** visited in order to complete the query.
83065**
83066** If r[P3] is zero or negative, that means there is no OFFSET
83067** and r[P2] is set to be the value of the LIMIT, r[P1].
83068**
83069** if r[P1] is zero or negative, that means there is no LIMIT
83070** and r[P2] is set to -1.
83071**
83072** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
83073*/
83074case OP_OffsetLimit: {    /* in1, out2, in3 */
83075  pIn1 = &aMem[pOp->p1];
83076  pIn3 = &aMem[pOp->p3];
83077  pOut = out2Prerelease(p, pOp);
83078  assert( pIn1->flags & MEM_Int );
83079  assert( pIn3->flags & MEM_Int );
83080  pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
83081  break;
83082}
83083
83084/* Opcode: IfNotZero P1 P2 P3 * *
83085** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
83086**
83087** Register P1 must contain an integer.  If the content of register P1 is
83088** initially nonzero, then subtract P3 from the value in register P1 and
83089** jump to P2.  If register P1 is initially zero, leave it unchanged
83090** and fall through.
83091*/
83092case OP_IfNotZero: {        /* jump, in1 */
83093  pIn1 = &aMem[pOp->p1];
83094  assert( pIn1->flags&MEM_Int );
83095  VdbeBranchTaken(pIn1->u.i<0, 2);
83096  if( pIn1->u.i ){
83097     pIn1->u.i -= pOp->p3;
83098     goto jump_to_p2;
83099  }
83100  break;
83101}
83102
83103/* Opcode: DecrJumpZero P1 P2 * * *
83104** Synopsis: if (--r[P1])==0 goto P2
83105**
83106** Register P1 must hold an integer.  Decrement the value in register P1
83107** then jump to P2 if the new value is exactly zero.
83108*/
83109case OP_DecrJumpZero: {      /* jump, in1 */
83110  pIn1 = &aMem[pOp->p1];
83111  assert( pIn1->flags&MEM_Int );
83112  pIn1->u.i--;
83113  VdbeBranchTaken(pIn1->u.i==0, 2);
83114  if( pIn1->u.i==0 ) goto jump_to_p2;
83115  break;
83116}
83117
83118
83119/* Opcode: AggStep0 * P2 P3 P4 P5
83120** Synopsis: accum=r[P3] step(r[P2@P5])
83121**
83122** Execute the step function for an aggregate.  The
83123** function has P5 arguments.   P4 is a pointer to the FuncDef
83124** structure that specifies the function.  Register P3 is the
83125** accumulator.
83126**
83127** The P5 arguments are taken from register P2 and its
83128** successors.
83129*/
83130/* Opcode: AggStep * P2 P3 P4 P5
83131** Synopsis: accum=r[P3] step(r[P2@P5])
83132**
83133** Execute the step function for an aggregate.  The
83134** function has P5 arguments.   P4 is a pointer to an sqlite3_context
83135** object that is used to run the function.  Register P3 is
83136** as the accumulator.
83137**
83138** The P5 arguments are taken from register P2 and its
83139** successors.
83140**
83141** This opcode is initially coded as OP_AggStep0.  On first evaluation,
83142** the FuncDef stored in P4 is converted into an sqlite3_context and
83143** the opcode is changed.  In this way, the initialization of the
83144** sqlite3_context only happens once, instead of on each call to the
83145** step function.
83146*/
83147case OP_AggStep0: {
83148  int n;
83149  sqlite3_context *pCtx;
83150
83151  assert( pOp->p4type==P4_FUNCDEF );
83152  n = pOp->p5;
83153  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83154  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
83155  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
83156  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
83157  if( pCtx==0 ) goto no_mem;
83158  pCtx->pMem = 0;
83159  pCtx->pFunc = pOp->p4.pFunc;
83160  pCtx->iOp = (int)(pOp - aOp);
83161  pCtx->pVdbe = p;
83162  pCtx->argc = n;
83163  pOp->p4type = P4_FUNCCTX;
83164  pOp->p4.pCtx = pCtx;
83165  pOp->opcode = OP_AggStep;
83166  /* Fall through into OP_AggStep */
83167}
83168case OP_AggStep: {
83169  int i;
83170  sqlite3_context *pCtx;
83171  Mem *pMem;
83172  Mem t;
83173
83174  assert( pOp->p4type==P4_FUNCCTX );
83175  pCtx = pOp->p4.pCtx;
83176  pMem = &aMem[pOp->p3];
83177
83178  /* If this function is inside of a trigger, the register array in aMem[]
83179  ** might change from one evaluation to the next.  The next block of code
83180  ** checks to see if the register array has changed, and if so it
83181  ** reinitializes the relavant parts of the sqlite3_context object */
83182  if( pCtx->pMem != pMem ){
83183    pCtx->pMem = pMem;
83184    for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
83185  }
83186
83187#ifdef SQLITE_DEBUG
83188  for(i=0; i<pCtx->argc; i++){
83189    assert( memIsValid(pCtx->argv[i]) );
83190    REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
83191  }
83192#endif
83193
83194  pMem->n++;
83195  sqlite3VdbeMemInit(&t, db, MEM_Null);
83196  pCtx->pOut = &t;
83197  pCtx->fErrorOrAux = 0;
83198  pCtx->skipFlag = 0;
83199  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
83200  if( pCtx->fErrorOrAux ){
83201    if( pCtx->isError ){
83202      sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
83203      rc = pCtx->isError;
83204    }
83205    sqlite3VdbeMemRelease(&t);
83206    if( rc ) goto abort_due_to_error;
83207  }else{
83208    assert( t.flags==MEM_Null );
83209  }
83210  if( pCtx->skipFlag ){
83211    assert( pOp[-1].opcode==OP_CollSeq );
83212    i = pOp[-1].p1;
83213    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
83214  }
83215  break;
83216}
83217
83218/* Opcode: AggFinal P1 P2 * P4 *
83219** Synopsis: accum=r[P1] N=P2
83220**
83221** Execute the finalizer function for an aggregate.  P1 is
83222** the memory location that is the accumulator for the aggregate.
83223**
83224** P2 is the number of arguments that the step function takes and
83225** P4 is a pointer to the FuncDef for this function.  The P2
83226** argument is not used by this opcode.  It is only there to disambiguate
83227** functions that can take varying numbers of arguments.  The
83228** P4 argument is only needed for the degenerate case where
83229** the step function was not previously called.
83230*/
83231case OP_AggFinal: {
83232  Mem *pMem;
83233  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
83234  pMem = &aMem[pOp->p1];
83235  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
83236  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
83237  if( rc ){
83238    sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
83239    goto abort_due_to_error;
83240  }
83241  sqlite3VdbeChangeEncoding(pMem, encoding);
83242  UPDATE_MAX_BLOBSIZE(pMem);
83243  if( sqlite3VdbeMemTooBig(pMem) ){
83244    goto too_big;
83245  }
83246  break;
83247}
83248
83249#ifndef SQLITE_OMIT_WAL
83250/* Opcode: Checkpoint P1 P2 P3 * *
83251**
83252** Checkpoint database P1. This is a no-op if P1 is not currently in
83253** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
83254** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
83255** SQLITE_BUSY or not, respectively.  Write the number of pages in the
83256** WAL after the checkpoint into mem[P3+1] and the number of pages
83257** in the WAL that have been checkpointed after the checkpoint
83258** completes into mem[P3+2].  However on an error, mem[P3+1] and
83259** mem[P3+2] are initialized to -1.
83260*/
83261case OP_Checkpoint: {
83262  int i;                          /* Loop counter */
83263  int aRes[3];                    /* Results */
83264  Mem *pMem;                      /* Write results here */
83265
83266  assert( p->readOnly==0 );
83267  aRes[0] = 0;
83268  aRes[1] = aRes[2] = -1;
83269  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
83270       || pOp->p2==SQLITE_CHECKPOINT_FULL
83271       || pOp->p2==SQLITE_CHECKPOINT_RESTART
83272       || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
83273  );
83274  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
83275  if( rc ){
83276    if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
83277    rc = SQLITE_OK;
83278    aRes[0] = 1;
83279  }
83280  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
83281    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
83282  }
83283  break;
83284};
83285#endif
83286
83287#ifndef SQLITE_OMIT_PRAGMA
83288/* Opcode: JournalMode P1 P2 P3 * *
83289**
83290** Change the journal mode of database P1 to P3. P3 must be one of the
83291** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
83292** modes (delete, truncate, persist, off and memory), this is a simple
83293** operation. No IO is required.
83294**
83295** If changing into or out of WAL mode the procedure is more complicated.
83296**
83297** Write a string containing the final journal-mode to register P2.
83298*/
83299case OP_JournalMode: {    /* out2 */
83300  Btree *pBt;                     /* Btree to change journal mode of */
83301  Pager *pPager;                  /* Pager associated with pBt */
83302  int eNew;                       /* New journal mode */
83303  int eOld;                       /* The old journal mode */
83304#ifndef SQLITE_OMIT_WAL
83305  const char *zFilename;          /* Name of database file for pPager */
83306#endif
83307
83308  pOut = out2Prerelease(p, pOp);
83309  eNew = pOp->p3;
83310  assert( eNew==PAGER_JOURNALMODE_DELETE
83311       || eNew==PAGER_JOURNALMODE_TRUNCATE
83312       || eNew==PAGER_JOURNALMODE_PERSIST
83313       || eNew==PAGER_JOURNALMODE_OFF
83314       || eNew==PAGER_JOURNALMODE_MEMORY
83315       || eNew==PAGER_JOURNALMODE_WAL
83316       || eNew==PAGER_JOURNALMODE_QUERY
83317  );
83318  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83319  assert( p->readOnly==0 );
83320
83321  pBt = db->aDb[pOp->p1].pBt;
83322  pPager = sqlite3BtreePager(pBt);
83323  eOld = sqlite3PagerGetJournalMode(pPager);
83324  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
83325  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
83326
83327#ifndef SQLITE_OMIT_WAL
83328  zFilename = sqlite3PagerFilename(pPager, 1);
83329
83330  /* Do not allow a transition to journal_mode=WAL for a database
83331  ** in temporary storage or if the VFS does not support shared memory
83332  */
83333  if( eNew==PAGER_JOURNALMODE_WAL
83334   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
83335       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
83336  ){
83337    eNew = eOld;
83338  }
83339
83340  if( (eNew!=eOld)
83341   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
83342  ){
83343    if( !db->autoCommit || db->nVdbeRead>1 ){
83344      rc = SQLITE_ERROR;
83345      sqlite3VdbeError(p,
83346          "cannot change %s wal mode from within a transaction",
83347          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
83348      );
83349      goto abort_due_to_error;
83350    }else{
83351
83352      if( eOld==PAGER_JOURNALMODE_WAL ){
83353        /* If leaving WAL mode, close the log file. If successful, the call
83354        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
83355        ** file. An EXCLUSIVE lock may still be held on the database file
83356        ** after a successful return.
83357        */
83358        rc = sqlite3PagerCloseWal(pPager);
83359        if( rc==SQLITE_OK ){
83360          sqlite3PagerSetJournalMode(pPager, eNew);
83361        }
83362      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
83363        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
83364        ** as an intermediate */
83365        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
83366      }
83367
83368      /* Open a transaction on the database file. Regardless of the journal
83369      ** mode, this transaction always uses a rollback journal.
83370      */
83371      assert( sqlite3BtreeIsInTrans(pBt)==0 );
83372      if( rc==SQLITE_OK ){
83373        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
83374      }
83375    }
83376  }
83377#endif /* ifndef SQLITE_OMIT_WAL */
83378
83379  if( rc ) eNew = eOld;
83380  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
83381
83382  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
83383  pOut->z = (char *)sqlite3JournalModename(eNew);
83384  pOut->n = sqlite3Strlen30(pOut->z);
83385  pOut->enc = SQLITE_UTF8;
83386  sqlite3VdbeChangeEncoding(pOut, encoding);
83387  if( rc ) goto abort_due_to_error;
83388  break;
83389};
83390#endif /* SQLITE_OMIT_PRAGMA */
83391
83392#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
83393/* Opcode: Vacuum * * * * *
83394**
83395** Vacuum the entire database.  This opcode will cause other virtual
83396** machines to be created and run.  It may not be called from within
83397** a transaction.
83398*/
83399case OP_Vacuum: {
83400  assert( p->readOnly==0 );
83401  rc = sqlite3RunVacuum(&p->zErrMsg, db);
83402  if( rc ) goto abort_due_to_error;
83403  break;
83404}
83405#endif
83406
83407#if !defined(SQLITE_OMIT_AUTOVACUUM)
83408/* Opcode: IncrVacuum P1 P2 * * *
83409**
83410** Perform a single step of the incremental vacuum procedure on
83411** the P1 database. If the vacuum has finished, jump to instruction
83412** P2. Otherwise, fall through to the next instruction.
83413*/
83414case OP_IncrVacuum: {        /* jump */
83415  Btree *pBt;
83416
83417  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83418  assert( DbMaskTest(p->btreeMask, pOp->p1) );
83419  assert( p->readOnly==0 );
83420  pBt = db->aDb[pOp->p1].pBt;
83421  rc = sqlite3BtreeIncrVacuum(pBt);
83422  VdbeBranchTaken(rc==SQLITE_DONE,2);
83423  if( rc ){
83424    if( rc!=SQLITE_DONE ) goto abort_due_to_error;
83425    rc = SQLITE_OK;
83426    goto jump_to_p2;
83427  }
83428  break;
83429}
83430#endif
83431
83432/* Opcode: Expire P1 * * * *
83433**
83434** Cause precompiled statements to expire.  When an expired statement
83435** is executed using sqlite3_step() it will either automatically
83436** reprepare itself (if it was originally created using sqlite3_prepare_v2())
83437** or it will fail with SQLITE_SCHEMA.
83438**
83439** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
83440** then only the currently executing statement is expired.
83441*/
83442case OP_Expire: {
83443  if( !pOp->p1 ){
83444    sqlite3ExpirePreparedStatements(db);
83445  }else{
83446    p->expired = 1;
83447  }
83448  break;
83449}
83450
83451#ifndef SQLITE_OMIT_SHARED_CACHE
83452/* Opcode: TableLock P1 P2 P3 P4 *
83453** Synopsis: iDb=P1 root=P2 write=P3
83454**
83455** Obtain a lock on a particular table. This instruction is only used when
83456** the shared-cache feature is enabled.
83457**
83458** P1 is the index of the database in sqlite3.aDb[] of the database
83459** on which the lock is acquired.  A readlock is obtained if P3==0 or
83460** a write lock if P3==1.
83461**
83462** P2 contains the root-page of the table to lock.
83463**
83464** P4 contains a pointer to the name of the table being locked. This is only
83465** used to generate an error message if the lock cannot be obtained.
83466*/
83467case OP_TableLock: {
83468  u8 isWriteLock = (u8)pOp->p3;
83469  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
83470    int p1 = pOp->p1;
83471    assert( p1>=0 && p1<db->nDb );
83472    assert( DbMaskTest(p->btreeMask, p1) );
83473    assert( isWriteLock==0 || isWriteLock==1 );
83474    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
83475    if( rc ){
83476      if( (rc&0xFF)==SQLITE_LOCKED ){
83477        const char *z = pOp->p4.z;
83478        sqlite3VdbeError(p, "database table is locked: %s", z);
83479      }
83480      goto abort_due_to_error;
83481    }
83482  }
83483  break;
83484}
83485#endif /* SQLITE_OMIT_SHARED_CACHE */
83486
83487#ifndef SQLITE_OMIT_VIRTUALTABLE
83488/* Opcode: VBegin * * * P4 *
83489**
83490** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
83491** xBegin method for that table.
83492**
83493** Also, whether or not P4 is set, check that this is not being called from
83494** within a callback to a virtual table xSync() method. If it is, the error
83495** code will be set to SQLITE_LOCKED.
83496*/
83497case OP_VBegin: {
83498  VTable *pVTab;
83499  pVTab = pOp->p4.pVtab;
83500  rc = sqlite3VtabBegin(db, pVTab);
83501  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
83502  if( rc ) goto abort_due_to_error;
83503  break;
83504}
83505#endif /* SQLITE_OMIT_VIRTUALTABLE */
83506
83507#ifndef SQLITE_OMIT_VIRTUALTABLE
83508/* Opcode: VCreate P1 P2 * * *
83509**
83510** P2 is a register that holds the name of a virtual table in database
83511** P1. Call the xCreate method for that table.
83512*/
83513case OP_VCreate: {
83514  Mem sMem;          /* For storing the record being decoded */
83515  const char *zTab;  /* Name of the virtual table */
83516
83517  memset(&sMem, 0, sizeof(sMem));
83518  sMem.db = db;
83519  /* Because P2 is always a static string, it is impossible for the
83520  ** sqlite3VdbeMemCopy() to fail */
83521  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
83522  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
83523  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
83524  assert( rc==SQLITE_OK );
83525  zTab = (const char*)sqlite3_value_text(&sMem);
83526  assert( zTab || db->mallocFailed );
83527  if( zTab ){
83528    rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
83529  }
83530  sqlite3VdbeMemRelease(&sMem);
83531  if( rc ) goto abort_due_to_error;
83532  break;
83533}
83534#endif /* SQLITE_OMIT_VIRTUALTABLE */
83535
83536#ifndef SQLITE_OMIT_VIRTUALTABLE
83537/* Opcode: VDestroy P1 * * P4 *
83538**
83539** P4 is the name of a virtual table in database P1.  Call the xDestroy method
83540** of that table.
83541*/
83542case OP_VDestroy: {
83543  db->nVDestroy++;
83544  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
83545  db->nVDestroy--;
83546  if( rc ) goto abort_due_to_error;
83547  break;
83548}
83549#endif /* SQLITE_OMIT_VIRTUALTABLE */
83550
83551#ifndef SQLITE_OMIT_VIRTUALTABLE
83552/* Opcode: VOpen P1 * * P4 *
83553**
83554** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83555** P1 is a cursor number.  This opcode opens a cursor to the virtual
83556** table and stores that cursor in P1.
83557*/
83558case OP_VOpen: {
83559  VdbeCursor *pCur;
83560  sqlite3_vtab_cursor *pVCur;
83561  sqlite3_vtab *pVtab;
83562  const sqlite3_module *pModule;
83563
83564  assert( p->bIsReader );
83565  pCur = 0;
83566  pVCur = 0;
83567  pVtab = pOp->p4.pVtab->pVtab;
83568  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83569    rc = SQLITE_LOCKED;
83570    goto abort_due_to_error;
83571  }
83572  pModule = pVtab->pModule;
83573  rc = pModule->xOpen(pVtab, &pVCur);
83574  sqlite3VtabImportErrmsg(p, pVtab);
83575  if( rc ) goto abort_due_to_error;
83576
83577  /* Initialize sqlite3_vtab_cursor base class */
83578  pVCur->pVtab = pVtab;
83579
83580  /* Initialize vdbe cursor object */
83581  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
83582  if( pCur ){
83583    pCur->uc.pVCur = pVCur;
83584    pVtab->nRef++;
83585  }else{
83586    assert( db->mallocFailed );
83587    pModule->xClose(pVCur);
83588    goto no_mem;
83589  }
83590  break;
83591}
83592#endif /* SQLITE_OMIT_VIRTUALTABLE */
83593
83594#ifndef SQLITE_OMIT_VIRTUALTABLE
83595/* Opcode: VFilter P1 P2 P3 P4 *
83596** Synopsis: iplan=r[P3] zplan='P4'
83597**
83598** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
83599** the filtered result set is empty.
83600**
83601** P4 is either NULL or a string that was generated by the xBestIndex
83602** method of the module.  The interpretation of the P4 string is left
83603** to the module implementation.
83604**
83605** This opcode invokes the xFilter method on the virtual table specified
83606** by P1.  The integer query plan parameter to xFilter is stored in register
83607** P3. Register P3+1 stores the argc parameter to be passed to the
83608** xFilter method. Registers P3+2..P3+1+argc are the argc
83609** additional parameters which are passed to
83610** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
83611**
83612** A jump is made to P2 if the result set after filtering would be empty.
83613*/
83614case OP_VFilter: {   /* jump */
83615  int nArg;
83616  int iQuery;
83617  const sqlite3_module *pModule;
83618  Mem *pQuery;
83619  Mem *pArgc;
83620  sqlite3_vtab_cursor *pVCur;
83621  sqlite3_vtab *pVtab;
83622  VdbeCursor *pCur;
83623  int res;
83624  int i;
83625  Mem **apArg;
83626
83627  pQuery = &aMem[pOp->p3];
83628  pArgc = &pQuery[1];
83629  pCur = p->apCsr[pOp->p1];
83630  assert( memIsValid(pQuery) );
83631  REGISTER_TRACE(pOp->p3, pQuery);
83632  assert( pCur->eCurType==CURTYPE_VTAB );
83633  pVCur = pCur->uc.pVCur;
83634  pVtab = pVCur->pVtab;
83635  pModule = pVtab->pModule;
83636
83637  /* Grab the index number and argc parameters */
83638  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
83639  nArg = (int)pArgc->u.i;
83640  iQuery = (int)pQuery->u.i;
83641
83642  /* Invoke the xFilter method */
83643  res = 0;
83644  apArg = p->apArg;
83645  for(i = 0; i<nArg; i++){
83646    apArg[i] = &pArgc[i+1];
83647  }
83648  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
83649  sqlite3VtabImportErrmsg(p, pVtab);
83650  if( rc ) goto abort_due_to_error;
83651  res = pModule->xEof(pVCur);
83652  pCur->nullRow = 0;
83653  VdbeBranchTaken(res!=0,2);
83654  if( res ) goto jump_to_p2;
83655  break;
83656}
83657#endif /* SQLITE_OMIT_VIRTUALTABLE */
83658
83659#ifndef SQLITE_OMIT_VIRTUALTABLE
83660/* Opcode: VColumn P1 P2 P3 * *
83661** Synopsis: r[P3]=vcolumn(P2)
83662**
83663** Store the value of the P2-th column of
83664** the row of the virtual-table that the
83665** P1 cursor is pointing to into register P3.
83666*/
83667case OP_VColumn: {
83668  sqlite3_vtab *pVtab;
83669  const sqlite3_module *pModule;
83670  Mem *pDest;
83671  sqlite3_context sContext;
83672
83673  VdbeCursor *pCur = p->apCsr[pOp->p1];
83674  assert( pCur->eCurType==CURTYPE_VTAB );
83675  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83676  pDest = &aMem[pOp->p3];
83677  memAboutToChange(p, pDest);
83678  if( pCur->nullRow ){
83679    sqlite3VdbeMemSetNull(pDest);
83680    break;
83681  }
83682  pVtab = pCur->uc.pVCur->pVtab;
83683  pModule = pVtab->pModule;
83684  assert( pModule->xColumn );
83685  memset(&sContext, 0, sizeof(sContext));
83686  sContext.pOut = pDest;
83687  MemSetTypeFlag(pDest, MEM_Null);
83688  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
83689  sqlite3VtabImportErrmsg(p, pVtab);
83690  if( sContext.isError ){
83691    rc = sContext.isError;
83692  }
83693  sqlite3VdbeChangeEncoding(pDest, encoding);
83694  REGISTER_TRACE(pOp->p3, pDest);
83695  UPDATE_MAX_BLOBSIZE(pDest);
83696
83697  if( sqlite3VdbeMemTooBig(pDest) ){
83698    goto too_big;
83699  }
83700  if( rc ) goto abort_due_to_error;
83701  break;
83702}
83703#endif /* SQLITE_OMIT_VIRTUALTABLE */
83704
83705#ifndef SQLITE_OMIT_VIRTUALTABLE
83706/* Opcode: VNext P1 P2 * * *
83707**
83708** Advance virtual table P1 to the next row in its result set and
83709** jump to instruction P2.  Or, if the virtual table has reached
83710** the end of its result set, then fall through to the next instruction.
83711*/
83712case OP_VNext: {   /* jump */
83713  sqlite3_vtab *pVtab;
83714  const sqlite3_module *pModule;
83715  int res;
83716  VdbeCursor *pCur;
83717
83718  res = 0;
83719  pCur = p->apCsr[pOp->p1];
83720  assert( pCur->eCurType==CURTYPE_VTAB );
83721  if( pCur->nullRow ){
83722    break;
83723  }
83724  pVtab = pCur->uc.pVCur->pVtab;
83725  pModule = pVtab->pModule;
83726  assert( pModule->xNext );
83727
83728  /* Invoke the xNext() method of the module. There is no way for the
83729  ** underlying implementation to return an error if one occurs during
83730  ** xNext(). Instead, if an error occurs, true is returned (indicating that
83731  ** data is available) and the error code returned when xColumn or
83732  ** some other method is next invoked on the save virtual table cursor.
83733  */
83734  rc = pModule->xNext(pCur->uc.pVCur);
83735  sqlite3VtabImportErrmsg(p, pVtab);
83736  if( rc ) goto abort_due_to_error;
83737  res = pModule->xEof(pCur->uc.pVCur);
83738  VdbeBranchTaken(!res,2);
83739  if( !res ){
83740    /* If there is data, jump to P2 */
83741    goto jump_to_p2_and_check_for_interrupt;
83742  }
83743  goto check_for_interrupt;
83744}
83745#endif /* SQLITE_OMIT_VIRTUALTABLE */
83746
83747#ifndef SQLITE_OMIT_VIRTUALTABLE
83748/* Opcode: VRename P1 * * P4 *
83749**
83750** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83751** This opcode invokes the corresponding xRename method. The value
83752** in register P1 is passed as the zName argument to the xRename method.
83753*/
83754case OP_VRename: {
83755  sqlite3_vtab *pVtab;
83756  Mem *pName;
83757
83758  pVtab = pOp->p4.pVtab->pVtab;
83759  pName = &aMem[pOp->p1];
83760  assert( pVtab->pModule->xRename );
83761  assert( memIsValid(pName) );
83762  assert( p->readOnly==0 );
83763  REGISTER_TRACE(pOp->p1, pName);
83764  assert( pName->flags & MEM_Str );
83765  testcase( pName->enc==SQLITE_UTF8 );
83766  testcase( pName->enc==SQLITE_UTF16BE );
83767  testcase( pName->enc==SQLITE_UTF16LE );
83768  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
83769  if( rc ) goto abort_due_to_error;
83770  rc = pVtab->pModule->xRename(pVtab, pName->z);
83771  sqlite3VtabImportErrmsg(p, pVtab);
83772  p->expired = 0;
83773  if( rc ) goto abort_due_to_error;
83774  break;
83775}
83776#endif
83777
83778#ifndef SQLITE_OMIT_VIRTUALTABLE
83779/* Opcode: VUpdate P1 P2 P3 P4 P5
83780** Synopsis: data=r[P3@P2]
83781**
83782** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83783** This opcode invokes the corresponding xUpdate method. P2 values
83784** are contiguous memory cells starting at P3 to pass to the xUpdate
83785** invocation. The value in register (P3+P2-1) corresponds to the
83786** p2th element of the argv array passed to xUpdate.
83787**
83788** The xUpdate method will do a DELETE or an INSERT or both.
83789** The argv[0] element (which corresponds to memory cell P3)
83790** is the rowid of a row to delete.  If argv[0] is NULL then no
83791** deletion occurs.  The argv[1] element is the rowid of the new
83792** row.  This can be NULL to have the virtual table select the new
83793** rowid for itself.  The subsequent elements in the array are
83794** the values of columns in the new row.
83795**
83796** If P2==1 then no insert is performed.  argv[0] is the rowid of
83797** a row to delete.
83798**
83799** P1 is a boolean flag. If it is set to true and the xUpdate call
83800** is successful, then the value returned by sqlite3_last_insert_rowid()
83801** is set to the value of the rowid for the row just inserted.
83802**
83803** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
83804** apply in the case of a constraint failure on an insert or update.
83805*/
83806case OP_VUpdate: {
83807  sqlite3_vtab *pVtab;
83808  const sqlite3_module *pModule;
83809  int nArg;
83810  int i;
83811  sqlite_int64 rowid;
83812  Mem **apArg;
83813  Mem *pX;
83814
83815  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
83816       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
83817  );
83818  assert( p->readOnly==0 );
83819  pVtab = pOp->p4.pVtab->pVtab;
83820  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83821    rc = SQLITE_LOCKED;
83822    goto abort_due_to_error;
83823  }
83824  pModule = pVtab->pModule;
83825  nArg = pOp->p2;
83826  assert( pOp->p4type==P4_VTAB );
83827  if( ALWAYS(pModule->xUpdate) ){
83828    u8 vtabOnConflict = db->vtabOnConflict;
83829    apArg = p->apArg;
83830    pX = &aMem[pOp->p3];
83831    for(i=0; i<nArg; i++){
83832      assert( memIsValid(pX) );
83833      memAboutToChange(p, pX);
83834      apArg[i] = pX;
83835      pX++;
83836    }
83837    db->vtabOnConflict = pOp->p5;
83838    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
83839    db->vtabOnConflict = vtabOnConflict;
83840    sqlite3VtabImportErrmsg(p, pVtab);
83841    if( rc==SQLITE_OK && pOp->p1 ){
83842      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
83843      db->lastRowid = lastRowid = rowid;
83844    }
83845    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
83846      if( pOp->p5==OE_Ignore ){
83847        rc = SQLITE_OK;
83848      }else{
83849        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
83850      }
83851    }else{
83852      p->nChange++;
83853    }
83854    if( rc ) goto abort_due_to_error;
83855  }
83856  break;
83857}
83858#endif /* SQLITE_OMIT_VIRTUALTABLE */
83859
83860#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
83861/* Opcode: Pagecount P1 P2 * * *
83862**
83863** Write the current number of pages in database P1 to memory cell P2.
83864*/
83865case OP_Pagecount: {            /* out2 */
83866  pOut = out2Prerelease(p, pOp);
83867  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
83868  break;
83869}
83870#endif
83871
83872
83873#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
83874/* Opcode: MaxPgcnt P1 P2 P3 * *
83875**
83876** Try to set the maximum page count for database P1 to the value in P3.
83877** Do not let the maximum page count fall below the current page count and
83878** do not change the maximum page count value if P3==0.
83879**
83880** Store the maximum page count after the change in register P2.
83881*/
83882case OP_MaxPgcnt: {            /* out2 */
83883  unsigned int newMax;
83884  Btree *pBt;
83885
83886  pOut = out2Prerelease(p, pOp);
83887  pBt = db->aDb[pOp->p1].pBt;
83888  newMax = 0;
83889  if( pOp->p3 ){
83890    newMax = sqlite3BtreeLastPage(pBt);
83891    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
83892  }
83893  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
83894  break;
83895}
83896#endif
83897
83898
83899/* Opcode: Init * P2 * P4 *
83900** Synopsis:  Start at P2
83901**
83902** Programs contain a single instance of this opcode as the very first
83903** opcode.
83904**
83905** If tracing is enabled (by the sqlite3_trace()) interface, then
83906** the UTF-8 string contained in P4 is emitted on the trace callback.
83907** Or if P4 is blank, use the string returned by sqlite3_sql().
83908**
83909** If P2 is not zero, jump to instruction P2.
83910*/
83911case OP_Init: {          /* jump */
83912  char *zTrace;
83913
83914  /* If the P4 argument is not NULL, then it must be an SQL comment string.
83915  ** The "--" string is broken up to prevent false-positives with srcck1.c.
83916  **
83917  ** This assert() provides evidence for:
83918  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
83919  ** would have been returned by the legacy sqlite3_trace() interface by
83920  ** using the X argument when X begins with "--" and invoking
83921  ** sqlite3_expanded_sql(P) otherwise.
83922  */
83923  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
83924
83925#ifndef SQLITE_OMIT_TRACE
83926  if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
83927   && !p->doingRerun
83928   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83929  ){
83930#ifndef SQLITE_OMIT_DEPRECATED
83931    if( db->mTrace & SQLITE_TRACE_LEGACY ){
83932      void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
83933      char *z = sqlite3VdbeExpandSql(p, zTrace);
83934      x(db->pTraceArg, z);
83935      sqlite3_free(z);
83936    }else
83937#endif
83938    {
83939      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
83940    }
83941  }
83942#ifdef SQLITE_USE_FCNTL_TRACE
83943  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
83944  if( zTrace ){
83945    int i;
83946    for(i=0; i<db->nDb; i++){
83947      if( DbMaskTest(p->btreeMask, i)==0 ) continue;
83948      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
83949    }
83950  }
83951#endif /* SQLITE_USE_FCNTL_TRACE */
83952#ifdef SQLITE_DEBUG
83953  if( (db->flags & SQLITE_SqlTrace)!=0
83954   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83955  ){
83956    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
83957  }
83958#endif /* SQLITE_DEBUG */
83959#endif /* SQLITE_OMIT_TRACE */
83960  if( pOp->p2 ) goto jump_to_p2;
83961  break;
83962}
83963
83964#ifdef SQLITE_ENABLE_CURSOR_HINTS
83965/* Opcode: CursorHint P1 * * P4 *
83966**
83967** Provide a hint to cursor P1 that it only needs to return rows that
83968** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
83969** to values currently held in registers.  TK_COLUMN terms in the P4
83970** expression refer to columns in the b-tree to which cursor P1 is pointing.
83971*/
83972case OP_CursorHint: {
83973  VdbeCursor *pC;
83974
83975  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83976  assert( pOp->p4type==P4_EXPR );
83977  pC = p->apCsr[pOp->p1];
83978  if( pC ){
83979    assert( pC->eCurType==CURTYPE_BTREE );
83980    sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
83981                           pOp->p4.pExpr, aMem);
83982  }
83983  break;
83984}
83985#endif /* SQLITE_ENABLE_CURSOR_HINTS */
83986
83987/* Opcode: Noop * * * * *
83988**
83989** Do nothing.  This instruction is often useful as a jump
83990** destination.
83991*/
83992/*
83993** The magic Explain opcode are only inserted when explain==2 (which
83994** is to say when the EXPLAIN QUERY PLAN syntax is used.)
83995** This opcode records information from the optimizer.  It is the
83996** the same as a no-op.  This opcodesnever appears in a real VM program.
83997*/
83998default: {          /* This is really OP_Noop and OP_Explain */
83999  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
84000  break;
84001}
84002
84003/*****************************************************************************
84004** The cases of the switch statement above this line should all be indented
84005** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
84006** readability.  From this point on down, the normal indentation rules are
84007** restored.
84008*****************************************************************************/
84009    }
84010
84011#ifdef VDBE_PROFILE
84012    {
84013      u64 endTime = sqlite3Hwtime();
84014      if( endTime>start ) pOrigOp->cycles += endTime - start;
84015      pOrigOp->cnt++;
84016    }
84017#endif
84018
84019    /* The following code adds nothing to the actual functionality
84020    ** of the program.  It is only here for testing and debugging.
84021    ** On the other hand, it does burn CPU cycles every time through
84022    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
84023    */
84024#ifndef NDEBUG
84025    assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
84026
84027#ifdef SQLITE_DEBUG
84028    if( db->flags & SQLITE_VdbeTrace ){
84029      u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
84030      if( rc!=0 ) printf("rc=%d\n",rc);
84031      if( opProperty & (OPFLG_OUT2) ){
84032        registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
84033      }
84034      if( opProperty & OPFLG_OUT3 ){
84035        registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
84036      }
84037    }
84038#endif  /* SQLITE_DEBUG */
84039#endif  /* NDEBUG */
84040  }  /* The end of the for(;;) loop the loops through opcodes */
84041
84042  /* If we reach this point, it means that execution is finished with
84043  ** an error of some kind.
84044  */
84045abort_due_to_error:
84046  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
84047  assert( rc );
84048  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
84049    sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84050  }
84051  p->rc = rc;
84052  sqlite3SystemError(db, rc);
84053  testcase( sqlite3GlobalConfig.xLog!=0 );
84054  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
84055                   (int)(pOp - aOp), p->zSql, p->zErrMsg);
84056  sqlite3VdbeHalt(p);
84057  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
84058  rc = SQLITE_ERROR;
84059  if( resetSchemaOnFault>0 ){
84060    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
84061  }
84062
84063  /* This is the only way out of this procedure.  We have to
84064  ** release the mutexes on btrees that were acquired at the
84065  ** top. */
84066vdbe_return:
84067  db->lastRowid = lastRowid;
84068  testcase( nVmStep>0 );
84069  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
84070  sqlite3VdbeLeave(p);
84071  assert( rc!=SQLITE_OK || nExtraDelete==0
84072       || sqlite3_strlike("DELETE%",p->zSql,0)!=0
84073  );
84074  return rc;
84075
84076  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
84077  ** is encountered.
84078  */
84079too_big:
84080  sqlite3VdbeError(p, "string or blob too big");
84081  rc = SQLITE_TOOBIG;
84082  goto abort_due_to_error;
84083
84084  /* Jump to here if a malloc() fails.
84085  */
84086no_mem:
84087  sqlite3OomFault(db);
84088  sqlite3VdbeError(p, "out of memory");
84089  rc = SQLITE_NOMEM_BKPT;
84090  goto abort_due_to_error;
84091
84092  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
84093  ** flag.
84094  */
84095abort_due_to_interrupt:
84096  assert( db->u1.isInterrupted );
84097  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
84098  p->rc = rc;
84099  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84100  goto abort_due_to_error;
84101}
84102
84103
84104/************** End of vdbe.c ************************************************/
84105/************** Begin file vdbeblob.c ****************************************/
84106/*
84107** 2007 May 1
84108**
84109** The author disclaims copyright to this source code.  In place of
84110** a legal notice, here is a blessing:
84111**
84112**    May you do good and not evil.
84113**    May you find forgiveness for yourself and forgive others.
84114**    May you share freely, never taking more than you give.
84115**
84116*************************************************************************
84117**
84118** This file contains code used to implement incremental BLOB I/O.
84119*/
84120
84121/* #include "sqliteInt.h" */
84122/* #include "vdbeInt.h" */
84123
84124#ifndef SQLITE_OMIT_INCRBLOB
84125
84126/*
84127** Valid sqlite3_blob* handles point to Incrblob structures.
84128*/
84129typedef struct Incrblob Incrblob;
84130struct Incrblob {
84131  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
84132  int nByte;              /* Size of open blob, in bytes */
84133  int iOffset;            /* Byte offset of blob in cursor data */
84134  int iCol;               /* Table column this handle is open on */
84135  BtCursor *pCsr;         /* Cursor pointing at blob row */
84136  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
84137  sqlite3 *db;            /* The associated database */
84138  char *zDb;              /* Database name */
84139  Table *pTab;            /* Table object */
84140};
84141
84142
84143/*
84144** This function is used by both blob_open() and blob_reopen(). It seeks
84145** the b-tree cursor associated with blob handle p to point to row iRow.
84146** If successful, SQLITE_OK is returned and subsequent calls to
84147** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
84148**
84149** If an error occurs, or if the specified row does not exist or does not
84150** contain a value of type TEXT or BLOB in the column nominated when the
84151** blob handle was opened, then an error code is returned and *pzErr may
84152** be set to point to a buffer containing an error message. It is the
84153** responsibility of the caller to free the error message buffer using
84154** sqlite3DbFree().
84155**
84156** If an error does occur, then the b-tree cursor is closed. All subsequent
84157** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
84158** immediately return SQLITE_ABORT.
84159*/
84160static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
84161  int rc;                         /* Error code */
84162  char *zErr = 0;                 /* Error message */
84163  Vdbe *v = (Vdbe *)p->pStmt;
84164
84165  /* Set the value of the SQL statements only variable to integer iRow.
84166  ** This is done directly instead of using sqlite3_bind_int64() to avoid
84167  ** triggering asserts related to mutexes.
84168  */
84169  assert( v->aVar[0].flags&MEM_Int );
84170  v->aVar[0].u.i = iRow;
84171
84172  rc = sqlite3_step(p->pStmt);
84173  if( rc==SQLITE_ROW ){
84174    VdbeCursor *pC = v->apCsr[0];
84175    u32 type = pC->aType[p->iCol];
84176    if( type<12 ){
84177      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
84178          type==0?"null": type==7?"real": "integer"
84179      );
84180      rc = SQLITE_ERROR;
84181      sqlite3_finalize(p->pStmt);
84182      p->pStmt = 0;
84183    }else{
84184      p->iOffset = pC->aType[p->iCol + pC->nField];
84185      p->nByte = sqlite3VdbeSerialTypeLen(type);
84186      p->pCsr =  pC->uc.pCursor;
84187      sqlite3BtreeIncrblobCursor(p->pCsr);
84188    }
84189  }
84190
84191  if( rc==SQLITE_ROW ){
84192    rc = SQLITE_OK;
84193  }else if( p->pStmt ){
84194    rc = sqlite3_finalize(p->pStmt);
84195    p->pStmt = 0;
84196    if( rc==SQLITE_OK ){
84197      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
84198      rc = SQLITE_ERROR;
84199    }else{
84200      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
84201    }
84202  }
84203
84204  assert( rc!=SQLITE_OK || zErr==0 );
84205  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
84206
84207  *pzErr = zErr;
84208  return rc;
84209}
84210
84211/*
84212** Open a blob handle.
84213*/
84214SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
84215  sqlite3* db,            /* The database connection */
84216  const char *zDb,        /* The attached database containing the blob */
84217  const char *zTable,     /* The table containing the blob */
84218  const char *zColumn,    /* The column containing the blob */
84219  sqlite_int64 iRow,      /* The row containing the glob */
84220  int flags,              /* True -> read/write access, false -> read-only */
84221  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
84222){
84223  int nAttempt = 0;
84224  int iCol;               /* Index of zColumn in row-record */
84225  int rc = SQLITE_OK;
84226  char *zErr = 0;
84227  Table *pTab;
84228  Parse *pParse = 0;
84229  Incrblob *pBlob = 0;
84230
84231#ifdef SQLITE_ENABLE_API_ARMOR
84232  if( ppBlob==0 ){
84233    return SQLITE_MISUSE_BKPT;
84234  }
84235#endif
84236  *ppBlob = 0;
84237#ifdef SQLITE_ENABLE_API_ARMOR
84238  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
84239    return SQLITE_MISUSE_BKPT;
84240  }
84241#endif
84242  flags = !!flags;                /* flags = (flags ? 1 : 0); */
84243
84244  sqlite3_mutex_enter(db->mutex);
84245
84246  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
84247  if( !pBlob ) goto blob_open_out;
84248  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
84249  if( !pParse ) goto blob_open_out;
84250
84251  do {
84252    memset(pParse, 0, sizeof(Parse));
84253    pParse->db = db;
84254    sqlite3DbFree(db, zErr);
84255    zErr = 0;
84256
84257    sqlite3BtreeEnterAll(db);
84258    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
84259    if( pTab && IsVirtual(pTab) ){
84260      pTab = 0;
84261      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
84262    }
84263    if( pTab && !HasRowid(pTab) ){
84264      pTab = 0;
84265      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
84266    }
84267#ifndef SQLITE_OMIT_VIEW
84268    if( pTab && pTab->pSelect ){
84269      pTab = 0;
84270      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
84271    }
84272#endif
84273    if( !pTab ){
84274      if( pParse->zErrMsg ){
84275        sqlite3DbFree(db, zErr);
84276        zErr = pParse->zErrMsg;
84277        pParse->zErrMsg = 0;
84278      }
84279      rc = SQLITE_ERROR;
84280      sqlite3BtreeLeaveAll(db);
84281      goto blob_open_out;
84282    }
84283    pBlob->pTab = pTab;
84284    pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
84285
84286    /* Now search pTab for the exact column. */
84287    for(iCol=0; iCol<pTab->nCol; iCol++) {
84288      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
84289        break;
84290      }
84291    }
84292    if( iCol==pTab->nCol ){
84293      sqlite3DbFree(db, zErr);
84294      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
84295      rc = SQLITE_ERROR;
84296      sqlite3BtreeLeaveAll(db);
84297      goto blob_open_out;
84298    }
84299
84300    /* If the value is being opened for writing, check that the
84301    ** column is not indexed, and that it is not part of a foreign key.
84302    ** It is against the rules to open a column to which either of these
84303    ** descriptions applies for writing.  */
84304    if( flags ){
84305      const char *zFault = 0;
84306      Index *pIdx;
84307#ifndef SQLITE_OMIT_FOREIGN_KEY
84308      if( db->flags&SQLITE_ForeignKeys ){
84309        /* Check that the column is not part of an FK child key definition. It
84310        ** is not necessary to check if it is part of a parent key, as parent
84311        ** key columns must be indexed. The check below will pick up this
84312        ** case.  */
84313        FKey *pFKey;
84314        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84315          int j;
84316          for(j=0; j<pFKey->nCol; j++){
84317            if( pFKey->aCol[j].iFrom==iCol ){
84318              zFault = "foreign key";
84319            }
84320          }
84321        }
84322      }
84323#endif
84324      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84325        int j;
84326        for(j=0; j<pIdx->nKeyCol; j++){
84327          /* FIXME: Be smarter about indexes that use expressions */
84328          if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
84329            zFault = "indexed";
84330          }
84331        }
84332      }
84333      if( zFault ){
84334        sqlite3DbFree(db, zErr);
84335        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
84336        rc = SQLITE_ERROR;
84337        sqlite3BtreeLeaveAll(db);
84338        goto blob_open_out;
84339      }
84340    }
84341
84342    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
84343    assert( pBlob->pStmt || db->mallocFailed );
84344    if( pBlob->pStmt ){
84345
84346      /* This VDBE program seeks a btree cursor to the identified
84347      ** db/table/row entry. The reason for using a vdbe program instead
84348      ** of writing code to use the b-tree layer directly is that the
84349      ** vdbe program will take advantage of the various transaction,
84350      ** locking and error handling infrastructure built into the vdbe.
84351      **
84352      ** After seeking the cursor, the vdbe executes an OP_ResultRow.
84353      ** Code external to the Vdbe then "borrows" the b-tree cursor and
84354      ** uses it to implement the blob_read(), blob_write() and
84355      ** blob_bytes() functions.
84356      **
84357      ** The sqlite3_blob_close() function finalizes the vdbe program,
84358      ** which closes the b-tree cursor and (possibly) commits the
84359      ** transaction.
84360      */
84361      static const int iLn = VDBE_OFFSET_LINENO(2);
84362      static const VdbeOpList openBlob[] = {
84363        {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
84364        {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
84365        {OP_Variable,       1, 1, 0},  /* 2: Move ?1 into reg[1] */
84366        {OP_NotExists,      0, 7, 1},  /* 3: Seek the cursor */
84367        {OP_Column,         0, 0, 1},  /* 4  */
84368        {OP_ResultRow,      1, 0, 0},  /* 5  */
84369        {OP_Goto,           0, 2, 0},  /* 6  */
84370        {OP_Close,          0, 0, 0},  /* 7  */
84371        {OP_Halt,           0, 0, 0},  /* 8  */
84372      };
84373      Vdbe *v = (Vdbe *)pBlob->pStmt;
84374      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84375      VdbeOp *aOp;
84376
84377      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
84378                           pTab->pSchema->schema_cookie,
84379                           pTab->pSchema->iGeneration);
84380      sqlite3VdbeChangeP5(v, 1);
84381      aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
84382
84383      /* Make sure a mutex is held on the table to be accessed */
84384      sqlite3VdbeUsesBtree(v, iDb);
84385
84386      if( db->mallocFailed==0 ){
84387        assert( aOp!=0 );
84388        /* Configure the OP_TableLock instruction */
84389#ifdef SQLITE_OMIT_SHARED_CACHE
84390        aOp[0].opcode = OP_Noop;
84391#else
84392        aOp[0].p1 = iDb;
84393        aOp[0].p2 = pTab->tnum;
84394        aOp[0].p3 = flags;
84395        sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
84396      }
84397      if( db->mallocFailed==0 ){
84398#endif
84399
84400        /* Remove either the OP_OpenWrite or OpenRead. Set the P2
84401        ** parameter of the other to pTab->tnum.  */
84402        if( flags ) aOp[1].opcode = OP_OpenWrite;
84403        aOp[1].p2 = pTab->tnum;
84404        aOp[1].p3 = iDb;
84405
84406        /* Configure the number of columns. Configure the cursor to
84407        ** think that the table has one more column than it really
84408        ** does. An OP_Column to retrieve this imaginary column will
84409        ** always return an SQL NULL. This is useful because it means
84410        ** we can invoke OP_Column to fill in the vdbe cursors type
84411        ** and offset cache without causing any IO.
84412        */
84413        aOp[1].p4type = P4_INT32;
84414        aOp[1].p4.i = pTab->nCol+1;
84415        aOp[4].p2 = pTab->nCol;
84416
84417        pParse->nVar = 1;
84418        pParse->nMem = 1;
84419        pParse->nTab = 1;
84420        sqlite3VdbeMakeReady(v, pParse);
84421      }
84422    }
84423
84424    pBlob->flags = flags;
84425    pBlob->iCol = iCol;
84426    pBlob->db = db;
84427    sqlite3BtreeLeaveAll(db);
84428    if( db->mallocFailed ){
84429      goto blob_open_out;
84430    }
84431    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
84432    rc = blobSeekToRow(pBlob, iRow, &zErr);
84433  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
84434
84435blob_open_out:
84436  if( rc==SQLITE_OK && db->mallocFailed==0 ){
84437    *ppBlob = (sqlite3_blob *)pBlob;
84438  }else{
84439    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
84440    sqlite3DbFree(db, pBlob);
84441  }
84442  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84443  sqlite3DbFree(db, zErr);
84444  sqlite3ParserReset(pParse);
84445  sqlite3StackFree(db, pParse);
84446  rc = sqlite3ApiExit(db, rc);
84447  sqlite3_mutex_leave(db->mutex);
84448  return rc;
84449}
84450
84451/*
84452** Close a blob handle that was previously created using
84453** sqlite3_blob_open().
84454*/
84455SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
84456  Incrblob *p = (Incrblob *)pBlob;
84457  int rc;
84458  sqlite3 *db;
84459
84460  if( p ){
84461    db = p->db;
84462    sqlite3_mutex_enter(db->mutex);
84463    rc = sqlite3_finalize(p->pStmt);
84464    sqlite3DbFree(db, p);
84465    sqlite3_mutex_leave(db->mutex);
84466  }else{
84467    rc = SQLITE_OK;
84468  }
84469  return rc;
84470}
84471
84472/*
84473** Perform a read or write operation on a blob
84474*/
84475static int blobReadWrite(
84476  sqlite3_blob *pBlob,
84477  void *z,
84478  int n,
84479  int iOffset,
84480  int (*xCall)(BtCursor*, u32, u32, void*)
84481){
84482  int rc;
84483  Incrblob *p = (Incrblob *)pBlob;
84484  Vdbe *v;
84485  sqlite3 *db;
84486
84487  if( p==0 ) return SQLITE_MISUSE_BKPT;
84488  db = p->db;
84489  sqlite3_mutex_enter(db->mutex);
84490  v = (Vdbe*)p->pStmt;
84491
84492  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
84493    /* Request is out of range. Return a transient error. */
84494    rc = SQLITE_ERROR;
84495  }else if( v==0 ){
84496    /* If there is no statement handle, then the blob-handle has
84497    ** already been invalidated. Return SQLITE_ABORT in this case.
84498    */
84499    rc = SQLITE_ABORT;
84500  }else{
84501    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
84502    ** returned, clean-up the statement handle.
84503    */
84504    assert( db == v->db );
84505    sqlite3BtreeEnterCursor(p->pCsr);
84506
84507#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84508    if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84509      /* If a pre-update hook is registered and this is a write cursor,
84510      ** invoke it here.
84511      **
84512      ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84513      ** operation should really be an SQLITE_UPDATE. This is probably
84514      ** incorrect, but is convenient because at this point the new.* values
84515      ** are not easily obtainable. And for the sessions module, an
84516      ** SQLITE_UPDATE where the PK columns do not change is handled in the
84517      ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84518      ** slightly more efficient). Since you cannot write to a PK column
84519      ** using the incremental-blob API, this works. For the sessions module
84520      ** anyhow.
84521      */
84522      sqlite3_int64 iKey;
84523      iKey = sqlite3BtreeIntegerKey(p->pCsr);
84524      sqlite3VdbePreUpdateHook(
84525          v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84526      );
84527    }
84528#endif
84529
84530    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
84531    sqlite3BtreeLeaveCursor(p->pCsr);
84532    if( rc==SQLITE_ABORT ){
84533      sqlite3VdbeFinalize(v);
84534      p->pStmt = 0;
84535    }else{
84536      v->rc = rc;
84537    }
84538  }
84539  sqlite3Error(db, rc);
84540  rc = sqlite3ApiExit(db, rc);
84541  sqlite3_mutex_leave(db->mutex);
84542  return rc;
84543}
84544
84545/*
84546** Read data from a blob handle.
84547*/
84548SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
84549  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
84550}
84551
84552/*
84553** Write data to a blob handle.
84554*/
84555SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
84556  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
84557}
84558
84559/*
84560** Query a blob handle for the size of the data.
84561**
84562** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
84563** so no mutex is required for access.
84564*/
84565SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
84566  Incrblob *p = (Incrblob *)pBlob;
84567  return (p && p->pStmt) ? p->nByte : 0;
84568}
84569
84570/*
84571** Move an existing blob handle to point to a different row of the same
84572** database table.
84573**
84574** If an error occurs, or if the specified row does not exist or does not
84575** contain a blob or text value, then an error code is returned and the
84576** database handle error code and message set. If this happens, then all
84577** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
84578** immediately return SQLITE_ABORT.
84579*/
84580SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
84581  int rc;
84582  Incrblob *p = (Incrblob *)pBlob;
84583  sqlite3 *db;
84584
84585  if( p==0 ) return SQLITE_MISUSE_BKPT;
84586  db = p->db;
84587  sqlite3_mutex_enter(db->mutex);
84588
84589  if( p->pStmt==0 ){
84590    /* If there is no statement handle, then the blob-handle has
84591    ** already been invalidated. Return SQLITE_ABORT in this case.
84592    */
84593    rc = SQLITE_ABORT;
84594  }else{
84595    char *zErr;
84596    rc = blobSeekToRow(p, iRow, &zErr);
84597    if( rc!=SQLITE_OK ){
84598      sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84599      sqlite3DbFree(db, zErr);
84600    }
84601    assert( rc!=SQLITE_SCHEMA );
84602  }
84603
84604  rc = sqlite3ApiExit(db, rc);
84605  assert( rc==SQLITE_OK || p->pStmt==0 );
84606  sqlite3_mutex_leave(db->mutex);
84607  return rc;
84608}
84609
84610#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
84611
84612/************** End of vdbeblob.c ********************************************/
84613/************** Begin file vdbesort.c ****************************************/
84614/*
84615** 2011-07-09
84616**
84617** The author disclaims copyright to this source code.  In place of
84618** a legal notice, here is a blessing:
84619**
84620**    May you do good and not evil.
84621**    May you find forgiveness for yourself and forgive others.
84622**    May you share freely, never taking more than you give.
84623**
84624*************************************************************************
84625** This file contains code for the VdbeSorter object, used in concert with
84626** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
84627** or by SELECT statements with ORDER BY clauses that cannot be satisfied
84628** using indexes and without LIMIT clauses.
84629**
84630** The VdbeSorter object implements a multi-threaded external merge sort
84631** algorithm that is efficient even if the number of elements being sorted
84632** exceeds the available memory.
84633**
84634** Here is the (internal, non-API) interface between this module and the
84635** rest of the SQLite system:
84636**
84637**    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
84638**
84639**    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
84640**                                  object.  The row is a binary blob in the
84641**                                  OP_MakeRecord format that contains both
84642**                                  the ORDER BY key columns and result columns
84643**                                  in the case of a SELECT w/ ORDER BY, or
84644**                                  the complete record for an index entry
84645**                                  in the case of a CREATE INDEX.
84646**
84647**    sqlite3VdbeSorterRewind()     Sort all content previously added.
84648**                                  Position the read cursor on the
84649**                                  first sorted element.
84650**
84651**    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
84652**                                  element.
84653**
84654**    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
84655**                                  row currently under the read cursor.
84656**
84657**    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
84658**                                  currently under the read cursor against
84659**                                  another binary blob X and report if
84660**                                  X is strictly less than the read cursor.
84661**                                  Used to enforce uniqueness in a
84662**                                  CREATE UNIQUE INDEX statement.
84663**
84664**    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
84665**                                  all resources.
84666**
84667**    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
84668**                                  is like Close() followed by Init() only
84669**                                  much faster.
84670**
84671** The interfaces above must be called in a particular order.  Write() can
84672** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
84673** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
84674**
84675**   Init()
84676**   for each record: Write()
84677**   Rewind()
84678**     Rowkey()/Compare()
84679**   Next()
84680**   Close()
84681**
84682** Algorithm:
84683**
84684** Records passed to the sorter via calls to Write() are initially held
84685** unsorted in main memory. Assuming the amount of memory used never exceeds
84686** a threshold, when Rewind() is called the set of records is sorted using
84687** an in-memory merge sort. In this case, no temporary files are required
84688** and subsequent calls to Rowkey(), Next() and Compare() read records
84689** directly from main memory.
84690**
84691** If the amount of space used to store records in main memory exceeds the
84692** threshold, then the set of records currently in memory are sorted and
84693** written to a temporary file in "Packed Memory Array" (PMA) format.
84694** A PMA created at this point is known as a "level-0 PMA". Higher levels
84695** of PMAs may be created by merging existing PMAs together - for example
84696** merging two or more level-0 PMAs together creates a level-1 PMA.
84697**
84698** The threshold for the amount of main memory to use before flushing
84699** records to a PMA is roughly the same as the limit configured for the
84700** page-cache of the main database. Specifically, the threshold is set to
84701** the value returned by "PRAGMA main.page_size" multipled by
84702** that returned by "PRAGMA main.cache_size", in bytes.
84703**
84704** If the sorter is running in single-threaded mode, then all PMAs generated
84705** are appended to a single temporary file. Or, if the sorter is running in
84706** multi-threaded mode then up to (N+1) temporary files may be opened, where
84707** N is the configured number of worker threads. In this case, instead of
84708** sorting the records and writing the PMA to a temporary file itself, the
84709** calling thread usually launches a worker thread to do so. Except, if
84710** there are already N worker threads running, the main thread does the work
84711** itself.
84712**
84713** The sorter is running in multi-threaded mode if (a) the library was built
84714** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
84715** than zero, and (b) worker threads have been enabled at runtime by calling
84716** "PRAGMA threads=N" with some value of N greater than 0.
84717**
84718** When Rewind() is called, any data remaining in memory is flushed to a
84719** final PMA. So at this point the data is stored in some number of sorted
84720** PMAs within temporary files on disk.
84721**
84722** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
84723** sorter is running in single-threaded mode, then these PMAs are merged
84724** incrementally as keys are retreived from the sorter by the VDBE.  The
84725** MergeEngine object, described in further detail below, performs this
84726** merge.
84727**
84728** Or, if running in multi-threaded mode, then a background thread is
84729** launched to merge the existing PMAs. Once the background thread has
84730** merged T bytes of data into a single sorted PMA, the main thread
84731** begins reading keys from that PMA while the background thread proceeds
84732** with merging the next T bytes of data. And so on.
84733**
84734** Parameter T is set to half the value of the memory threshold used
84735** by Write() above to determine when to create a new PMA.
84736**
84737** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
84738** Rewind() is called, then a hierarchy of incremental-merges is used.
84739** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
84740** disk are merged together. Then T bytes of data from the second set, and
84741** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
84742** PMAs at a time. This done is to improve locality.
84743**
84744** If running in multi-threaded mode and there are more than
84745** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
84746** than one background thread may be created. Specifically, there may be
84747** one background thread for each temporary file on disk, and one background
84748** thread to merge the output of each of the others to a single PMA for
84749** the main thread to read from.
84750*/
84751/* #include "sqliteInt.h" */
84752/* #include "vdbeInt.h" */
84753
84754/*
84755** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
84756** messages to stderr that may be helpful in understanding the performance
84757** characteristics of the sorter in multi-threaded mode.
84758*/
84759#if 0
84760# define SQLITE_DEBUG_SORTER_THREADS 1
84761#endif
84762
84763/*
84764** Hard-coded maximum amount of data to accumulate in memory before flushing
84765** to a level 0 PMA. The purpose of this limit is to prevent various integer
84766** overflows. 512MiB.
84767*/
84768#define SQLITE_MAX_PMASZ    (1<<29)
84769
84770/*
84771** Private objects used by the sorter
84772*/
84773typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
84774typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
84775typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
84776typedef struct SorterRecord SorterRecord;   /* A record being sorted */
84777typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
84778typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
84779typedef struct SorterList SorterList;       /* In-memory list of records */
84780typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
84781
84782/*
84783** A container for a temp file handle and the current amount of data
84784** stored in the file.
84785*/
84786struct SorterFile {
84787  sqlite3_file *pFd;              /* File handle */
84788  i64 iEof;                       /* Bytes of data stored in pFd */
84789};
84790
84791/*
84792** An in-memory list of objects to be sorted.
84793**
84794** If aMemory==0 then each object is allocated separately and the objects
84795** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
84796** are stored in the aMemory[] bulk memory, one right after the other, and
84797** are connected using SorterRecord.u.iNext.
84798*/
84799struct SorterList {
84800  SorterRecord *pList;            /* Linked list of records */
84801  u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
84802  int szPMA;                      /* Size of pList as PMA in bytes */
84803};
84804
84805/*
84806** The MergeEngine object is used to combine two or more smaller PMAs into
84807** one big PMA using a merge operation.  Separate PMAs all need to be
84808** combined into one big PMA in order to be able to step through the sorted
84809** records in order.
84810**
84811** The aReadr[] array contains a PmaReader object for each of the PMAs being
84812** merged.  An aReadr[] object either points to a valid key or else is at EOF.
84813** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
84814** For the purposes of the paragraphs below, we assume that the array is
84815** actually N elements in size, where N is the smallest power of 2 greater
84816** to or equal to the number of PMAs being merged. The extra aReadr[] elements
84817** are treated as if they are empty (always at EOF).
84818**
84819** The aTree[] array is also N elements in size. The value of N is stored in
84820** the MergeEngine.nTree variable.
84821**
84822** The final (N/2) elements of aTree[] contain the results of comparing
84823** pairs of PMA keys together. Element i contains the result of
84824** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
84825** aTree element is set to the index of it.
84826**
84827** For the purposes of this comparison, EOF is considered greater than any
84828** other key value. If the keys are equal (only possible with two EOF
84829** values), it doesn't matter which index is stored.
84830**
84831** The (N/4) elements of aTree[] that precede the final (N/2) described
84832** above contains the index of the smallest of each block of 4 PmaReaders
84833** And so on. So that aTree[1] contains the index of the PmaReader that
84834** currently points to the smallest key value. aTree[0] is unused.
84835**
84836** Example:
84837**
84838**     aReadr[0] -> Banana
84839**     aReadr[1] -> Feijoa
84840**     aReadr[2] -> Elderberry
84841**     aReadr[3] -> Currant
84842**     aReadr[4] -> Grapefruit
84843**     aReadr[5] -> Apple
84844**     aReadr[6] -> Durian
84845**     aReadr[7] -> EOF
84846**
84847**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
84848**
84849** The current element is "Apple" (the value of the key indicated by
84850** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
84851** be advanced to the next key in its segment. Say the next key is
84852** "Eggplant":
84853**
84854**     aReadr[5] -> Eggplant
84855**
84856** The contents of aTree[] are updated first by comparing the new PmaReader
84857** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
84858** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
84859** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
84860** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
84861** so the value written into element 1 of the array is 0. As follows:
84862**
84863**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
84864**
84865** In other words, each time we advance to the next sorter element, log2(N)
84866** key comparison operations are required, where N is the number of segments
84867** being merged (rounded up to the next power of 2).
84868*/
84869struct MergeEngine {
84870  int nTree;                 /* Used size of aTree/aReadr (power of 2) */
84871  SortSubtask *pTask;        /* Used by this thread only */
84872  int *aTree;                /* Current state of incremental merge */
84873  PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
84874};
84875
84876/*
84877** This object represents a single thread of control in a sort operation.
84878** Exactly VdbeSorter.nTask instances of this object are allocated
84879** as part of each VdbeSorter object. Instances are never allocated any
84880** other way. VdbeSorter.nTask is set to the number of worker threads allowed
84881** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
84882** single-threaded operation, there is exactly one instance of this object
84883** and for multi-threaded operation there are two or more instances.
84884**
84885** Essentially, this structure contains all those fields of the VdbeSorter
84886** structure for which each thread requires a separate instance. For example,
84887** each thread requries its own UnpackedRecord object to unpack records in
84888** as part of comparison operations.
84889**
84890** Before a background thread is launched, variable bDone is set to 0. Then,
84891** right before it exits, the thread itself sets bDone to 1. This is used for
84892** two purposes:
84893**
84894**   1. When flushing the contents of memory to a level-0 PMA on disk, to
84895**      attempt to select a SortSubtask for which there is not already an
84896**      active background thread (since doing so causes the main thread
84897**      to block until it finishes).
84898**
84899**   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
84900**      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
84901**      block provoke debugging output.
84902**
84903** In both cases, the effects of the main thread seeing (bDone==0) even
84904** after the thread has finished are not dire. So we don't worry about
84905** memory barriers and such here.
84906*/
84907typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
84908struct SortSubtask {
84909  SQLiteThread *pThread;          /* Background thread, if any */
84910  int bDone;                      /* Set if thread is finished but not joined */
84911  VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
84912  UnpackedRecord *pUnpacked;      /* Space to unpack a record */
84913  SorterList list;                /* List for thread to write to a PMA */
84914  int nPMA;                       /* Number of PMAs currently in file */
84915  SorterCompare xCompare;         /* Compare function to use */
84916  SorterFile file;                /* Temp file for level-0 PMAs */
84917  SorterFile file2;               /* Space for other PMAs */
84918};
84919
84920
84921/*
84922** Main sorter structure. A single instance of this is allocated for each
84923** sorter cursor created by the VDBE.
84924**
84925** mxKeysize:
84926**   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
84927**   this variable is updated so as to be set to the size on disk of the
84928**   largest record in the sorter.
84929*/
84930struct VdbeSorter {
84931  int mnPmaSize;                  /* Minimum PMA size, in bytes */
84932  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
84933  int mxKeysize;                  /* Largest serialized key seen so far */
84934  int pgsz;                       /* Main database page size */
84935  PmaReader *pReader;             /* Readr data from here after Rewind() */
84936  MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
84937  sqlite3 *db;                    /* Database connection */
84938  KeyInfo *pKeyInfo;              /* How to compare records */
84939  UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
84940  SorterList list;                /* List of in-memory records */
84941  int iMemory;                    /* Offset of free space in list.aMemory */
84942  int nMemory;                    /* Size of list.aMemory allocation in bytes */
84943  u8 bUsePMA;                     /* True if one or more PMAs created */
84944  u8 bUseThreads;                 /* True to use background threads */
84945  u8 iPrev;                       /* Previous thread used to flush PMA */
84946  u8 nTask;                       /* Size of aTask[] array */
84947  u8 typeMask;
84948  SortSubtask aTask[1];           /* One or more subtasks */
84949};
84950
84951#define SORTER_TYPE_INTEGER 0x01
84952#define SORTER_TYPE_TEXT    0x02
84953
84954/*
84955** An instance of the following object is used to read records out of a
84956** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
84957** aKey might point into aMap or into aBuffer.  If neither of those locations
84958** contain a contiguous representation of the key, then aAlloc is allocated
84959** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
84960**
84961** pFd==0 at EOF.
84962*/
84963struct PmaReader {
84964  i64 iReadOff;               /* Current read offset */
84965  i64 iEof;                   /* 1 byte past EOF for this PmaReader */
84966  int nAlloc;                 /* Bytes of space at aAlloc */
84967  int nKey;                   /* Number of bytes in key */
84968  sqlite3_file *pFd;          /* File handle we are reading from */
84969  u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
84970  u8 *aKey;                   /* Pointer to current key */
84971  u8 *aBuffer;                /* Current read buffer */
84972  int nBuffer;                /* Size of read buffer in bytes */
84973  u8 *aMap;                   /* Pointer to mapping of entire file */
84974  IncrMerger *pIncr;          /* Incremental merger */
84975};
84976
84977/*
84978** Normally, a PmaReader object iterates through an existing PMA stored
84979** within a temp file. However, if the PmaReader.pIncr variable points to
84980** an object of the following type, it may be used to iterate/merge through
84981** multiple PMAs simultaneously.
84982**
84983** There are two types of IncrMerger object - single (bUseThread==0) and
84984** multi-threaded (bUseThread==1).
84985**
84986** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
84987** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
84988** size. When the IncrMerger is initialized, it reads enough data from
84989** pMerger to populate aFile[0]. It then sets variables within the
84990** corresponding PmaReader object to read from that file and kicks off
84991** a background thread to populate aFile[1] with the next mxSz bytes of
84992** sorted record data from pMerger.
84993**
84994** When the PmaReader reaches the end of aFile[0], it blocks until the
84995** background thread has finished populating aFile[1]. It then exchanges
84996** the contents of the aFile[0] and aFile[1] variables within this structure,
84997** sets the PmaReader fields to read from the new aFile[0] and kicks off
84998** another background thread to populate the new aFile[1]. And so on, until
84999** the contents of pMerger are exhausted.
85000**
85001** A single-threaded IncrMerger does not open any temporary files of its
85002** own. Instead, it has exclusive access to mxSz bytes of space beginning
85003** at offset iStartOff of file pTask->file2. And instead of using a
85004** background thread to prepare data for the PmaReader, with a single
85005** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
85006** keys from pMerger by the calling thread whenever the PmaReader runs out
85007** of data.
85008*/
85009struct IncrMerger {
85010  SortSubtask *pTask;             /* Task that owns this merger */
85011  MergeEngine *pMerger;           /* Merge engine thread reads data from */
85012  i64 iStartOff;                  /* Offset to start writing file at */
85013  int mxSz;                       /* Maximum bytes of data to store */
85014  int bEof;                       /* Set to true when merge is finished */
85015  int bUseThread;                 /* True to use a bg thread for this object */
85016  SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
85017};
85018
85019/*
85020** An instance of this object is used for writing a PMA.
85021**
85022** The PMA is written one record at a time.  Each record is of an arbitrary
85023** size.  But I/O is more efficient if it occurs in page-sized blocks where
85024** each block is aligned on a page boundary.  This object caches writes to
85025** the PMA so that aligned, page-size blocks are written.
85026*/
85027struct PmaWriter {
85028  int eFWErr;                     /* Non-zero if in an error state */
85029  u8 *aBuffer;                    /* Pointer to write buffer */
85030  int nBuffer;                    /* Size of write buffer in bytes */
85031  int iBufStart;                  /* First byte of buffer to write */
85032  int iBufEnd;                    /* Last byte of buffer to write */
85033  i64 iWriteOff;                  /* Offset of start of buffer in file */
85034  sqlite3_file *pFd;              /* File handle to write to */
85035};
85036
85037/*
85038** This object is the header on a single record while that record is being
85039** held in memory and prior to being written out as part of a PMA.
85040**
85041** How the linked list is connected depends on how memory is being managed
85042** by this module. If using a separate allocation for each in-memory record
85043** (VdbeSorter.list.aMemory==0), then the list is always connected using the
85044** SorterRecord.u.pNext pointers.
85045**
85046** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
85047** then while records are being accumulated the list is linked using the
85048** SorterRecord.u.iNext offset. This is because the aMemory[] array may
85049** be sqlite3Realloc()ed while records are being accumulated. Once the VM
85050** has finished passing records to the sorter, or when the in-memory buffer
85051** is full, the list is sorted. As part of the sorting process, it is
85052** converted to use the SorterRecord.u.pNext pointers. See function
85053** vdbeSorterSort() for details.
85054*/
85055struct SorterRecord {
85056  int nVal;                       /* Size of the record in bytes */
85057  union {
85058    SorterRecord *pNext;          /* Pointer to next record in list */
85059    int iNext;                    /* Offset within aMemory of next record */
85060  } u;
85061  /* The data for the record immediately follows this header */
85062};
85063
85064/* Return a pointer to the buffer containing the record data for SorterRecord
85065** object p. Should be used as if:
85066**
85067**   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
85068*/
85069#define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
85070
85071
85072/* Maximum number of PMAs that a single MergeEngine can merge */
85073#define SORTER_MAX_MERGE_COUNT 16
85074
85075static int vdbeIncrSwap(IncrMerger*);
85076static void vdbeIncrFree(IncrMerger *);
85077
85078/*
85079** Free all memory belonging to the PmaReader object passed as the
85080** argument. All structure fields are set to zero before returning.
85081*/
85082static void vdbePmaReaderClear(PmaReader *pReadr){
85083  sqlite3_free(pReadr->aAlloc);
85084  sqlite3_free(pReadr->aBuffer);
85085  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85086  vdbeIncrFree(pReadr->pIncr);
85087  memset(pReadr, 0, sizeof(PmaReader));
85088}
85089
85090/*
85091** Read the next nByte bytes of data from the PMA p.
85092** If successful, set *ppOut to point to a buffer containing the data
85093** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
85094** error code.
85095**
85096** The buffer returned in *ppOut is only valid until the
85097** next call to this function.
85098*/
85099static int vdbePmaReadBlob(
85100  PmaReader *p,                   /* PmaReader from which to take the blob */
85101  int nByte,                      /* Bytes of data to read */
85102  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
85103){
85104  int iBuf;                       /* Offset within buffer to read from */
85105  int nAvail;                     /* Bytes of data available in buffer */
85106
85107  if( p->aMap ){
85108    *ppOut = &p->aMap[p->iReadOff];
85109    p->iReadOff += nByte;
85110    return SQLITE_OK;
85111  }
85112
85113  assert( p->aBuffer );
85114
85115  /* If there is no more data to be read from the buffer, read the next
85116  ** p->nBuffer bytes of data from the file into it. Or, if there are less
85117  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
85118  iBuf = p->iReadOff % p->nBuffer;
85119  if( iBuf==0 ){
85120    int nRead;                    /* Bytes to read from disk */
85121    int rc;                       /* sqlite3OsRead() return code */
85122
85123    /* Determine how many bytes of data to read. */
85124    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
85125      nRead = p->nBuffer;
85126    }else{
85127      nRead = (int)(p->iEof - p->iReadOff);
85128    }
85129    assert( nRead>0 );
85130
85131    /* Readr data from the file. Return early if an error occurs. */
85132    rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
85133    assert( rc!=SQLITE_IOERR_SHORT_READ );
85134    if( rc!=SQLITE_OK ) return rc;
85135  }
85136  nAvail = p->nBuffer - iBuf;
85137
85138  if( nByte<=nAvail ){
85139    /* The requested data is available in the in-memory buffer. In this
85140    ** case there is no need to make a copy of the data, just return a
85141    ** pointer into the buffer to the caller.  */
85142    *ppOut = &p->aBuffer[iBuf];
85143    p->iReadOff += nByte;
85144  }else{
85145    /* The requested data is not all available in the in-memory buffer.
85146    ** In this case, allocate space at p->aAlloc[] to copy the requested
85147    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
85148    int nRem;                     /* Bytes remaining to copy */
85149
85150    /* Extend the p->aAlloc[] allocation if required. */
85151    if( p->nAlloc<nByte ){
85152      u8 *aNew;
85153      int nNew = MAX(128, p->nAlloc*2);
85154      while( nByte>nNew ) nNew = nNew*2;
85155      aNew = sqlite3Realloc(p->aAlloc, nNew);
85156      if( !aNew ) return SQLITE_NOMEM_BKPT;
85157      p->nAlloc = nNew;
85158      p->aAlloc = aNew;
85159    }
85160
85161    /* Copy as much data as is available in the buffer into the start of
85162    ** p->aAlloc[].  */
85163    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
85164    p->iReadOff += nAvail;
85165    nRem = nByte - nAvail;
85166
85167    /* The following loop copies up to p->nBuffer bytes per iteration into
85168    ** the p->aAlloc[] buffer.  */
85169    while( nRem>0 ){
85170      int rc;                     /* vdbePmaReadBlob() return code */
85171      int nCopy;                  /* Number of bytes to copy */
85172      u8 *aNext;                  /* Pointer to buffer to copy data from */
85173
85174      nCopy = nRem;
85175      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
85176      rc = vdbePmaReadBlob(p, nCopy, &aNext);
85177      if( rc!=SQLITE_OK ) return rc;
85178      assert( aNext!=p->aAlloc );
85179      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
85180      nRem -= nCopy;
85181    }
85182
85183    *ppOut = p->aAlloc;
85184  }
85185
85186  return SQLITE_OK;
85187}
85188
85189/*
85190** Read a varint from the stream of data accessed by p. Set *pnOut to
85191** the value read.
85192*/
85193static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
85194  int iBuf;
85195
85196  if( p->aMap ){
85197    p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
85198  }else{
85199    iBuf = p->iReadOff % p->nBuffer;
85200    if( iBuf && (p->nBuffer-iBuf)>=9 ){
85201      p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
85202    }else{
85203      u8 aVarint[16], *a;
85204      int i = 0, rc;
85205      do{
85206        rc = vdbePmaReadBlob(p, 1, &a);
85207        if( rc ) return rc;
85208        aVarint[(i++)&0xf] = a[0];
85209      }while( (a[0]&0x80)!=0 );
85210      sqlite3GetVarint(aVarint, pnOut);
85211    }
85212  }
85213
85214  return SQLITE_OK;
85215}
85216
85217/*
85218** Attempt to memory map file pFile. If successful, set *pp to point to the
85219** new mapping and return SQLITE_OK. If the mapping is not attempted
85220** (because the file is too large or the VFS layer is configured not to use
85221** mmap), return SQLITE_OK and set *pp to NULL.
85222**
85223** Or, if an error occurs, return an SQLite error code. The final value of
85224** *pp is undefined in this case.
85225*/
85226static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
85227  int rc = SQLITE_OK;
85228  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
85229    sqlite3_file *pFd = pFile->pFd;
85230    if( pFd->pMethods->iVersion>=3 ){
85231      rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
85232      testcase( rc!=SQLITE_OK );
85233    }
85234  }
85235  return rc;
85236}
85237
85238/*
85239** Attach PmaReader pReadr to file pFile (if it is not already attached to
85240** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
85241** if successful, or an SQLite error code if an error occurs.
85242*/
85243static int vdbePmaReaderSeek(
85244  SortSubtask *pTask,             /* Task context */
85245  PmaReader *pReadr,              /* Reader whose cursor is to be moved */
85246  SorterFile *pFile,              /* Sorter file to read from */
85247  i64 iOff                        /* Offset in pFile */
85248){
85249  int rc = SQLITE_OK;
85250
85251  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
85252
85253  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
85254  if( pReadr->aMap ){
85255    sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85256    pReadr->aMap = 0;
85257  }
85258  pReadr->iReadOff = iOff;
85259  pReadr->iEof = pFile->iEof;
85260  pReadr->pFd = pFile->pFd;
85261
85262  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
85263  if( rc==SQLITE_OK && pReadr->aMap==0 ){
85264    int pgsz = pTask->pSorter->pgsz;
85265    int iBuf = pReadr->iReadOff % pgsz;
85266    if( pReadr->aBuffer==0 ){
85267      pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
85268      if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
85269      pReadr->nBuffer = pgsz;
85270    }
85271    if( rc==SQLITE_OK && iBuf ){
85272      int nRead = pgsz - iBuf;
85273      if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
85274        nRead = (int)(pReadr->iEof - pReadr->iReadOff);
85275      }
85276      rc = sqlite3OsRead(
85277          pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
85278      );
85279      testcase( rc!=SQLITE_OK );
85280    }
85281  }
85282
85283  return rc;
85284}
85285
85286/*
85287** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
85288** no error occurs, or an SQLite error code if one does.
85289*/
85290static int vdbePmaReaderNext(PmaReader *pReadr){
85291  int rc = SQLITE_OK;             /* Return Code */
85292  u64 nRec = 0;                   /* Size of record in bytes */
85293
85294
85295  if( pReadr->iReadOff>=pReadr->iEof ){
85296    IncrMerger *pIncr = pReadr->pIncr;
85297    int bEof = 1;
85298    if( pIncr ){
85299      rc = vdbeIncrSwap(pIncr);
85300      if( rc==SQLITE_OK && pIncr->bEof==0 ){
85301        rc = vdbePmaReaderSeek(
85302            pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
85303        );
85304        bEof = 0;
85305      }
85306    }
85307
85308    if( bEof ){
85309      /* This is an EOF condition */
85310      vdbePmaReaderClear(pReadr);
85311      testcase( rc!=SQLITE_OK );
85312      return rc;
85313    }
85314  }
85315
85316  if( rc==SQLITE_OK ){
85317    rc = vdbePmaReadVarint(pReadr, &nRec);
85318  }
85319  if( rc==SQLITE_OK ){
85320    pReadr->nKey = (int)nRec;
85321    rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
85322    testcase( rc!=SQLITE_OK );
85323  }
85324
85325  return rc;
85326}
85327
85328/*
85329** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
85330** starting at offset iStart and ending at offset iEof-1. This function
85331** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
85332** PMA is empty).
85333**
85334** If the pnByte parameter is NULL, then it is assumed that the file
85335** contains a single PMA, and that that PMA omits the initial length varint.
85336*/
85337static int vdbePmaReaderInit(
85338  SortSubtask *pTask,             /* Task context */
85339  SorterFile *pFile,              /* Sorter file to read from */
85340  i64 iStart,                     /* Start offset in pFile */
85341  PmaReader *pReadr,              /* PmaReader to populate */
85342  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
85343){
85344  int rc;
85345
85346  assert( pFile->iEof>iStart );
85347  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
85348  assert( pReadr->aBuffer==0 );
85349  assert( pReadr->aMap==0 );
85350
85351  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
85352  if( rc==SQLITE_OK ){
85353    u64 nByte = 0;                 /* Size of PMA in bytes */
85354    rc = vdbePmaReadVarint(pReadr, &nByte);
85355    pReadr->iEof = pReadr->iReadOff + nByte;
85356    *pnByte += nByte;
85357  }
85358
85359  if( rc==SQLITE_OK ){
85360    rc = vdbePmaReaderNext(pReadr);
85361  }
85362  return rc;
85363}
85364
85365/*
85366** A version of vdbeSorterCompare() that assumes that it has already been
85367** determined that the first field of key1 is equal to the first field of
85368** key2.
85369*/
85370static int vdbeSorterCompareTail(
85371  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85372  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85373  const void *pKey1, int nKey1,   /* Left side of comparison */
85374  const void *pKey2, int nKey2    /* Right side of comparison */
85375){
85376  UnpackedRecord *r2 = pTask->pUnpacked;
85377  if( *pbKey2Cached==0 ){
85378    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85379    *pbKey2Cached = 1;
85380  }
85381  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
85382}
85383
85384/*
85385** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
85386** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
85387** used by the comparison. Return the result of the comparison.
85388**
85389** If IN/OUT parameter *pbKey2Cached is true when this function is called,
85390** it is assumed that (pTask->pUnpacked) contains the unpacked version
85391** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
85392** version of key2 and *pbKey2Cached set to true before returning.
85393**
85394** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
85395** to SQLITE_NOMEM.
85396*/
85397static int vdbeSorterCompare(
85398  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85399  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85400  const void *pKey1, int nKey1,   /* Left side of comparison */
85401  const void *pKey2, int nKey2    /* Right side of comparison */
85402){
85403  UnpackedRecord *r2 = pTask->pUnpacked;
85404  if( !*pbKey2Cached ){
85405    sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85406    *pbKey2Cached = 1;
85407  }
85408  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
85409}
85410
85411/*
85412** A specially optimized version of vdbeSorterCompare() that assumes that
85413** the first field of each key is a TEXT value and that the collation
85414** sequence to compare them with is BINARY.
85415*/
85416static int vdbeSorterCompareText(
85417  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85418  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85419  const void *pKey1, int nKey1,   /* Left side of comparison */
85420  const void *pKey2, int nKey2    /* Right side of comparison */
85421){
85422  const u8 * const p1 = (const u8 * const)pKey1;
85423  const u8 * const p2 = (const u8 * const)pKey2;
85424  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
85425  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
85426
85427  int n1;
85428  int n2;
85429  int res;
85430
85431  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
85432  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
85433  res = memcmp(v1, v2, MIN(n1, n2));
85434  if( res==0 ){
85435    res = n1 - n2;
85436  }
85437
85438  if( res==0 ){
85439    if( pTask->pSorter->pKeyInfo->nField>1 ){
85440      res = vdbeSorterCompareTail(
85441          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85442      );
85443    }
85444  }else{
85445    if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85446      res = res * -1;
85447    }
85448  }
85449
85450  return res;
85451}
85452
85453/*
85454** A specially optimized version of vdbeSorterCompare() that assumes that
85455** the first field of each key is an INTEGER value.
85456*/
85457static int vdbeSorterCompareInt(
85458  SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85459  int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85460  const void *pKey1, int nKey1,   /* Left side of comparison */
85461  const void *pKey2, int nKey2    /* Right side of comparison */
85462){
85463  const u8 * const p1 = (const u8 * const)pKey1;
85464  const u8 * const p2 = (const u8 * const)pKey2;
85465  const int s1 = p1[1];                 /* Left hand serial type */
85466  const int s2 = p2[1];                 /* Right hand serial type */
85467  const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
85468  const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
85469  int res;                              /* Return value */
85470
85471  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
85472  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
85473
85474  if( s1>7 && s2>7 ){
85475    res = s1 - s2;
85476  }else{
85477    if( s1==s2 ){
85478      if( (*v1 ^ *v2) & 0x80 ){
85479        /* The two values have different signs */
85480        res = (*v1 & 0x80) ? -1 : +1;
85481      }else{
85482        /* The two values have the same sign. Compare using memcmp(). */
85483        static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
85484        int i;
85485        res = 0;
85486        for(i=0; i<aLen[s1]; i++){
85487          if( (res = v1[i] - v2[i]) ) break;
85488        }
85489      }
85490    }else{
85491      if( s2>7 ){
85492        res = +1;
85493      }else if( s1>7 ){
85494        res = -1;
85495      }else{
85496        res = s1 - s2;
85497      }
85498      assert( res!=0 );
85499
85500      if( res>0 ){
85501        if( *v1 & 0x80 ) res = -1;
85502      }else{
85503        if( *v2 & 0x80 ) res = +1;
85504      }
85505    }
85506  }
85507
85508  if( res==0 ){
85509    if( pTask->pSorter->pKeyInfo->nField>1 ){
85510      res = vdbeSorterCompareTail(
85511          pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85512      );
85513    }
85514  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85515    res = res * -1;
85516  }
85517
85518  return res;
85519}
85520
85521/*
85522** Initialize the temporary index cursor just opened as a sorter cursor.
85523**
85524** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
85525** to determine the number of fields that should be compared from the
85526** records being sorted. However, if the value passed as argument nField
85527** is non-zero and the sorter is able to guarantee a stable sort, nField
85528** is used instead. This is used when sorting records for a CREATE INDEX
85529** statement. In this case, keys are always delivered to the sorter in
85530** order of the primary key, which happens to be make up the final part
85531** of the records being sorted. So if the sort is stable, there is never
85532** any reason to compare PK fields and they can be ignored for a small
85533** performance boost.
85534**
85535** The sorter can guarantee a stable sort when running in single-threaded
85536** mode, but not in multi-threaded mode.
85537**
85538** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
85539*/
85540SQLITE_PRIVATE int sqlite3VdbeSorterInit(
85541  sqlite3 *db,                    /* Database connection (for malloc()) */
85542  int nField,                     /* Number of key fields in each record */
85543  VdbeCursor *pCsr                /* Cursor that holds the new sorter */
85544){
85545  int pgsz;                       /* Page size of main database */
85546  int i;                          /* Used to iterate through aTask[] */
85547  VdbeSorter *pSorter;            /* The new sorter */
85548  KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
85549  int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
85550  int sz;                         /* Size of pSorter in bytes */
85551  int rc = SQLITE_OK;
85552#if SQLITE_MAX_WORKER_THREADS==0
85553# define nWorker 0
85554#else
85555  int nWorker;
85556#endif
85557
85558  /* Initialize the upper limit on the number of worker threads */
85559#if SQLITE_MAX_WORKER_THREADS>0
85560  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
85561    nWorker = 0;
85562  }else{
85563    nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
85564  }
85565#endif
85566
85567  /* Do not allow the total number of threads (main thread + all workers)
85568  ** to exceed the maximum merge count */
85569#if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
85570  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
85571    nWorker = SORTER_MAX_MERGE_COUNT-1;
85572  }
85573#endif
85574
85575  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
85576  assert( pCsr->eCurType==CURTYPE_SORTER );
85577  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
85578  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
85579
85580  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
85581  pCsr->uc.pSorter = pSorter;
85582  if( pSorter==0 ){
85583    rc = SQLITE_NOMEM_BKPT;
85584  }else{
85585    pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
85586    memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
85587    pKeyInfo->db = 0;
85588    if( nField && nWorker==0 ){
85589      pKeyInfo->nXField += (pKeyInfo->nField - nField);
85590      pKeyInfo->nField = nField;
85591    }
85592    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
85593    pSorter->nTask = nWorker + 1;
85594    pSorter->iPrev = (u8)(nWorker - 1);
85595    pSorter->bUseThreads = (pSorter->nTask>1);
85596    pSorter->db = db;
85597    for(i=0; i<pSorter->nTask; i++){
85598      SortSubtask *pTask = &pSorter->aTask[i];
85599      pTask->pSorter = pSorter;
85600    }
85601
85602    if( !sqlite3TempInMemory(db) ){
85603      i64 mxCache;                /* Cache size in bytes*/
85604      u32 szPma = sqlite3GlobalConfig.szPma;
85605      pSorter->mnPmaSize = szPma * pgsz;
85606
85607      mxCache = db->aDb[0].pSchema->cache_size;
85608      if( mxCache<0 ){
85609        /* A negative cache-size value C indicates that the cache is abs(C)
85610        ** KiB in size.  */
85611        mxCache = mxCache * -1024;
85612      }else{
85613        mxCache = mxCache * pgsz;
85614      }
85615      mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85616      pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85617
85618      /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85619      ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85620      ** large heap allocations.
85621      */
85622      if( sqlite3GlobalConfig.pScratch==0 ){
85623        assert( pSorter->iMemory==0 );
85624        pSorter->nMemory = pgsz;
85625        pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
85626        if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
85627      }
85628    }
85629
85630    if( (pKeyInfo->nField+pKeyInfo->nXField)<13
85631     && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
85632    ){
85633      pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
85634    }
85635  }
85636
85637  return rc;
85638}
85639#undef nWorker   /* Defined at the top of this function */
85640
85641/*
85642** Free the list of sorted records starting at pRecord.
85643*/
85644static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
85645  SorterRecord *p;
85646  SorterRecord *pNext;
85647  for(p=pRecord; p; p=pNext){
85648    pNext = p->u.pNext;
85649    sqlite3DbFree(db, p);
85650  }
85651}
85652
85653/*
85654** Free all resources owned by the object indicated by argument pTask. All
85655** fields of *pTask are zeroed before returning.
85656*/
85657static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
85658  sqlite3DbFree(db, pTask->pUnpacked);
85659#if SQLITE_MAX_WORKER_THREADS>0
85660  /* pTask->list.aMemory can only be non-zero if it was handed memory
85661  ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
85662  if( pTask->list.aMemory ){
85663    sqlite3_free(pTask->list.aMemory);
85664  }else
85665#endif
85666  {
85667    assert( pTask->list.aMemory==0 );
85668    vdbeSorterRecordFree(0, pTask->list.pList);
85669  }
85670  if( pTask->file.pFd ){
85671    sqlite3OsCloseFree(pTask->file.pFd);
85672  }
85673  if( pTask->file2.pFd ){
85674    sqlite3OsCloseFree(pTask->file2.pFd);
85675  }
85676  memset(pTask, 0, sizeof(SortSubtask));
85677}
85678
85679#ifdef SQLITE_DEBUG_SORTER_THREADS
85680static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
85681  i64 t;
85682  int iTask = (pTask - pTask->pSorter->aTask);
85683  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85684  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
85685}
85686static void vdbeSorterRewindDebug(const char *zEvent){
85687  i64 t;
85688  sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
85689  fprintf(stderr, "%lld:X %s\n", t, zEvent);
85690}
85691static void vdbeSorterPopulateDebug(
85692  SortSubtask *pTask,
85693  const char *zEvent
85694){
85695  i64 t;
85696  int iTask = (pTask - pTask->pSorter->aTask);
85697  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85698  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
85699}
85700static void vdbeSorterBlockDebug(
85701  SortSubtask *pTask,
85702  int bBlocked,
85703  const char *zEvent
85704){
85705  if( bBlocked ){
85706    i64 t;
85707    sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85708    fprintf(stderr, "%lld:main %s\n", t, zEvent);
85709  }
85710}
85711#else
85712# define vdbeSorterWorkDebug(x,y)
85713# define vdbeSorterRewindDebug(y)
85714# define vdbeSorterPopulateDebug(x,y)
85715# define vdbeSorterBlockDebug(x,y,z)
85716#endif
85717
85718#if SQLITE_MAX_WORKER_THREADS>0
85719/*
85720** Join thread pTask->thread.
85721*/
85722static int vdbeSorterJoinThread(SortSubtask *pTask){
85723  int rc = SQLITE_OK;
85724  if( pTask->pThread ){
85725#ifdef SQLITE_DEBUG_SORTER_THREADS
85726    int bDone = pTask->bDone;
85727#endif
85728    void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
85729    vdbeSorterBlockDebug(pTask, !bDone, "enter");
85730    (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
85731    vdbeSorterBlockDebug(pTask, !bDone, "exit");
85732    rc = SQLITE_PTR_TO_INT(pRet);
85733    assert( pTask->bDone==1 );
85734    pTask->bDone = 0;
85735    pTask->pThread = 0;
85736  }
85737  return rc;
85738}
85739
85740/*
85741** Launch a background thread to run xTask(pIn).
85742*/
85743static int vdbeSorterCreateThread(
85744  SortSubtask *pTask,             /* Thread will use this task object */
85745  void *(*xTask)(void*),          /* Routine to run in a separate thread */
85746  void *pIn                       /* Argument passed into xTask() */
85747){
85748  assert( pTask->pThread==0 && pTask->bDone==0 );
85749  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
85750}
85751
85752/*
85753** Join all outstanding threads launched by SorterWrite() to create
85754** level-0 PMAs.
85755*/
85756static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
85757  int rc = rcin;
85758  int i;
85759
85760  /* This function is always called by the main user thread.
85761  **
85762  ** If this function is being called after SorterRewind() has been called,
85763  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
85764  ** is currently attempt to join one of the other threads. To avoid a race
85765  ** condition where this thread also attempts to join the same object, join
85766  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
85767  for(i=pSorter->nTask-1; i>=0; i--){
85768    SortSubtask *pTask = &pSorter->aTask[i];
85769    int rc2 = vdbeSorterJoinThread(pTask);
85770    if( rc==SQLITE_OK ) rc = rc2;
85771  }
85772  return rc;
85773}
85774#else
85775# define vdbeSorterJoinAll(x,rcin) (rcin)
85776# define vdbeSorterJoinThread(pTask) SQLITE_OK
85777#endif
85778
85779/*
85780** Allocate a new MergeEngine object capable of handling up to
85781** nReader PmaReader inputs.
85782**
85783** nReader is automatically rounded up to the next power of two.
85784** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
85785*/
85786static MergeEngine *vdbeMergeEngineNew(int nReader){
85787  int N = 2;                      /* Smallest power of two >= nReader */
85788  int nByte;                      /* Total bytes of space to allocate */
85789  MergeEngine *pNew;              /* Pointer to allocated object to return */
85790
85791  assert( nReader<=SORTER_MAX_MERGE_COUNT );
85792
85793  while( N<nReader ) N += N;
85794  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
85795
85796  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
85797  if( pNew ){
85798    pNew->nTree = N;
85799    pNew->pTask = 0;
85800    pNew->aReadr = (PmaReader*)&pNew[1];
85801    pNew->aTree = (int*)&pNew->aReadr[N];
85802  }
85803  return pNew;
85804}
85805
85806/*
85807** Free the MergeEngine object passed as the only argument.
85808*/
85809static void vdbeMergeEngineFree(MergeEngine *pMerger){
85810  int i;
85811  if( pMerger ){
85812    for(i=0; i<pMerger->nTree; i++){
85813      vdbePmaReaderClear(&pMerger->aReadr[i]);
85814    }
85815  }
85816  sqlite3_free(pMerger);
85817}
85818
85819/*
85820** Free all resources associated with the IncrMerger object indicated by
85821** the first argument.
85822*/
85823static void vdbeIncrFree(IncrMerger *pIncr){
85824  if( pIncr ){
85825#if SQLITE_MAX_WORKER_THREADS>0
85826    if( pIncr->bUseThread ){
85827      vdbeSorterJoinThread(pIncr->pTask);
85828      if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
85829      if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
85830    }
85831#endif
85832    vdbeMergeEngineFree(pIncr->pMerger);
85833    sqlite3_free(pIncr);
85834  }
85835}
85836
85837/*
85838** Reset a sorting cursor back to its original empty state.
85839*/
85840SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
85841  int i;
85842  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
85843  assert( pSorter->bUseThreads || pSorter->pReader==0 );
85844#if SQLITE_MAX_WORKER_THREADS>0
85845  if( pSorter->pReader ){
85846    vdbePmaReaderClear(pSorter->pReader);
85847    sqlite3DbFree(db, pSorter->pReader);
85848    pSorter->pReader = 0;
85849  }
85850#endif
85851  vdbeMergeEngineFree(pSorter->pMerger);
85852  pSorter->pMerger = 0;
85853  for(i=0; i<pSorter->nTask; i++){
85854    SortSubtask *pTask = &pSorter->aTask[i];
85855    vdbeSortSubtaskCleanup(db, pTask);
85856    pTask->pSorter = pSorter;
85857  }
85858  if( pSorter->list.aMemory==0 ){
85859    vdbeSorterRecordFree(0, pSorter->list.pList);
85860  }
85861  pSorter->list.pList = 0;
85862  pSorter->list.szPMA = 0;
85863  pSorter->bUsePMA = 0;
85864  pSorter->iMemory = 0;
85865  pSorter->mxKeysize = 0;
85866  sqlite3DbFree(db, pSorter->pUnpacked);
85867  pSorter->pUnpacked = 0;
85868}
85869
85870/*
85871** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
85872*/
85873SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
85874  VdbeSorter *pSorter;
85875  assert( pCsr->eCurType==CURTYPE_SORTER );
85876  pSorter = pCsr->uc.pSorter;
85877  if( pSorter ){
85878    sqlite3VdbeSorterReset(db, pSorter);
85879    sqlite3_free(pSorter->list.aMemory);
85880    sqlite3DbFree(db, pSorter);
85881    pCsr->uc.pSorter = 0;
85882  }
85883}
85884
85885#if SQLITE_MAX_MMAP_SIZE>0
85886/*
85887** The first argument is a file-handle open on a temporary file. The file
85888** is guaranteed to be nByte bytes or smaller in size. This function
85889** attempts to extend the file to nByte bytes in size and to ensure that
85890** the VFS has memory mapped it.
85891**
85892** Whether or not the file does end up memory mapped of course depends on
85893** the specific VFS implementation.
85894*/
85895static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
85896  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
85897    void *p = 0;
85898    int chunksize = 4*1024;
85899    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
85900    sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
85901    sqlite3OsFetch(pFd, 0, (int)nByte, &p);
85902    sqlite3OsUnfetch(pFd, 0, p);
85903  }
85904}
85905#else
85906# define vdbeSorterExtendFile(x,y,z)
85907#endif
85908
85909/*
85910** Allocate space for a file-handle and open a temporary file. If successful,
85911** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
85912** Otherwise, set *ppFd to 0 and return an SQLite error code.
85913*/
85914static int vdbeSorterOpenTempFile(
85915  sqlite3 *db,                    /* Database handle doing sort */
85916  i64 nExtend,                    /* Attempt to extend file to this size */
85917  sqlite3_file **ppFd
85918){
85919  int rc;
85920  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
85921  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
85922      SQLITE_OPEN_TEMP_JOURNAL |
85923      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
85924      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
85925  );
85926  if( rc==SQLITE_OK ){
85927    i64 max = SQLITE_MAX_MMAP_SIZE;
85928    sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
85929    if( nExtend>0 ){
85930      vdbeSorterExtendFile(db, *ppFd, nExtend);
85931    }
85932  }
85933  return rc;
85934}
85935
85936/*
85937** If it has not already been allocated, allocate the UnpackedRecord
85938** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
85939** if no allocation was required), or SQLITE_NOMEM otherwise.
85940*/
85941static int vdbeSortAllocUnpacked(SortSubtask *pTask){
85942  if( pTask->pUnpacked==0 ){
85943    char *pFree;
85944    pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
85945        pTask->pSorter->pKeyInfo, 0, 0, &pFree
85946    );
85947    assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
85948    if( pFree==0 ) return SQLITE_NOMEM_BKPT;
85949    pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
85950    pTask->pUnpacked->errCode = 0;
85951  }
85952  return SQLITE_OK;
85953}
85954
85955
85956/*
85957** Merge the two sorted lists p1 and p2 into a single list.
85958*/
85959static SorterRecord *vdbeSorterMerge(
85960  SortSubtask *pTask,             /* Calling thread context */
85961  SorterRecord *p1,               /* First list to merge */
85962  SorterRecord *p2                /* Second list to merge */
85963){
85964  SorterRecord *pFinal = 0;
85965  SorterRecord **pp = &pFinal;
85966  int bCached = 0;
85967
85968  assert( p1!=0 && p2!=0 );
85969  for(;;){
85970    int res;
85971    res = pTask->xCompare(
85972        pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
85973    );
85974
85975    if( res<=0 ){
85976      *pp = p1;
85977      pp = &p1->u.pNext;
85978      p1 = p1->u.pNext;
85979      if( p1==0 ){
85980        *pp = p2;
85981        break;
85982      }
85983    }else{
85984      *pp = p2;
85985      pp = &p2->u.pNext;
85986      p2 = p2->u.pNext;
85987      bCached = 0;
85988      if( p2==0 ){
85989        *pp = p1;
85990        break;
85991      }
85992    }
85993  }
85994  return pFinal;
85995}
85996
85997/*
85998** Return the SorterCompare function to compare values collected by the
85999** sorter object passed as the only argument.
86000*/
86001static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
86002  if( p->typeMask==SORTER_TYPE_INTEGER ){
86003    return vdbeSorterCompareInt;
86004  }else if( p->typeMask==SORTER_TYPE_TEXT ){
86005    return vdbeSorterCompareText;
86006  }
86007  return vdbeSorterCompare;
86008}
86009
86010/*
86011** Sort the linked list of records headed at pTask->pList. Return
86012** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
86013** an error occurs.
86014*/
86015static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
86016  int i;
86017  SorterRecord **aSlot;
86018  SorterRecord *p;
86019  int rc;
86020
86021  rc = vdbeSortAllocUnpacked(pTask);
86022  if( rc!=SQLITE_OK ) return rc;
86023
86024  p = pList->pList;
86025  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
86026
86027  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
86028  if( !aSlot ){
86029    return SQLITE_NOMEM_BKPT;
86030  }
86031
86032  while( p ){
86033    SorterRecord *pNext;
86034    if( pList->aMemory ){
86035      if( (u8*)p==pList->aMemory ){
86036        pNext = 0;
86037      }else{
86038        assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
86039        pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
86040      }
86041    }else{
86042      pNext = p->u.pNext;
86043    }
86044
86045    p->u.pNext = 0;
86046    for(i=0; aSlot[i]; i++){
86047      p = vdbeSorterMerge(pTask, p, aSlot[i]);
86048      aSlot[i] = 0;
86049    }
86050    aSlot[i] = p;
86051    p = pNext;
86052  }
86053
86054  p = 0;
86055  for(i=0; i<64; i++){
86056    if( aSlot[i]==0 ) continue;
86057    p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
86058  }
86059  pList->pList = p;
86060
86061  sqlite3_free(aSlot);
86062  assert( pTask->pUnpacked->errCode==SQLITE_OK
86063       || pTask->pUnpacked->errCode==SQLITE_NOMEM
86064  );
86065  return pTask->pUnpacked->errCode;
86066}
86067
86068/*
86069** Initialize a PMA-writer object.
86070*/
86071static void vdbePmaWriterInit(
86072  sqlite3_file *pFd,              /* File handle to write to */
86073  PmaWriter *p,                   /* Object to populate */
86074  int nBuf,                       /* Buffer size */
86075  i64 iStart                      /* Offset of pFd to begin writing at */
86076){
86077  memset(p, 0, sizeof(PmaWriter));
86078  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
86079  if( !p->aBuffer ){
86080    p->eFWErr = SQLITE_NOMEM_BKPT;
86081  }else{
86082    p->iBufEnd = p->iBufStart = (iStart % nBuf);
86083    p->iWriteOff = iStart - p->iBufStart;
86084    p->nBuffer = nBuf;
86085    p->pFd = pFd;
86086  }
86087}
86088
86089/*
86090** Write nData bytes of data to the PMA. Return SQLITE_OK
86091** if successful, or an SQLite error code if an error occurs.
86092*/
86093static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
86094  int nRem = nData;
86095  while( nRem>0 && p->eFWErr==0 ){
86096    int nCopy = nRem;
86097    if( nCopy>(p->nBuffer - p->iBufEnd) ){
86098      nCopy = p->nBuffer - p->iBufEnd;
86099    }
86100
86101    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
86102    p->iBufEnd += nCopy;
86103    if( p->iBufEnd==p->nBuffer ){
86104      p->eFWErr = sqlite3OsWrite(p->pFd,
86105          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86106          p->iWriteOff + p->iBufStart
86107      );
86108      p->iBufStart = p->iBufEnd = 0;
86109      p->iWriteOff += p->nBuffer;
86110    }
86111    assert( p->iBufEnd<p->nBuffer );
86112
86113    nRem -= nCopy;
86114  }
86115}
86116
86117/*
86118** Flush any buffered data to disk and clean up the PMA-writer object.
86119** The results of using the PMA-writer after this call are undefined.
86120** Return SQLITE_OK if flushing the buffered data succeeds or is not
86121** required. Otherwise, return an SQLite error code.
86122**
86123** Before returning, set *piEof to the offset immediately following the
86124** last byte written to the file.
86125*/
86126static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
86127  int rc;
86128  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
86129    p->eFWErr = sqlite3OsWrite(p->pFd,
86130        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86131        p->iWriteOff + p->iBufStart
86132    );
86133  }
86134  *piEof = (p->iWriteOff + p->iBufEnd);
86135  sqlite3_free(p->aBuffer);
86136  rc = p->eFWErr;
86137  memset(p, 0, sizeof(PmaWriter));
86138  return rc;
86139}
86140
86141/*
86142** Write value iVal encoded as a varint to the PMA. Return
86143** SQLITE_OK if successful, or an SQLite error code if an error occurs.
86144*/
86145static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
86146  int nByte;
86147  u8 aByte[10];
86148  nByte = sqlite3PutVarint(aByte, iVal);
86149  vdbePmaWriteBlob(p, aByte, nByte);
86150}
86151
86152/*
86153** Write the current contents of in-memory linked-list pList to a level-0
86154** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
86155** successful, or an SQLite error code otherwise.
86156**
86157** The format of a PMA is:
86158**
86159**     * A varint. This varint contains the total number of bytes of content
86160**       in the PMA (not including the varint itself).
86161**
86162**     * One or more records packed end-to-end in order of ascending keys.
86163**       Each record consists of a varint followed by a blob of data (the
86164**       key). The varint is the number of bytes in the blob of data.
86165*/
86166static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
86167  sqlite3 *db = pTask->pSorter->db;
86168  int rc = SQLITE_OK;             /* Return code */
86169  PmaWriter writer;               /* Object used to write to the file */
86170
86171#ifdef SQLITE_DEBUG
86172  /* Set iSz to the expected size of file pTask->file after writing the PMA.
86173  ** This is used by an assert() statement at the end of this function.  */
86174  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
86175#endif
86176
86177  vdbeSorterWorkDebug(pTask, "enter");
86178  memset(&writer, 0, sizeof(PmaWriter));
86179  assert( pList->szPMA>0 );
86180
86181  /* If the first temporary PMA file has not been opened, open it now. */
86182  if( pTask->file.pFd==0 ){
86183    rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
86184    assert( rc!=SQLITE_OK || pTask->file.pFd );
86185    assert( pTask->file.iEof==0 );
86186    assert( pTask->nPMA==0 );
86187  }
86188
86189  /* Try to get the file to memory map */
86190  if( rc==SQLITE_OK ){
86191    vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
86192  }
86193
86194  /* Sort the list */
86195  if( rc==SQLITE_OK ){
86196    rc = vdbeSorterSort(pTask, pList);
86197  }
86198
86199  if( rc==SQLITE_OK ){
86200    SorterRecord *p;
86201    SorterRecord *pNext = 0;
86202
86203    vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
86204                      pTask->file.iEof);
86205    pTask->nPMA++;
86206    vdbePmaWriteVarint(&writer, pList->szPMA);
86207    for(p=pList->pList; p; p=pNext){
86208      pNext = p->u.pNext;
86209      vdbePmaWriteVarint(&writer, p->nVal);
86210      vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
86211      if( pList->aMemory==0 ) sqlite3_free(p);
86212    }
86213    pList->pList = p;
86214    rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
86215  }
86216
86217  vdbeSorterWorkDebug(pTask, "exit");
86218  assert( rc!=SQLITE_OK || pList->pList==0 );
86219  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
86220  return rc;
86221}
86222
86223/*
86224** Advance the MergeEngine to its next entry.
86225** Set *pbEof to true there is no next entry because
86226** the MergeEngine has reached the end of all its inputs.
86227**
86228** Return SQLITE_OK if successful or an error code if an error occurs.
86229*/
86230static int vdbeMergeEngineStep(
86231  MergeEngine *pMerger,      /* The merge engine to advance to the next row */
86232  int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
86233){
86234  int rc;
86235  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
86236  SortSubtask *pTask = pMerger->pTask;
86237
86238  /* Advance the current PmaReader */
86239  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
86240
86241  /* Update contents of aTree[] */
86242  if( rc==SQLITE_OK ){
86243    int i;                      /* Index of aTree[] to recalculate */
86244    PmaReader *pReadr1;         /* First PmaReader to compare */
86245    PmaReader *pReadr2;         /* Second PmaReader to compare */
86246    int bCached = 0;
86247
86248    /* Find the first two PmaReaders to compare. The one that was just
86249    ** advanced (iPrev) and the one next to it in the array.  */
86250    pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
86251    pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
86252
86253    for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
86254      /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
86255      int iRes;
86256      if( pReadr1->pFd==0 ){
86257        iRes = +1;
86258      }else if( pReadr2->pFd==0 ){
86259        iRes = -1;
86260      }else{
86261        iRes = pTask->xCompare(pTask, &bCached,
86262            pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
86263        );
86264      }
86265
86266      /* If pReadr1 contained the smaller value, set aTree[i] to its index.
86267      ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
86268      ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
86269      ** pKey2 to point to the record belonging to pReadr2.
86270      **
86271      ** Alternatively, if pReadr2 contains the smaller of the two values,
86272      ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
86273      ** was actually called above, then pTask->pUnpacked now contains
86274      ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
86275      ** vdbeSorterCompare() from decoding pReadr2 again.
86276      **
86277      ** If the two values were equal, then the value from the oldest
86278      ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
86279      ** is sorted from oldest to newest, so pReadr1 contains older values
86280      ** than pReadr2 iff (pReadr1<pReadr2).  */
86281      if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
86282        pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
86283        pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86284        bCached = 0;
86285      }else{
86286        if( pReadr1->pFd ) bCached = 0;
86287        pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
86288        pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86289      }
86290    }
86291    *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
86292  }
86293
86294  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
86295}
86296
86297#if SQLITE_MAX_WORKER_THREADS>0
86298/*
86299** The main routine for background threads that write level-0 PMAs.
86300*/
86301static void *vdbeSorterFlushThread(void *pCtx){
86302  SortSubtask *pTask = (SortSubtask*)pCtx;
86303  int rc;                         /* Return code */
86304  assert( pTask->bDone==0 );
86305  rc = vdbeSorterListToPMA(pTask, &pTask->list);
86306  pTask->bDone = 1;
86307  return SQLITE_INT_TO_PTR(rc);
86308}
86309#endif /* SQLITE_MAX_WORKER_THREADS>0 */
86310
86311/*
86312** Flush the current contents of VdbeSorter.list to a new PMA, possibly
86313** using a background thread.
86314*/
86315static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
86316#if SQLITE_MAX_WORKER_THREADS==0
86317  pSorter->bUsePMA = 1;
86318  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
86319#else
86320  int rc = SQLITE_OK;
86321  int i;
86322  SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
86323  int nWorker = (pSorter->nTask-1);
86324
86325  /* Set the flag to indicate that at least one PMA has been written.
86326  ** Or will be, anyhow.  */
86327  pSorter->bUsePMA = 1;
86328
86329  /* Select a sub-task to sort and flush the current list of in-memory
86330  ** records to disk. If the sorter is running in multi-threaded mode,
86331  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
86332  ** the background thread from a sub-tasks previous turn is still running,
86333  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
86334  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
86335  ** sub-tasks are prefered as they use background threads - the final
86336  ** sub-task uses the main thread. */
86337  for(i=0; i<nWorker; i++){
86338    int iTest = (pSorter->iPrev + i + 1) % nWorker;
86339    pTask = &pSorter->aTask[iTest];
86340    if( pTask->bDone ){
86341      rc = vdbeSorterJoinThread(pTask);
86342    }
86343    if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
86344  }
86345
86346  if( rc==SQLITE_OK ){
86347    if( i==nWorker ){
86348      /* Use the foreground thread for this operation */
86349      rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
86350    }else{
86351      /* Launch a background thread for this operation */
86352      u8 *aMem = pTask->list.aMemory;
86353      void *pCtx = (void*)pTask;
86354
86355      assert( pTask->pThread==0 && pTask->bDone==0 );
86356      assert( pTask->list.pList==0 );
86357      assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
86358
86359      pSorter->iPrev = (u8)(pTask - pSorter->aTask);
86360      pTask->list = pSorter->list;
86361      pSorter->list.pList = 0;
86362      pSorter->list.szPMA = 0;
86363      if( aMem ){
86364        pSorter->list.aMemory = aMem;
86365        pSorter->nMemory = sqlite3MallocSize(aMem);
86366      }else if( pSorter->list.aMemory ){
86367        pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
86368        if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
86369      }
86370
86371      rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
86372    }
86373  }
86374
86375  return rc;
86376#endif /* SQLITE_MAX_WORKER_THREADS!=0 */
86377}
86378
86379/*
86380** Add a record to the sorter.
86381*/
86382SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
86383  const VdbeCursor *pCsr,         /* Sorter cursor */
86384  Mem *pVal                       /* Memory cell containing record */
86385){
86386  VdbeSorter *pSorter;
86387  int rc = SQLITE_OK;             /* Return Code */
86388  SorterRecord *pNew;             /* New list element */
86389  int bFlush;                     /* True to flush contents of memory to PMA */
86390  int nReq;                       /* Bytes of memory required */
86391  int nPMA;                       /* Bytes of PMA space required */
86392  int t;                          /* serial type of first record field */
86393
86394  assert( pCsr->eCurType==CURTYPE_SORTER );
86395  pSorter = pCsr->uc.pSorter;
86396  getVarint32((const u8*)&pVal->z[1], t);
86397  if( t>0 && t<10 && t!=7 ){
86398    pSorter->typeMask &= SORTER_TYPE_INTEGER;
86399  }else if( t>10 && (t & 0x01) ){
86400    pSorter->typeMask &= SORTER_TYPE_TEXT;
86401  }else{
86402    pSorter->typeMask = 0;
86403  }
86404
86405  assert( pSorter );
86406
86407  /* Figure out whether or not the current contents of memory should be
86408  ** flushed to a PMA before continuing. If so, do so.
86409  **
86410  ** If using the single large allocation mode (pSorter->aMemory!=0), then
86411  ** flush the contents of memory to a new PMA if (a) at least one value is
86412  ** already in memory and (b) the new value will not fit in memory.
86413  **
86414  ** Or, if using separate allocations for each record, flush the contents
86415  ** of memory to a PMA if either of the following are true:
86416  **
86417  **   * The total memory allocated for the in-memory list is greater
86418  **     than (page-size * cache-size), or
86419  **
86420  **   * The total memory allocated for the in-memory list is greater
86421  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
86422  */
86423  nReq = pVal->n + sizeof(SorterRecord);
86424  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
86425  if( pSorter->mxPmaSize ){
86426    if( pSorter->list.aMemory ){
86427      bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
86428    }else{
86429      bFlush = (
86430          (pSorter->list.szPMA > pSorter->mxPmaSize)
86431       || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
86432      );
86433    }
86434    if( bFlush ){
86435      rc = vdbeSorterFlushPMA(pSorter);
86436      pSorter->list.szPMA = 0;
86437      pSorter->iMemory = 0;
86438      assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
86439    }
86440  }
86441
86442  pSorter->list.szPMA += nPMA;
86443  if( nPMA>pSorter->mxKeysize ){
86444    pSorter->mxKeysize = nPMA;
86445  }
86446
86447  if( pSorter->list.aMemory ){
86448    int nMin = pSorter->iMemory + nReq;
86449
86450    if( nMin>pSorter->nMemory ){
86451      u8 *aNew;
86452      int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
86453      int nNew = pSorter->nMemory * 2;
86454      while( nNew < nMin ) nNew = nNew*2;
86455      if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
86456      if( nNew < nMin ) nNew = nMin;
86457
86458      aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
86459      if( !aNew ) return SQLITE_NOMEM_BKPT;
86460      pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
86461      pSorter->list.aMemory = aNew;
86462      pSorter->nMemory = nNew;
86463    }
86464
86465    pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
86466    pSorter->iMemory += ROUND8(nReq);
86467    if( pSorter->list.pList ){
86468      pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
86469    }
86470  }else{
86471    pNew = (SorterRecord *)sqlite3Malloc(nReq);
86472    if( pNew==0 ){
86473      return SQLITE_NOMEM_BKPT;
86474    }
86475    pNew->u.pNext = pSorter->list.pList;
86476  }
86477
86478  memcpy(SRVAL(pNew), pVal->z, pVal->n);
86479  pNew->nVal = pVal->n;
86480  pSorter->list.pList = pNew;
86481
86482  return rc;
86483}
86484
86485/*
86486** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
86487** of the data stored in aFile[1] is the same as that used by regular PMAs,
86488** except that the number-of-bytes varint is omitted from the start.
86489*/
86490static int vdbeIncrPopulate(IncrMerger *pIncr){
86491  int rc = SQLITE_OK;
86492  int rc2;
86493  i64 iStart = pIncr->iStartOff;
86494  SorterFile *pOut = &pIncr->aFile[1];
86495  SortSubtask *pTask = pIncr->pTask;
86496  MergeEngine *pMerger = pIncr->pMerger;
86497  PmaWriter writer;
86498  assert( pIncr->bEof==0 );
86499
86500  vdbeSorterPopulateDebug(pTask, "enter");
86501
86502  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
86503  while( rc==SQLITE_OK ){
86504    int dummy;
86505    PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
86506    int nKey = pReader->nKey;
86507    i64 iEof = writer.iWriteOff + writer.iBufEnd;
86508
86509    /* Check if the output file is full or if the input has been exhausted.
86510    ** In either case exit the loop. */
86511    if( pReader->pFd==0 ) break;
86512    if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
86513
86514    /* Write the next key to the output. */
86515    vdbePmaWriteVarint(&writer, nKey);
86516    vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
86517    assert( pIncr->pMerger->pTask==pTask );
86518    rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
86519  }
86520
86521  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
86522  if( rc==SQLITE_OK ) rc = rc2;
86523  vdbeSorterPopulateDebug(pTask, "exit");
86524  return rc;
86525}
86526
86527#if SQLITE_MAX_WORKER_THREADS>0
86528/*
86529** The main routine for background threads that populate aFile[1] of
86530** multi-threaded IncrMerger objects.
86531*/
86532static void *vdbeIncrPopulateThread(void *pCtx){
86533  IncrMerger *pIncr = (IncrMerger*)pCtx;
86534  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
86535  pIncr->pTask->bDone = 1;
86536  return pRet;
86537}
86538
86539/*
86540** Launch a background thread to populate aFile[1] of pIncr.
86541*/
86542static int vdbeIncrBgPopulate(IncrMerger *pIncr){
86543  void *p = (void*)pIncr;
86544  assert( pIncr->bUseThread );
86545  return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
86546}
86547#endif
86548
86549/*
86550** This function is called when the PmaReader corresponding to pIncr has
86551** finished reading the contents of aFile[0]. Its purpose is to "refill"
86552** aFile[0] such that the PmaReader should start rereading it from the
86553** beginning.
86554**
86555** For single-threaded objects, this is accomplished by literally reading
86556** keys from pIncr->pMerger and repopulating aFile[0].
86557**
86558** For multi-threaded objects, all that is required is to wait until the
86559** background thread is finished (if it is not already) and then swap
86560** aFile[0] and aFile[1] in place. If the contents of pMerger have not
86561** been exhausted, this function also launches a new background thread
86562** to populate the new aFile[1].
86563**
86564** SQLITE_OK is returned on success, or an SQLite error code otherwise.
86565*/
86566static int vdbeIncrSwap(IncrMerger *pIncr){
86567  int rc = SQLITE_OK;
86568
86569#if SQLITE_MAX_WORKER_THREADS>0
86570  if( pIncr->bUseThread ){
86571    rc = vdbeSorterJoinThread(pIncr->pTask);
86572
86573    if( rc==SQLITE_OK ){
86574      SorterFile f0 = pIncr->aFile[0];
86575      pIncr->aFile[0] = pIncr->aFile[1];
86576      pIncr->aFile[1] = f0;
86577    }
86578
86579    if( rc==SQLITE_OK ){
86580      if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86581        pIncr->bEof = 1;
86582      }else{
86583        rc = vdbeIncrBgPopulate(pIncr);
86584      }
86585    }
86586  }else
86587#endif
86588  {
86589    rc = vdbeIncrPopulate(pIncr);
86590    pIncr->aFile[0] = pIncr->aFile[1];
86591    if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86592      pIncr->bEof = 1;
86593    }
86594  }
86595
86596  return rc;
86597}
86598
86599/*
86600** Allocate and return a new IncrMerger object to read data from pMerger.
86601**
86602** If an OOM condition is encountered, return NULL. In this case free the
86603** pMerger argument before returning.
86604*/
86605static int vdbeIncrMergerNew(
86606  SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
86607  MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
86608  IncrMerger **ppOut      /* Write the new IncrMerger here */
86609){
86610  int rc = SQLITE_OK;
86611  IncrMerger *pIncr = *ppOut = (IncrMerger*)
86612       (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
86613  if( pIncr ){
86614    pIncr->pMerger = pMerger;
86615    pIncr->pTask = pTask;
86616    pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
86617    pTask->file2.iEof += pIncr->mxSz;
86618  }else{
86619    vdbeMergeEngineFree(pMerger);
86620    rc = SQLITE_NOMEM_BKPT;
86621  }
86622  return rc;
86623}
86624
86625#if SQLITE_MAX_WORKER_THREADS>0
86626/*
86627** Set the "use-threads" flag on object pIncr.
86628*/
86629static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
86630  pIncr->bUseThread = 1;
86631  pIncr->pTask->file2.iEof -= pIncr->mxSz;
86632}
86633#endif /* SQLITE_MAX_WORKER_THREADS>0 */
86634
86635
86636
86637/*
86638** Recompute pMerger->aTree[iOut] by comparing the next keys on the
86639** two PmaReaders that feed that entry.  Neither of the PmaReaders
86640** are advanced.  This routine merely does the comparison.
86641*/
86642static void vdbeMergeEngineCompare(
86643  MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
86644  int iOut               /* Store the result in pMerger->aTree[iOut] */
86645){
86646  int i1;
86647  int i2;
86648  int iRes;
86649  PmaReader *p1;
86650  PmaReader *p2;
86651
86652  assert( iOut<pMerger->nTree && iOut>0 );
86653
86654  if( iOut>=(pMerger->nTree/2) ){
86655    i1 = (iOut - pMerger->nTree/2) * 2;
86656    i2 = i1 + 1;
86657  }else{
86658    i1 = pMerger->aTree[iOut*2];
86659    i2 = pMerger->aTree[iOut*2+1];
86660  }
86661
86662  p1 = &pMerger->aReadr[i1];
86663  p2 = &pMerger->aReadr[i2];
86664
86665  if( p1->pFd==0 ){
86666    iRes = i2;
86667  }else if( p2->pFd==0 ){
86668    iRes = i1;
86669  }else{
86670    SortSubtask *pTask = pMerger->pTask;
86671    int bCached = 0;
86672    int res;
86673    assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
86674    res = pTask->xCompare(
86675        pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
86676    );
86677    if( res<=0 ){
86678      iRes = i1;
86679    }else{
86680      iRes = i2;
86681    }
86682  }
86683
86684  pMerger->aTree[iOut] = iRes;
86685}
86686
86687/*
86688** Allowed values for the eMode parameter to vdbeMergeEngineInit()
86689** and vdbePmaReaderIncrMergeInit().
86690**
86691** Only INCRINIT_NORMAL is valid in single-threaded builds (when
86692** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
86693** when there exists one or more separate worker threads.
86694*/
86695#define INCRINIT_NORMAL 0
86696#define INCRINIT_TASK   1
86697#define INCRINIT_ROOT   2
86698
86699/*
86700** Forward reference required as the vdbeIncrMergeInit() and
86701** vdbePmaReaderIncrInit() routines are called mutually recursively when
86702** building a merge tree.
86703*/
86704static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
86705
86706/*
86707** Initialize the MergeEngine object passed as the second argument. Once this
86708** function returns, the first key of merged data may be read from the
86709** MergeEngine object in the usual fashion.
86710**
86711** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
86712** objects attached to the PmaReader objects that the merger reads from have
86713** already been populated, but that they have not yet populated aFile[0] and
86714** set the PmaReader objects up to read from it. In this case all that is
86715** required is to call vdbePmaReaderNext() on each PmaReader to point it at
86716** its first key.
86717**
86718** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
86719** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
86720** to pMerger.
86721**
86722** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86723*/
86724static int vdbeMergeEngineInit(
86725  SortSubtask *pTask,             /* Thread that will run pMerger */
86726  MergeEngine *pMerger,           /* MergeEngine to initialize */
86727  int eMode                       /* One of the INCRINIT_XXX constants */
86728){
86729  int rc = SQLITE_OK;             /* Return code */
86730  int i;                          /* For looping over PmaReader objects */
86731  int nTree = pMerger->nTree;
86732
86733  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86734  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86735
86736  /* Verify that the MergeEngine is assigned to a single thread */
86737  assert( pMerger->pTask==0 );
86738  pMerger->pTask = pTask;
86739
86740  for(i=0; i<nTree; i++){
86741    if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
86742      /* PmaReaders should be normally initialized in order, as if they are
86743      ** reading from the same temp file this makes for more linear file IO.
86744      ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
86745      ** in use it will block the vdbePmaReaderNext() call while it uses
86746      ** the main thread to fill its buffer. So calling PmaReaderNext()
86747      ** on this PmaReader before any of the multi-threaded PmaReaders takes
86748      ** better advantage of multi-processor hardware. */
86749      rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
86750    }else{
86751      rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
86752    }
86753    if( rc!=SQLITE_OK ) return rc;
86754  }
86755
86756  for(i=pMerger->nTree-1; i>0; i--){
86757    vdbeMergeEngineCompare(pMerger, i);
86758  }
86759  return pTask->pUnpacked->errCode;
86760}
86761
86762/*
86763** The PmaReader passed as the first argument is guaranteed to be an
86764** incremental-reader (pReadr->pIncr!=0). This function serves to open
86765** and/or initialize the temp file related fields of the IncrMerge
86766** object at (pReadr->pIncr).
86767**
86768** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
86769** in the sub-tree headed by pReadr are also initialized. Data is then
86770** loaded into the buffers belonging to pReadr and it is set to point to
86771** the first key in its range.
86772**
86773** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
86774** to be a multi-threaded PmaReader and this function is being called in a
86775** background thread. In this case all PmaReaders in the sub-tree are
86776** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
86777** pReadr is populated. However, pReadr itself is not set up to point
86778** to its first key. A call to vdbePmaReaderNext() is still required to do
86779** that.
86780**
86781** The reason this function does not call vdbePmaReaderNext() immediately
86782** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
86783** to block on thread (pTask->thread) before accessing aFile[1]. But, since
86784** this entire function is being run by thread (pTask->thread), that will
86785** lead to the current background thread attempting to join itself.
86786**
86787** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
86788** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
86789** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
86790** In this case vdbePmaReaderNext() is called on all child PmaReaders and
86791** the current PmaReader set to point to the first key in its range.
86792**
86793** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86794*/
86795static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
86796  int rc = SQLITE_OK;
86797  IncrMerger *pIncr = pReadr->pIncr;
86798  SortSubtask *pTask = pIncr->pTask;
86799  sqlite3 *db = pTask->pSorter->db;
86800
86801  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86802  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86803
86804  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
86805
86806  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
86807  ** requires two temp files to itself, whereas a single-threaded object
86808  ** only requires a region of pTask->file2. */
86809  if( rc==SQLITE_OK ){
86810    int mxSz = pIncr->mxSz;
86811#if SQLITE_MAX_WORKER_THREADS>0
86812    if( pIncr->bUseThread ){
86813      rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
86814      if( rc==SQLITE_OK ){
86815        rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
86816      }
86817    }else
86818#endif
86819    /*if( !pIncr->bUseThread )*/{
86820      if( pTask->file2.pFd==0 ){
86821        assert( pTask->file2.iEof>0 );
86822        rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
86823        pTask->file2.iEof = 0;
86824      }
86825      if( rc==SQLITE_OK ){
86826        pIncr->aFile[1].pFd = pTask->file2.pFd;
86827        pIncr->iStartOff = pTask->file2.iEof;
86828        pTask->file2.iEof += mxSz;
86829      }
86830    }
86831  }
86832
86833#if SQLITE_MAX_WORKER_THREADS>0
86834  if( rc==SQLITE_OK && pIncr->bUseThread ){
86835    /* Use the current thread to populate aFile[1], even though this
86836    ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
86837    ** then this function is already running in background thread
86838    ** pIncr->pTask->thread.
86839    **
86840    ** If this is the INCRINIT_ROOT object, then it is running in the
86841    ** main VDBE thread. But that is Ok, as that thread cannot return
86842    ** control to the VDBE or proceed with anything useful until the
86843    ** first results are ready from this merger object anyway.
86844    */
86845    assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
86846    rc = vdbeIncrPopulate(pIncr);
86847  }
86848#endif
86849
86850  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
86851    rc = vdbePmaReaderNext(pReadr);
86852  }
86853
86854  return rc;
86855}
86856
86857#if SQLITE_MAX_WORKER_THREADS>0
86858/*
86859** The main routine for vdbePmaReaderIncrMergeInit() operations run in
86860** background threads.
86861*/
86862static void *vdbePmaReaderBgIncrInit(void *pCtx){
86863  PmaReader *pReader = (PmaReader*)pCtx;
86864  void *pRet = SQLITE_INT_TO_PTR(
86865                  vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
86866               );
86867  pReader->pIncr->pTask->bDone = 1;
86868  return pRet;
86869}
86870#endif
86871
86872/*
86873** If the PmaReader passed as the first argument is not an incremental-reader
86874** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
86875** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
86876** this routine to initialize the incremental merge.
86877**
86878** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
86879** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
86880** Or, if the IncrMerger is single threaded, the same function is called
86881** using the current thread.
86882*/
86883static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
86884  IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
86885  int rc = SQLITE_OK;                  /* Return code */
86886  if( pIncr ){
86887#if SQLITE_MAX_WORKER_THREADS>0
86888    assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
86889    if( pIncr->bUseThread ){
86890      void *pCtx = (void*)pReadr;
86891      rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
86892    }else
86893#endif
86894    {
86895      rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
86896    }
86897  }
86898  return rc;
86899}
86900
86901/*
86902** Allocate a new MergeEngine object to merge the contents of nPMA level-0
86903** PMAs from pTask->file. If no error occurs, set *ppOut to point to
86904** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
86905** to NULL and return an SQLite error code.
86906**
86907** When this function is called, *piOffset is set to the offset of the
86908** first PMA to read from pTask->file. Assuming no error occurs, it is
86909** set to the offset immediately following the last byte of the last
86910** PMA before returning. If an error does occur, then the final value of
86911** *piOffset is undefined.
86912*/
86913static int vdbeMergeEngineLevel0(
86914  SortSubtask *pTask,             /* Sorter task to read from */
86915  int nPMA,                       /* Number of PMAs to read */
86916  i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
86917  MergeEngine **ppOut             /* OUT: New merge-engine */
86918){
86919  MergeEngine *pNew;              /* Merge engine to return */
86920  i64 iOff = *piOffset;
86921  int i;
86922  int rc = SQLITE_OK;
86923
86924  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
86925  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
86926
86927  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
86928    i64 nDummy = 0;
86929    PmaReader *pReadr = &pNew->aReadr[i];
86930    rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
86931    iOff = pReadr->iEof;
86932  }
86933
86934  if( rc!=SQLITE_OK ){
86935    vdbeMergeEngineFree(pNew);
86936    *ppOut = 0;
86937  }
86938  *piOffset = iOff;
86939  return rc;
86940}
86941
86942/*
86943** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
86944** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
86945**
86946** i.e.
86947**
86948**   nPMA<=16    -> TreeDepth() == 0
86949**   nPMA<=256   -> TreeDepth() == 1
86950**   nPMA<=65536 -> TreeDepth() == 2
86951*/
86952static int vdbeSorterTreeDepth(int nPMA){
86953  int nDepth = 0;
86954  i64 nDiv = SORTER_MAX_MERGE_COUNT;
86955  while( nDiv < (i64)nPMA ){
86956    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86957    nDepth++;
86958  }
86959  return nDepth;
86960}
86961
86962/*
86963** pRoot is the root of an incremental merge-tree with depth nDepth (according
86964** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
86965** tree, counting from zero. This function adds pLeaf to the tree.
86966**
86967** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
86968** code is returned and pLeaf is freed.
86969*/
86970static int vdbeSorterAddToTree(
86971  SortSubtask *pTask,             /* Task context */
86972  int nDepth,                     /* Depth of tree according to TreeDepth() */
86973  int iSeq,                       /* Sequence number of leaf within tree */
86974  MergeEngine *pRoot,             /* Root of tree */
86975  MergeEngine *pLeaf              /* Leaf to add to tree */
86976){
86977  int rc = SQLITE_OK;
86978  int nDiv = 1;
86979  int i;
86980  MergeEngine *p = pRoot;
86981  IncrMerger *pIncr;
86982
86983  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
86984
86985  for(i=1; i<nDepth; i++){
86986    nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86987  }
86988
86989  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
86990    int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
86991    PmaReader *pReadr = &p->aReadr[iIter];
86992
86993    if( pReadr->pIncr==0 ){
86994      MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
86995      if( pNew==0 ){
86996        rc = SQLITE_NOMEM_BKPT;
86997      }else{
86998        rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
86999      }
87000    }
87001    if( rc==SQLITE_OK ){
87002      p = pReadr->pIncr->pMerger;
87003      nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
87004    }
87005  }
87006
87007  if( rc==SQLITE_OK ){
87008    p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
87009  }else{
87010    vdbeIncrFree(pIncr);
87011  }
87012  return rc;
87013}
87014
87015/*
87016** This function is called as part of a SorterRewind() operation on a sorter
87017** that has already written two or more level-0 PMAs to one or more temp
87018** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
87019** can be used to incrementally merge all PMAs on disk.
87020**
87021** If successful, SQLITE_OK is returned and *ppOut set to point to the
87022** MergeEngine object at the root of the tree before returning. Or, if an
87023** error occurs, an SQLite error code is returned and the final value
87024** of *ppOut is undefined.
87025*/
87026static int vdbeSorterMergeTreeBuild(
87027  VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
87028  MergeEngine **ppOut        /* Write the MergeEngine here */
87029){
87030  MergeEngine *pMain = 0;
87031  int rc = SQLITE_OK;
87032  int iTask;
87033
87034#if SQLITE_MAX_WORKER_THREADS>0
87035  /* If the sorter uses more than one task, then create the top-level
87036  ** MergeEngine here. This MergeEngine will read data from exactly
87037  ** one PmaReader per sub-task.  */
87038  assert( pSorter->bUseThreads || pSorter->nTask==1 );
87039  if( pSorter->nTask>1 ){
87040    pMain = vdbeMergeEngineNew(pSorter->nTask);
87041    if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
87042  }
87043#endif
87044
87045  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87046    SortSubtask *pTask = &pSorter->aTask[iTask];
87047    assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
87048    if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
87049      MergeEngine *pRoot = 0;     /* Root node of tree for this task */
87050      int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
87051      i64 iReadOff = 0;
87052
87053      if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
87054        rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
87055      }else{
87056        int i;
87057        int iSeq = 0;
87058        pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
87059        if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
87060        for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
87061          MergeEngine *pMerger = 0; /* New level-0 PMA merger */
87062          int nReader;              /* Number of level-0 PMAs to merge */
87063
87064          nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
87065          rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
87066          if( rc==SQLITE_OK ){
87067            rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
87068          }
87069        }
87070      }
87071
87072      if( rc==SQLITE_OK ){
87073#if SQLITE_MAX_WORKER_THREADS>0
87074        if( pMain!=0 ){
87075          rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
87076        }else
87077#endif
87078        {
87079          assert( pMain==0 );
87080          pMain = pRoot;
87081        }
87082      }else{
87083        vdbeMergeEngineFree(pRoot);
87084      }
87085    }
87086  }
87087
87088  if( rc!=SQLITE_OK ){
87089    vdbeMergeEngineFree(pMain);
87090    pMain = 0;
87091  }
87092  *ppOut = pMain;
87093  return rc;
87094}
87095
87096/*
87097** This function is called as part of an sqlite3VdbeSorterRewind() operation
87098** on a sorter that has written two or more PMAs to temporary files. It sets
87099** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
87100** (for multi-threaded sorters) so that it can be used to iterate through
87101** all records stored in the sorter.
87102**
87103** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87104*/
87105static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
87106  int rc;                         /* Return code */
87107  SortSubtask *pTask0 = &pSorter->aTask[0];
87108  MergeEngine *pMain = 0;
87109#if SQLITE_MAX_WORKER_THREADS
87110  sqlite3 *db = pTask0->pSorter->db;
87111  int i;
87112  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
87113  for(i=0; i<pSorter->nTask; i++){
87114    pSorter->aTask[i].xCompare = xCompare;
87115  }
87116#endif
87117
87118  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
87119  if( rc==SQLITE_OK ){
87120#if SQLITE_MAX_WORKER_THREADS
87121    assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
87122    if( pSorter->bUseThreads ){
87123      int iTask;
87124      PmaReader *pReadr = 0;
87125      SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
87126      rc = vdbeSortAllocUnpacked(pLast);
87127      if( rc==SQLITE_OK ){
87128        pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
87129        pSorter->pReader = pReadr;
87130        if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
87131      }
87132      if( rc==SQLITE_OK ){
87133        rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
87134        if( rc==SQLITE_OK ){
87135          vdbeIncrMergerSetThreads(pReadr->pIncr);
87136          for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
87137            IncrMerger *pIncr;
87138            if( (pIncr = pMain->aReadr[iTask].pIncr) ){
87139              vdbeIncrMergerSetThreads(pIncr);
87140              assert( pIncr->pTask!=pLast );
87141            }
87142          }
87143          for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87144            /* Check that:
87145            **
87146            **   a) The incremental merge object is configured to use the
87147            **      right task, and
87148            **   b) If it is using task (nTask-1), it is configured to run
87149            **      in single-threaded mode. This is important, as the
87150            **      root merge (INCRINIT_ROOT) will be using the same task
87151            **      object.
87152            */
87153            PmaReader *p = &pMain->aReadr[iTask];
87154            assert( p->pIncr==0 || (
87155                (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
87156             && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
87157            ));
87158            rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
87159          }
87160        }
87161        pMain = 0;
87162      }
87163      if( rc==SQLITE_OK ){
87164        rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
87165      }
87166    }else
87167#endif
87168    {
87169      rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
87170      pSorter->pMerger = pMain;
87171      pMain = 0;
87172    }
87173  }
87174
87175  if( rc!=SQLITE_OK ){
87176    vdbeMergeEngineFree(pMain);
87177  }
87178  return rc;
87179}
87180
87181
87182/*
87183** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
87184** this function is called to prepare for iterating through the records
87185** in sorted order.
87186*/
87187SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
87188  VdbeSorter *pSorter;
87189  int rc = SQLITE_OK;             /* Return code */
87190
87191  assert( pCsr->eCurType==CURTYPE_SORTER );
87192  pSorter = pCsr->uc.pSorter;
87193  assert( pSorter );
87194
87195  /* If no data has been written to disk, then do not do so now. Instead,
87196  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
87197  ** from the in-memory list.  */
87198  if( pSorter->bUsePMA==0 ){
87199    if( pSorter->list.pList ){
87200      *pbEof = 0;
87201      rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
87202    }else{
87203      *pbEof = 1;
87204    }
87205    return rc;
87206  }
87207
87208  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
87209  ** function flushes the contents of memory to disk, it immediately always
87210  ** creates a new list consisting of a single key immediately afterwards.
87211  ** So the list is never empty at this point.  */
87212  assert( pSorter->list.pList );
87213  rc = vdbeSorterFlushPMA(pSorter);
87214
87215  /* Join all threads */
87216  rc = vdbeSorterJoinAll(pSorter, rc);
87217
87218  vdbeSorterRewindDebug("rewind");
87219
87220  /* Assuming no errors have occurred, set up a merger structure to
87221  ** incrementally read and merge all remaining PMAs.  */
87222  assert( pSorter->pReader==0 );
87223  if( rc==SQLITE_OK ){
87224    rc = vdbeSorterSetupMerge(pSorter);
87225    *pbEof = 0;
87226  }
87227
87228  vdbeSorterRewindDebug("rewinddone");
87229  return rc;
87230}
87231
87232/*
87233** Advance to the next element in the sorter.
87234*/
87235SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
87236  VdbeSorter *pSorter;
87237  int rc;                         /* Return code */
87238
87239  assert( pCsr->eCurType==CURTYPE_SORTER );
87240  pSorter = pCsr->uc.pSorter;
87241  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
87242  if( pSorter->bUsePMA ){
87243    assert( pSorter->pReader==0 || pSorter->pMerger==0 );
87244    assert( pSorter->bUseThreads==0 || pSorter->pReader );
87245    assert( pSorter->bUseThreads==1 || pSorter->pMerger );
87246#if SQLITE_MAX_WORKER_THREADS>0
87247    if( pSorter->bUseThreads ){
87248      rc = vdbePmaReaderNext(pSorter->pReader);
87249      *pbEof = (pSorter->pReader->pFd==0);
87250    }else
87251#endif
87252    /*if( !pSorter->bUseThreads )*/ {
87253      assert( pSorter->pMerger!=0 );
87254      assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
87255      rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
87256    }
87257  }else{
87258    SorterRecord *pFree = pSorter->list.pList;
87259    pSorter->list.pList = pFree->u.pNext;
87260    pFree->u.pNext = 0;
87261    if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
87262    *pbEof = !pSorter->list.pList;
87263    rc = SQLITE_OK;
87264  }
87265  return rc;
87266}
87267
87268/*
87269** Return a pointer to a buffer owned by the sorter that contains the
87270** current key.
87271*/
87272static void *vdbeSorterRowkey(
87273  const VdbeSorter *pSorter,      /* Sorter object */
87274  int *pnKey                      /* OUT: Size of current key in bytes */
87275){
87276  void *pKey;
87277  if( pSorter->bUsePMA ){
87278    PmaReader *pReader;
87279#if SQLITE_MAX_WORKER_THREADS>0
87280    if( pSorter->bUseThreads ){
87281      pReader = pSorter->pReader;
87282    }else
87283#endif
87284    /*if( !pSorter->bUseThreads )*/{
87285      pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
87286    }
87287    *pnKey = pReader->nKey;
87288    pKey = pReader->aKey;
87289  }else{
87290    *pnKey = pSorter->list.pList->nVal;
87291    pKey = SRVAL(pSorter->list.pList);
87292  }
87293  return pKey;
87294}
87295
87296/*
87297** Copy the current sorter key into the memory cell pOut.
87298*/
87299SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
87300  VdbeSorter *pSorter;
87301  void *pKey; int nKey;           /* Sorter key to copy into pOut */
87302
87303  assert( pCsr->eCurType==CURTYPE_SORTER );
87304  pSorter = pCsr->uc.pSorter;
87305  pKey = vdbeSorterRowkey(pSorter, &nKey);
87306  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
87307    return SQLITE_NOMEM_BKPT;
87308  }
87309  pOut->n = nKey;
87310  MemSetTypeFlag(pOut, MEM_Blob);
87311  memcpy(pOut->z, pKey, nKey);
87312
87313  return SQLITE_OK;
87314}
87315
87316/*
87317** Compare the key in memory cell pVal with the key that the sorter cursor
87318** passed as the first argument currently points to. For the purposes of
87319** the comparison, ignore the rowid field at the end of each record.
87320**
87321** If the sorter cursor key contains any NULL values, consider it to be
87322** less than pVal. Even if pVal also contains NULL values.
87323**
87324** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
87325** Otherwise, set *pRes to a negative, zero or positive value if the
87326** key in pVal is smaller than, equal to or larger than the current sorter
87327** key.
87328**
87329** This routine forms the core of the OP_SorterCompare opcode, which in
87330** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
87331*/
87332SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
87333  const VdbeCursor *pCsr,         /* Sorter cursor */
87334  Mem *pVal,                      /* Value to compare to current sorter key */
87335  int nKeyCol,                    /* Compare this many columns */
87336  int *pRes                       /* OUT: Result of comparison */
87337){
87338  VdbeSorter *pSorter;
87339  UnpackedRecord *r2;
87340  KeyInfo *pKeyInfo;
87341  int i;
87342  void *pKey; int nKey;           /* Sorter key to compare pVal with */
87343
87344  assert( pCsr->eCurType==CURTYPE_SORTER );
87345  pSorter = pCsr->uc.pSorter;
87346  r2 = pSorter->pUnpacked;
87347  pKeyInfo = pCsr->pKeyInfo;
87348  if( r2==0 ){
87349    char *p;
87350    r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
87351    assert( pSorter->pUnpacked==(UnpackedRecord*)p );
87352    if( r2==0 ) return SQLITE_NOMEM_BKPT;
87353    r2->nField = nKeyCol;
87354  }
87355  assert( r2->nField==nKeyCol );
87356
87357  pKey = vdbeSorterRowkey(pSorter, &nKey);
87358  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
87359  for(i=0; i<nKeyCol; i++){
87360    if( r2->aMem[i].flags & MEM_Null ){
87361      *pRes = -1;
87362      return SQLITE_OK;
87363    }
87364  }
87365
87366  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
87367  return SQLITE_OK;
87368}
87369
87370/************** End of vdbesort.c ********************************************/
87371/************** Begin file memjournal.c **************************************/
87372/*
87373** 2008 October 7
87374**
87375** The author disclaims copyright to this source code.  In place of
87376** a legal notice, here is a blessing:
87377**
87378**    May you do good and not evil.
87379**    May you find forgiveness for yourself and forgive others.
87380**    May you share freely, never taking more than you give.
87381**
87382*************************************************************************
87383**
87384** This file contains code use to implement an in-memory rollback journal.
87385** The in-memory rollback journal is used to journal transactions for
87386** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
87387**
87388** Update:  The in-memory journal is also used to temporarily cache
87389** smaller journals that are not critical for power-loss recovery.
87390** For example, statement journals that are not too big will be held
87391** entirely in memory, thus reducing the number of file I/O calls, and
87392** more importantly, reducing temporary file creation events.  If these
87393** journals become too large for memory, they are spilled to disk.  But
87394** in the common case, they are usually small and no file I/O needs to
87395** occur.
87396*/
87397/* #include "sqliteInt.h" */
87398
87399/* Forward references to internal structures */
87400typedef struct MemJournal MemJournal;
87401typedef struct FilePoint FilePoint;
87402typedef struct FileChunk FileChunk;
87403
87404/*
87405** The rollback journal is composed of a linked list of these structures.
87406**
87407** The zChunk array is always at least 8 bytes in size - usually much more.
87408** Its actual size is stored in the MemJournal.nChunkSize variable.
87409*/
87410struct FileChunk {
87411  FileChunk *pNext;               /* Next chunk in the journal */
87412  u8 zChunk[8];                   /* Content of this chunk */
87413};
87414
87415/*
87416** By default, allocate this many bytes of memory for each FileChunk object.
87417*/
87418#define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
87419
87420/*
87421** For chunk size nChunkSize, return the number of bytes that should
87422** be allocated for each FileChunk structure.
87423*/
87424#define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
87425
87426/*
87427** An instance of this object serves as a cursor into the rollback journal.
87428** The cursor can be either for reading or writing.
87429*/
87430struct FilePoint {
87431  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
87432  FileChunk *pChunk;              /* Specific chunk into which cursor points */
87433};
87434
87435/*
87436** This structure is a subclass of sqlite3_file. Each open memory-journal
87437** is an instance of this class.
87438*/
87439struct MemJournal {
87440  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
87441  int nChunkSize;                 /* In-memory chunk-size */
87442
87443  int nSpill;                     /* Bytes of data before flushing */
87444  int nSize;                      /* Bytes of data currently in memory */
87445  FileChunk *pFirst;              /* Head of in-memory chunk-list */
87446  FilePoint endpoint;             /* Pointer to the end of the file */
87447  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
87448
87449  int flags;                      /* xOpen flags */
87450  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
87451  const char *zJournal;           /* Name of the journal file */
87452};
87453
87454/*
87455** Read data from the in-memory journal file.  This is the implementation
87456** of the sqlite3_vfs.xRead method.
87457*/
87458static int memjrnlRead(
87459  sqlite3_file *pJfd,    /* The journal file from which to read */
87460  void *zBuf,            /* Put the results here */
87461  int iAmt,              /* Number of bytes to read */
87462  sqlite_int64 iOfst     /* Begin reading at this offset */
87463){
87464  MemJournal *p = (MemJournal *)pJfd;
87465  u8 *zOut = zBuf;
87466  int nRead = iAmt;
87467  int iChunkOffset;
87468  FileChunk *pChunk;
87469
87470#ifdef SQLITE_ENABLE_ATOMIC_WRITE
87471  if( (iAmt+iOfst)>p->endpoint.iOffset ){
87472    return SQLITE_IOERR_SHORT_READ;
87473  }
87474#endif
87475
87476  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
87477  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
87478  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
87479    sqlite3_int64 iOff = 0;
87480    for(pChunk=p->pFirst;
87481        ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
87482        pChunk=pChunk->pNext
87483    ){
87484      iOff += p->nChunkSize;
87485    }
87486  }else{
87487    pChunk = p->readpoint.pChunk;
87488    assert( pChunk!=0 );
87489  }
87490
87491  iChunkOffset = (int)(iOfst%p->nChunkSize);
87492  do {
87493    int iSpace = p->nChunkSize - iChunkOffset;
87494    int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
87495    memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
87496    zOut += nCopy;
87497    nRead -= iSpace;
87498    iChunkOffset = 0;
87499  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
87500  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
87501  p->readpoint.pChunk = pChunk;
87502
87503  return SQLITE_OK;
87504}
87505
87506/*
87507** Free the list of FileChunk structures headed at MemJournal.pFirst.
87508*/
87509static void memjrnlFreeChunks(MemJournal *p){
87510  FileChunk *pIter;
87511  FileChunk *pNext;
87512  for(pIter=p->pFirst; pIter; pIter=pNext){
87513    pNext = pIter->pNext;
87514    sqlite3_free(pIter);
87515  }
87516  p->pFirst = 0;
87517}
87518
87519/*
87520** Flush the contents of memory to a real file on disk.
87521*/
87522static int memjrnlCreateFile(MemJournal *p){
87523  int rc;
87524  sqlite3_file *pReal = (sqlite3_file*)p;
87525  MemJournal copy = *p;
87526
87527  memset(p, 0, sizeof(MemJournal));
87528  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
87529  if( rc==SQLITE_OK ){
87530    int nChunk = copy.nChunkSize;
87531    i64 iOff = 0;
87532    FileChunk *pIter;
87533    for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
87534      if( iOff + nChunk > copy.endpoint.iOffset ){
87535        nChunk = copy.endpoint.iOffset - iOff;
87536      }
87537      rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
87538      if( rc ) break;
87539      iOff += nChunk;
87540    }
87541    if( rc==SQLITE_OK ){
87542      /* No error has occurred. Free the in-memory buffers. */
87543      memjrnlFreeChunks(&copy);
87544    }
87545  }
87546  if( rc!=SQLITE_OK ){
87547    /* If an error occurred while creating or writing to the file, restore
87548    ** the original before returning. This way, SQLite uses the in-memory
87549    ** journal data to roll back changes made to the internal page-cache
87550    ** before this function was called.  */
87551    sqlite3OsClose(pReal);
87552    *p = copy;
87553  }
87554  return rc;
87555}
87556
87557
87558/*
87559** Write data to the file.
87560*/
87561static int memjrnlWrite(
87562  sqlite3_file *pJfd,    /* The journal file into which to write */
87563  const void *zBuf,      /* Take data to be written from here */
87564  int iAmt,              /* Number of bytes to write */
87565  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
87566){
87567  MemJournal *p = (MemJournal *)pJfd;
87568  int nWrite = iAmt;
87569  u8 *zWrite = (u8 *)zBuf;
87570
87571  /* If the file should be created now, create it and write the new data
87572  ** into the file on disk. */
87573  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
87574    int rc = memjrnlCreateFile(p);
87575    if( rc==SQLITE_OK ){
87576      rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
87577    }
87578    return rc;
87579  }
87580
87581  /* If the contents of this write should be stored in memory */
87582  else{
87583    /* An in-memory journal file should only ever be appended to. Random
87584    ** access writes are not required. The only exception to this is when
87585    ** the in-memory journal is being used by a connection using the
87586    ** atomic-write optimization. In this case the first 28 bytes of the
87587    ** journal file may be written as part of committing the transaction. */
87588    assert( iOfst==p->endpoint.iOffset || iOfst==0 );
87589#ifdef SQLITE_ENABLE_ATOMIC_WRITE
87590    if( iOfst==0 && p->pFirst ){
87591      assert( p->nChunkSize>iAmt );
87592      memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
87593    }else
87594#else
87595    assert( iOfst>0 || p->pFirst==0 );
87596#endif
87597    {
87598      while( nWrite>0 ){
87599        FileChunk *pChunk = p->endpoint.pChunk;
87600        int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
87601        int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
87602
87603        if( iChunkOffset==0 ){
87604          /* New chunk is required to extend the file. */
87605          FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
87606          if( !pNew ){
87607            return SQLITE_IOERR_NOMEM_BKPT;
87608          }
87609          pNew->pNext = 0;
87610          if( pChunk ){
87611            assert( p->pFirst );
87612            pChunk->pNext = pNew;
87613          }else{
87614            assert( !p->pFirst );
87615            p->pFirst = pNew;
87616          }
87617          p->endpoint.pChunk = pNew;
87618        }
87619
87620        memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
87621        zWrite += iSpace;
87622        nWrite -= iSpace;
87623        p->endpoint.iOffset += iSpace;
87624      }
87625      p->nSize = iAmt + iOfst;
87626    }
87627  }
87628
87629  return SQLITE_OK;
87630}
87631
87632/*
87633** Truncate the file.
87634**
87635** If the journal file is already on disk, truncate it there. Or, if it
87636** is still in main memory but is being truncated to zero bytes in size,
87637** ignore
87638*/
87639static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
87640  MemJournal *p = (MemJournal *)pJfd;
87641  if( ALWAYS(size==0) ){
87642    memjrnlFreeChunks(p);
87643    p->nSize = 0;
87644    p->endpoint.pChunk = 0;
87645    p->endpoint.iOffset = 0;
87646    p->readpoint.pChunk = 0;
87647    p->readpoint.iOffset = 0;
87648  }
87649  return SQLITE_OK;
87650}
87651
87652/*
87653** Close the file.
87654*/
87655static int memjrnlClose(sqlite3_file *pJfd){
87656  MemJournal *p = (MemJournal *)pJfd;
87657  memjrnlFreeChunks(p);
87658  return SQLITE_OK;
87659}
87660
87661/*
87662** Sync the file.
87663**
87664** If the real file has been created, call its xSync method. Otherwise,
87665** syncing an in-memory journal is a no-op.
87666*/
87667static int memjrnlSync(sqlite3_file *pJfd, int flags){
87668  UNUSED_PARAMETER2(pJfd, flags);
87669  return SQLITE_OK;
87670}
87671
87672/*
87673** Query the size of the file in bytes.
87674*/
87675static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
87676  MemJournal *p = (MemJournal *)pJfd;
87677  *pSize = (sqlite_int64) p->endpoint.iOffset;
87678  return SQLITE_OK;
87679}
87680
87681/*
87682** Table of methods for MemJournal sqlite3_file object.
87683*/
87684static const struct sqlite3_io_methods MemJournalMethods = {
87685  1,                /* iVersion */
87686  memjrnlClose,     /* xClose */
87687  memjrnlRead,      /* xRead */
87688  memjrnlWrite,     /* xWrite */
87689  memjrnlTruncate,  /* xTruncate */
87690  memjrnlSync,      /* xSync */
87691  memjrnlFileSize,  /* xFileSize */
87692  0,                /* xLock */
87693  0,                /* xUnlock */
87694  0,                /* xCheckReservedLock */
87695  0,                /* xFileControl */
87696  0,                /* xSectorSize */
87697  0,                /* xDeviceCharacteristics */
87698  0,                /* xShmMap */
87699  0,                /* xShmLock */
87700  0,                /* xShmBarrier */
87701  0,                /* xShmUnmap */
87702  0,                /* xFetch */
87703  0                 /* xUnfetch */
87704};
87705
87706/*
87707** Open a journal file.
87708**
87709** The behaviour of the journal file depends on the value of parameter
87710** nSpill. If nSpill is 0, then the journal file is always create and
87711** accessed using the underlying VFS. If nSpill is less than zero, then
87712** all content is always stored in main-memory. Finally, if nSpill is a
87713** positive value, then the journal file is initially created in-memory
87714** but may be flushed to disk later on. In this case the journal file is
87715** flushed to disk either when it grows larger than nSpill bytes in size,
87716** or when sqlite3JournalCreate() is called.
87717*/
87718SQLITE_PRIVATE int sqlite3JournalOpen(
87719  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
87720  const char *zName,         /* Name of the journal file */
87721  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
87722  int flags,                 /* Opening flags */
87723  int nSpill                 /* Bytes buffered before opening the file */
87724){
87725  MemJournal *p = (MemJournal*)pJfd;
87726
87727  /* Zero the file-handle object. If nSpill was passed zero, initialize
87728  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
87729  ** case none of the code in this module is executed as a result of calls
87730  ** made on the journal file-handle.  */
87731  memset(p, 0, sizeof(MemJournal));
87732  if( nSpill==0 ){
87733    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
87734  }
87735
87736  if( nSpill>0 ){
87737    p->nChunkSize = nSpill;
87738  }else{
87739    p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
87740    assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
87741  }
87742
87743  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
87744  p->nSpill = nSpill;
87745  p->flags = flags;
87746  p->zJournal = zName;
87747  p->pVfs = pVfs;
87748  return SQLITE_OK;
87749}
87750
87751/*
87752** Open an in-memory journal file.
87753*/
87754SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
87755  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
87756}
87757
87758#ifdef SQLITE_ENABLE_ATOMIC_WRITE
87759/*
87760** If the argument p points to a MemJournal structure that is not an
87761** in-memory-only journal file (i.e. is one that was opened with a +ve
87762** nSpill parameter), and the underlying file has not yet been created,
87763** create it now.
87764*/
87765SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
87766  int rc = SQLITE_OK;
87767  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
87768    rc = memjrnlCreateFile((MemJournal*)p);
87769  }
87770  return rc;
87771}
87772#endif
87773
87774/*
87775** The file-handle passed as the only argument is open on a journal file.
87776** Return true if this "journal file" is currently stored in heap memory,
87777** or false otherwise.
87778*/
87779SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
87780  return p->pMethods==&MemJournalMethods;
87781}
87782
87783/*
87784** Return the number of bytes required to store a JournalFile that uses vfs
87785** pVfs to create the underlying on-disk files.
87786*/
87787SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
87788  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
87789}
87790
87791/************** End of memjournal.c ******************************************/
87792/************** Begin file walker.c ******************************************/
87793/*
87794** 2008 August 16
87795**
87796** The author disclaims copyright to this source code.  In place of
87797** a legal notice, here is a blessing:
87798**
87799**    May you do good and not evil.
87800**    May you find forgiveness for yourself and forgive others.
87801**    May you share freely, never taking more than you give.
87802**
87803*************************************************************************
87804** This file contains routines used for walking the parser tree for
87805** an SQL statement.
87806*/
87807/* #include "sqliteInt.h" */
87808/* #include <stdlib.h> */
87809/* #include <string.h> */
87810
87811
87812/*
87813** Walk an expression tree.  Invoke the callback once for each node
87814** of the expression, while descending.  (In other words, the callback
87815** is invoked before visiting children.)
87816**
87817** The return value from the callback should be one of the WRC_*
87818** constants to specify how to proceed with the walk.
87819**
87820**    WRC_Continue      Continue descending down the tree.
87821**
87822**    WRC_Prune         Do not descend into child nodes.  But allow
87823**                      the walk to continue with sibling nodes.
87824**
87825**    WRC_Abort         Do no more callbacks.  Unwind the stack and
87826**                      return the top-level walk call.
87827**
87828** The return value from this routine is WRC_Abort to abandon the tree walk
87829** and WRC_Continue to continue.
87830*/
87831static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
87832  int rc;
87833  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
87834  testcase( ExprHasProperty(pExpr, EP_Reduced) );
87835  rc = pWalker->xExprCallback(pWalker, pExpr);
87836  if( rc==WRC_Continue
87837              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
87838    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
87839    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
87840    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87841      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
87842    }else{
87843      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
87844    }
87845  }
87846  return rc & WRC_Abort;
87847}
87848SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
87849  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
87850}
87851
87852/*
87853** Call sqlite3WalkExpr() for every expression in list p or until
87854** an abort request is seen.
87855*/
87856SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
87857  int i;
87858  struct ExprList_item *pItem;
87859  if( p ){
87860    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
87861      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
87862    }
87863  }
87864  return WRC_Continue;
87865}
87866
87867/*
87868** Walk all expressions associated with SELECT statement p.  Do
87869** not invoke the SELECT callback on p, but do (of course) invoke
87870** any expr callbacks and SELECT callbacks that come from subqueries.
87871** Return WRC_Abort or WRC_Continue.
87872*/
87873SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
87874  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
87875  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
87876  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
87877  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
87878  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
87879  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
87880  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
87881  return WRC_Continue;
87882}
87883
87884/*
87885** Walk the parse trees associated with all subqueries in the
87886** FROM clause of SELECT statement p.  Do not invoke the select
87887** callback on p, but do invoke it on each FROM clause subquery
87888** and on any subqueries further down in the tree.  Return
87889** WRC_Abort or WRC_Continue;
87890*/
87891SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
87892  SrcList *pSrc;
87893  int i;
87894  struct SrcList_item *pItem;
87895
87896  pSrc = p->pSrc;
87897  if( ALWAYS(pSrc) ){
87898    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
87899      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
87900        return WRC_Abort;
87901      }
87902      if( pItem->fg.isTabFunc
87903       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
87904      ){
87905        return WRC_Abort;
87906      }
87907    }
87908  }
87909  return WRC_Continue;
87910}
87911
87912/*
87913** Call sqlite3WalkExpr() for every expression in Select statement p.
87914** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
87915** on the compound select chain, p->pPrior.
87916**
87917** If it is not NULL, the xSelectCallback() callback is invoked before
87918** the walk of the expressions and FROM clause. The xSelectCallback2()
87919** method, if it is not NULL, is invoked following the walk of the
87920** expressions and FROM clause.
87921**
87922** Return WRC_Continue under normal conditions.  Return WRC_Abort if
87923** there is an abort request.
87924**
87925** If the Walker does not have an xSelectCallback() then this routine
87926** is a no-op returning WRC_Continue.
87927*/
87928SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
87929  int rc;
87930  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
87931    return WRC_Continue;
87932  }
87933  rc = WRC_Continue;
87934  pWalker->walkerDepth++;
87935  while( p ){
87936    if( pWalker->xSelectCallback ){
87937       rc = pWalker->xSelectCallback(pWalker, p);
87938       if( rc ) break;
87939    }
87940    if( sqlite3WalkSelectExpr(pWalker, p)
87941     || sqlite3WalkSelectFrom(pWalker, p)
87942    ){
87943      pWalker->walkerDepth--;
87944      return WRC_Abort;
87945    }
87946    if( pWalker->xSelectCallback2 ){
87947      pWalker->xSelectCallback2(pWalker, p);
87948    }
87949    p = p->pPrior;
87950  }
87951  pWalker->walkerDepth--;
87952  return rc & WRC_Abort;
87953}
87954
87955/************** End of walker.c **********************************************/
87956/************** Begin file resolve.c *****************************************/
87957/*
87958** 2008 August 18
87959**
87960** The author disclaims copyright to this source code.  In place of
87961** a legal notice, here is a blessing:
87962**
87963**    May you do good and not evil.
87964**    May you find forgiveness for yourself and forgive others.
87965**    May you share freely, never taking more than you give.
87966**
87967*************************************************************************
87968**
87969** This file contains routines used for walking the parser tree and
87970** resolve all identifiers by associating them with a particular
87971** table and column.
87972*/
87973/* #include "sqliteInt.h" */
87974/* #include <stdlib.h> */
87975/* #include <string.h> */
87976
87977/*
87978** Walk the expression tree pExpr and increase the aggregate function
87979** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
87980** This needs to occur when copying a TK_AGG_FUNCTION node from an
87981** outer query into an inner subquery.
87982**
87983** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
87984** is a helper function - a callback for the tree walker.
87985*/
87986static int incrAggDepth(Walker *pWalker, Expr *pExpr){
87987  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
87988  return WRC_Continue;
87989}
87990static void incrAggFunctionDepth(Expr *pExpr, int N){
87991  if( N>0 ){
87992    Walker w;
87993    memset(&w, 0, sizeof(w));
87994    w.xExprCallback = incrAggDepth;
87995    w.u.n = N;
87996    sqlite3WalkExpr(&w, pExpr);
87997  }
87998}
87999
88000/*
88001** Turn the pExpr expression into an alias for the iCol-th column of the
88002** result set in pEList.
88003**
88004** If the reference is followed by a COLLATE operator, then make sure
88005** the COLLATE operator is preserved.  For example:
88006**
88007**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
88008**
88009** Should be transformed into:
88010**
88011**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
88012**
88013** The nSubquery parameter specifies how many levels of subquery the
88014** alias is removed from the original expression.  The usual value is
88015** zero but it might be more if the alias is contained within a subquery
88016** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
88017** structures must be increased by the nSubquery amount.
88018*/
88019static void resolveAlias(
88020  Parse *pParse,         /* Parsing context */
88021  ExprList *pEList,      /* A result set */
88022  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
88023  Expr *pExpr,           /* Transform this into an alias to the result set */
88024  const char *zType,     /* "GROUP" or "ORDER" or "" */
88025  int nSubquery          /* Number of subqueries that the label is moving */
88026){
88027  Expr *pOrig;           /* The iCol-th column of the result set */
88028  Expr *pDup;            /* Copy of pOrig */
88029  sqlite3 *db;           /* The database connection */
88030
88031  assert( iCol>=0 && iCol<pEList->nExpr );
88032  pOrig = pEList->a[iCol].pExpr;
88033  assert( pOrig!=0 );
88034  db = pParse->db;
88035  pDup = sqlite3ExprDup(db, pOrig, 0);
88036  if( pDup==0 ) return;
88037  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
88038  if( pExpr->op==TK_COLLATE ){
88039    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
88040  }
88041  ExprSetProperty(pDup, EP_Alias);
88042
88043  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
88044  ** prevents ExprDelete() from deleting the Expr structure itself,
88045  ** allowing it to be repopulated by the memcpy() on the following line.
88046  ** The pExpr->u.zToken might point into memory that will be freed by the
88047  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
88048  ** make a copy of the token before doing the sqlite3DbFree().
88049  */
88050  ExprSetProperty(pExpr, EP_Static);
88051  sqlite3ExprDelete(db, pExpr);
88052  memcpy(pExpr, pDup, sizeof(*pExpr));
88053  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
88054    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
88055    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
88056    pExpr->flags |= EP_MemToken;
88057  }
88058  sqlite3DbFree(db, pDup);
88059}
88060
88061
88062/*
88063** Return TRUE if the name zCol occurs anywhere in the USING clause.
88064**
88065** Return FALSE if the USING clause is NULL or if it does not contain
88066** zCol.
88067*/
88068static int nameInUsingClause(IdList *pUsing, const char *zCol){
88069  if( pUsing ){
88070    int k;
88071    for(k=0; k<pUsing->nId; k++){
88072      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
88073    }
88074  }
88075  return 0;
88076}
88077
88078/*
88079** Subqueries stores the original database, table and column names for their
88080** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
88081** Check to see if the zSpan given to this routine matches the zDb, zTab,
88082** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
88083** match anything.
88084*/
88085SQLITE_PRIVATE int sqlite3MatchSpanName(
88086  const char *zSpan,
88087  const char *zCol,
88088  const char *zTab,
88089  const char *zDb
88090){
88091  int n;
88092  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88093  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
88094    return 0;
88095  }
88096  zSpan += n+1;
88097  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88098  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
88099    return 0;
88100  }
88101  zSpan += n+1;
88102  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
88103    return 0;
88104  }
88105  return 1;
88106}
88107
88108/*
88109** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
88110** that name in the set of source tables in pSrcList and make the pExpr
88111** expression node refer back to that source column.  The following changes
88112** are made to pExpr:
88113**
88114**    pExpr->iDb           Set the index in db->aDb[] of the database X
88115**                         (even if X is implied).
88116**    pExpr->iTable        Set to the cursor number for the table obtained
88117**                         from pSrcList.
88118**    pExpr->pTab          Points to the Table structure of X.Y (even if
88119**                         X and/or Y are implied.)
88120**    pExpr->iColumn       Set to the column number within the table.
88121**    pExpr->op            Set to TK_COLUMN.
88122**    pExpr->pLeft         Any expression this points to is deleted
88123**    pExpr->pRight        Any expression this points to is deleted.
88124**
88125** The zDb variable is the name of the database (the "X").  This value may be
88126** NULL meaning that name is of the form Y.Z or Z.  Any available database
88127** can be used.  The zTable variable is the name of the table (the "Y").  This
88128** value can be NULL if zDb is also NULL.  If zTable is NULL it
88129** means that the form of the name is Z and that columns from any table
88130** can be used.
88131**
88132** If the name cannot be resolved unambiguously, leave an error message
88133** in pParse and return WRC_Abort.  Return WRC_Prune on success.
88134*/
88135static int lookupName(
88136  Parse *pParse,       /* The parsing context */
88137  const char *zDb,     /* Name of the database containing table, or NULL */
88138  const char *zTab,    /* Name of table containing column, or NULL */
88139  const char *zCol,    /* Name of the column. */
88140  NameContext *pNC,    /* The name context used to resolve the name */
88141  Expr *pExpr          /* Make this EXPR node point to the selected column */
88142){
88143  int i, j;                         /* Loop counters */
88144  int cnt = 0;                      /* Number of matching column names */
88145  int cntTab = 0;                   /* Number of matching table names */
88146  int nSubquery = 0;                /* How many levels of subquery */
88147  sqlite3 *db = pParse->db;         /* The database connection */
88148  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
88149  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
88150  NameContext *pTopNC = pNC;        /* First namecontext in the list */
88151  Schema *pSchema = 0;              /* Schema of the expression */
88152  int isTrigger = 0;                /* True if resolved to a trigger column */
88153  Table *pTab = 0;                  /* Table hold the row */
88154  Column *pCol;                     /* A column of pTab */
88155
88156  assert( pNC );     /* the name context cannot be NULL. */
88157  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
88158  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88159
88160  /* Initialize the node to no-match */
88161  pExpr->iTable = -1;
88162  pExpr->pTab = 0;
88163  ExprSetVVAProperty(pExpr, EP_NoReduce);
88164
88165  /* Translate the schema name in zDb into a pointer to the corresponding
88166  ** schema.  If not found, pSchema will remain NULL and nothing will match
88167  ** resulting in an appropriate error message toward the end of this routine
88168  */
88169  if( zDb ){
88170    testcase( pNC->ncFlags & NC_PartIdx );
88171    testcase( pNC->ncFlags & NC_IsCheck );
88172    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
88173      /* Silently ignore database qualifiers inside CHECK constraints and
88174      ** partial indices.  Do not raise errors because that might break
88175      ** legacy and because it does not hurt anything to just ignore the
88176      ** database name. */
88177      zDb = 0;
88178    }else{
88179      for(i=0; i<db->nDb; i++){
88180        assert( db->aDb[i].zName );
88181        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
88182          pSchema = db->aDb[i].pSchema;
88183          break;
88184        }
88185      }
88186    }
88187  }
88188
88189  /* Start at the inner-most context and move outward until a match is found */
88190  while( pNC && cnt==0 ){
88191    ExprList *pEList;
88192    SrcList *pSrcList = pNC->pSrcList;
88193
88194    if( pSrcList ){
88195      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
88196        pTab = pItem->pTab;
88197        assert( pTab!=0 && pTab->zName!=0 );
88198        assert( pTab->nCol>0 );
88199        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
88200          int hit = 0;
88201          pEList = pItem->pSelect->pEList;
88202          for(j=0; j<pEList->nExpr; j++){
88203            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
88204              cnt++;
88205              cntTab = 2;
88206              pMatch = pItem;
88207              pExpr->iColumn = j;
88208              hit = 1;
88209            }
88210          }
88211          if( hit || zTab==0 ) continue;
88212        }
88213        if( zDb && pTab->pSchema!=pSchema ){
88214          continue;
88215        }
88216        if( zTab ){
88217          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
88218          assert( zTabName!=0 );
88219          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
88220            continue;
88221          }
88222        }
88223        if( 0==(cntTab++) ){
88224          pMatch = pItem;
88225        }
88226        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
88227          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88228            /* If there has been exactly one prior match and this match
88229            ** is for the right-hand table of a NATURAL JOIN or is in a
88230            ** USING clause, then skip this match.
88231            */
88232            if( cnt==1 ){
88233              if( pItem->fg.jointype & JT_NATURAL ) continue;
88234              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
88235            }
88236            cnt++;
88237            pMatch = pItem;
88238            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
88239            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
88240            break;
88241          }
88242        }
88243      }
88244      if( pMatch ){
88245        pExpr->iTable = pMatch->iCursor;
88246        pExpr->pTab = pMatch->pTab;
88247        /* RIGHT JOIN not (yet) supported */
88248        assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
88249        if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
88250          ExprSetProperty(pExpr, EP_CanBeNull);
88251        }
88252        pSchema = pExpr->pTab->pSchema;
88253      }
88254    } /* if( pSrcList ) */
88255
88256#ifndef SQLITE_OMIT_TRIGGER
88257    /* If we have not already resolved the name, then maybe
88258    ** it is a new.* or old.* trigger argument reference
88259    */
88260    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
88261      int op = pParse->eTriggerOp;
88262      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
88263      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
88264        pExpr->iTable = 1;
88265        pTab = pParse->pTriggerTab;
88266      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
88267        pExpr->iTable = 0;
88268        pTab = pParse->pTriggerTab;
88269      }else{
88270        pTab = 0;
88271      }
88272
88273      if( pTab ){
88274        int iCol;
88275        pSchema = pTab->pSchema;
88276        cntTab++;
88277        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
88278          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88279            if( iCol==pTab->iPKey ){
88280              iCol = -1;
88281            }
88282            break;
88283          }
88284        }
88285        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
88286          /* IMP: R-51414-32910 */
88287          iCol = -1;
88288        }
88289        if( iCol<pTab->nCol ){
88290          cnt++;
88291          if( iCol<0 ){
88292            pExpr->affinity = SQLITE_AFF_INTEGER;
88293          }else if( pExpr->iTable==0 ){
88294            testcase( iCol==31 );
88295            testcase( iCol==32 );
88296            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88297          }else{
88298            testcase( iCol==31 );
88299            testcase( iCol==32 );
88300            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88301          }
88302          pExpr->iColumn = (i16)iCol;
88303          pExpr->pTab = pTab;
88304          isTrigger = 1;
88305        }
88306      }
88307    }
88308#endif /* !defined(SQLITE_OMIT_TRIGGER) */
88309
88310    /*
88311    ** Perhaps the name is a reference to the ROWID
88312    */
88313    if( cnt==0
88314     && cntTab==1
88315     && pMatch
88316     && (pNC->ncFlags & NC_IdxExpr)==0
88317     && sqlite3IsRowid(zCol)
88318     && VisibleRowid(pMatch->pTab)
88319    ){
88320      cnt = 1;
88321      pExpr->iColumn = -1;
88322      pExpr->affinity = SQLITE_AFF_INTEGER;
88323    }
88324
88325    /*
88326    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
88327    ** might refer to an result-set alias.  This happens, for example, when
88328    ** we are resolving names in the WHERE clause of the following command:
88329    **
88330    **     SELECT a+b AS x FROM table WHERE x<10;
88331    **
88332    ** In cases like this, replace pExpr with a copy of the expression that
88333    ** forms the result set entry ("a+b" in the example) and return immediately.
88334    ** Note that the expression in the result set should have already been
88335    ** resolved by the time the WHERE clause is resolved.
88336    **
88337    ** The ability to use an output result-set column in the WHERE, GROUP BY,
88338    ** or HAVING clauses, or as part of a larger expression in the ORDER BY
88339    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
88340    ** is supported for backwards compatibility only. Hence, we issue a warning
88341    ** on sqlite3_log() whenever the capability is used.
88342    */
88343    if( (pEList = pNC->pEList)!=0
88344     && zTab==0
88345     && cnt==0
88346    ){
88347      for(j=0; j<pEList->nExpr; j++){
88348        char *zAs = pEList->a[j].zName;
88349        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88350          Expr *pOrig;
88351          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88352          assert( pExpr->x.pList==0 );
88353          assert( pExpr->x.pSelect==0 );
88354          pOrig = pEList->a[j].pExpr;
88355          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
88356            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
88357            return WRC_Abort;
88358          }
88359          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
88360          cnt = 1;
88361          pMatch = 0;
88362          assert( zTab==0 && zDb==0 );
88363          goto lookupname_end;
88364        }
88365      }
88366    }
88367
88368    /* Advance to the next name context.  The loop will exit when either
88369    ** we have a match (cnt>0) or when we run out of name contexts.
88370    */
88371    if( cnt==0 ){
88372      pNC = pNC->pNext;
88373      nSubquery++;
88374    }
88375  }
88376
88377  /*
88378  ** If X and Y are NULL (in other words if only the column name Z is
88379  ** supplied) and the value of Z is enclosed in double-quotes, then
88380  ** Z is a string literal if it doesn't match any column names.  In that
88381  ** case, we need to return right away and not make any changes to
88382  ** pExpr.
88383  **
88384  ** Because no reference was made to outer contexts, the pNC->nRef
88385  ** fields are not changed in any context.
88386  */
88387  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
88388    pExpr->op = TK_STRING;
88389    pExpr->pTab = 0;
88390    return WRC_Prune;
88391  }
88392
88393  /*
88394  ** cnt==0 means there was not match.  cnt>1 means there were two or
88395  ** more matches.  Either way, we have an error.
88396  */
88397  if( cnt!=1 ){
88398    const char *zErr;
88399    zErr = cnt==0 ? "no such column" : "ambiguous column name";
88400    if( zDb ){
88401      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
88402    }else if( zTab ){
88403      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
88404    }else{
88405      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
88406    }
88407    pParse->checkSchema = 1;
88408    pTopNC->nErr++;
88409  }
88410
88411  /* If a column from a table in pSrcList is referenced, then record
88412  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
88413  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
88414  ** column number is greater than the number of bits in the bitmask
88415  ** then set the high-order bit of the bitmask.
88416  */
88417  if( pExpr->iColumn>=0 && pMatch!=0 ){
88418    int n = pExpr->iColumn;
88419    testcase( n==BMS-1 );
88420    if( n>=BMS ){
88421      n = BMS-1;
88422    }
88423    assert( pMatch->iCursor==pExpr->iTable );
88424    pMatch->colUsed |= ((Bitmask)1)<<n;
88425  }
88426
88427  /* Clean up and return
88428  */
88429  sqlite3ExprDelete(db, pExpr->pLeft);
88430  pExpr->pLeft = 0;
88431  sqlite3ExprDelete(db, pExpr->pRight);
88432  pExpr->pRight = 0;
88433  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
88434lookupname_end:
88435  if( cnt==1 ){
88436    assert( pNC!=0 );
88437    if( !ExprHasProperty(pExpr, EP_Alias) ){
88438      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
88439    }
88440    /* Increment the nRef value on all name contexts from TopNC up to
88441    ** the point where the name matched. */
88442    for(;;){
88443      assert( pTopNC!=0 );
88444      pTopNC->nRef++;
88445      if( pTopNC==pNC ) break;
88446      pTopNC = pTopNC->pNext;
88447    }
88448    return WRC_Prune;
88449  } else {
88450    return WRC_Abort;
88451  }
88452}
88453
88454/*
88455** Allocate and return a pointer to an expression to load the column iCol
88456** from datasource iSrc in SrcList pSrc.
88457*/
88458SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
88459  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
88460  if( p ){
88461    struct SrcList_item *pItem = &pSrc->a[iSrc];
88462    p->pTab = pItem->pTab;
88463    p->iTable = pItem->iCursor;
88464    if( p->pTab->iPKey==iCol ){
88465      p->iColumn = -1;
88466    }else{
88467      p->iColumn = (ynVar)iCol;
88468      testcase( iCol==BMS );
88469      testcase( iCol==BMS-1 );
88470      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
88471    }
88472    ExprSetProperty(p, EP_Resolved);
88473  }
88474  return p;
88475}
88476
88477/*
88478** Report an error that an expression is not valid for some set of
88479** pNC->ncFlags values determined by validMask.
88480*/
88481static void notValid(
88482  Parse *pParse,       /* Leave error message here */
88483  NameContext *pNC,    /* The name context */
88484  const char *zMsg,    /* Type of error */
88485  int validMask        /* Set of contexts for which prohibited */
88486){
88487  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
88488  if( (pNC->ncFlags & validMask)!=0 ){
88489    const char *zIn = "partial index WHERE clauses";
88490    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
88491#ifndef SQLITE_OMIT_CHECK
88492    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
88493#endif
88494    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
88495  }
88496}
88497
88498/*
88499** Expression p should encode a floating point value between 1.0 and 0.0.
88500** Return 1024 times this value.  Or return -1 if p is not a floating point
88501** value between 1.0 and 0.0.
88502*/
88503static int exprProbability(Expr *p){
88504  double r = -1.0;
88505  if( p->op!=TK_FLOAT ) return -1;
88506  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
88507  assert( r>=0.0 );
88508  if( r>1.0 ) return -1;
88509  return (int)(r*134217728.0);
88510}
88511
88512/*
88513** This routine is callback for sqlite3WalkExpr().
88514**
88515** Resolve symbolic names into TK_COLUMN operators for the current
88516** node in the expression tree.  Return 0 to continue the search down
88517** the tree or 2 to abort the tree walk.
88518**
88519** This routine also does error checking and name resolution for
88520** function names.  The operator for aggregate functions is changed
88521** to TK_AGG_FUNCTION.
88522*/
88523static int resolveExprStep(Walker *pWalker, Expr *pExpr){
88524  NameContext *pNC;
88525  Parse *pParse;
88526
88527  pNC = pWalker->u.pNC;
88528  assert( pNC!=0 );
88529  pParse = pNC->pParse;
88530  assert( pParse==pWalker->pParse );
88531
88532  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
88533  ExprSetProperty(pExpr, EP_Resolved);
88534#ifndef NDEBUG
88535  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
88536    SrcList *pSrcList = pNC->pSrcList;
88537    int i;
88538    for(i=0; i<pNC->pSrcList->nSrc; i++){
88539      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
88540    }
88541  }
88542#endif
88543  switch( pExpr->op ){
88544
88545#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
88546    /* The special operator TK_ROW means use the rowid for the first
88547    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
88548    ** clause processing on UPDATE and DELETE statements.
88549    */
88550    case TK_ROW: {
88551      SrcList *pSrcList = pNC->pSrcList;
88552      struct SrcList_item *pItem;
88553      assert( pSrcList && pSrcList->nSrc==1 );
88554      pItem = pSrcList->a;
88555      pExpr->op = TK_COLUMN;
88556      pExpr->pTab = pItem->pTab;
88557      pExpr->iTable = pItem->iCursor;
88558      pExpr->iColumn = -1;
88559      pExpr->affinity = SQLITE_AFF_INTEGER;
88560      break;
88561    }
88562#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
88563          && !defined(SQLITE_OMIT_SUBQUERY) */
88564
88565    /* A lone identifier is the name of a column.
88566    */
88567    case TK_ID: {
88568      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
88569    }
88570
88571    /* A table name and column name:     ID.ID
88572    ** Or a database, table and column:  ID.ID.ID
88573    */
88574    case TK_DOT: {
88575      const char *zColumn;
88576      const char *zTable;
88577      const char *zDb;
88578      Expr *pRight;
88579
88580      /* if( pSrcList==0 ) break; */
88581      notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
88582      /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
88583      pRight = pExpr->pRight;
88584      if( pRight->op==TK_ID ){
88585        zDb = 0;
88586        zTable = pExpr->pLeft->u.zToken;
88587        zColumn = pRight->u.zToken;
88588      }else{
88589        assert( pRight->op==TK_DOT );
88590        zDb = pExpr->pLeft->u.zToken;
88591        zTable = pRight->pLeft->u.zToken;
88592        zColumn = pRight->pRight->u.zToken;
88593      }
88594      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
88595    }
88596
88597    /* Resolve function names
88598    */
88599    case TK_FUNCTION: {
88600      ExprList *pList = pExpr->x.pList;    /* The argument list */
88601      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
88602      int no_such_func = 0;       /* True if no such function exists */
88603      int wrong_num_args = 0;     /* True if wrong number of arguments */
88604      int is_agg = 0;             /* True if is an aggregate function */
88605      int auth;                   /* Authorization to use the function */
88606      int nId;                    /* Number of characters in function name */
88607      const char *zId;            /* The function name. */
88608      FuncDef *pDef;              /* Information about the function */
88609      u8 enc = ENC(pParse->db);   /* The database encoding */
88610
88611      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88612      notValid(pParse, pNC, "functions", NC_PartIdx);
88613      zId = pExpr->u.zToken;
88614      nId = sqlite3Strlen30(zId);
88615      pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
88616      if( pDef==0 ){
88617        pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
88618        if( pDef==0 ){
88619          no_such_func = 1;
88620        }else{
88621          wrong_num_args = 1;
88622        }
88623      }else{
88624        is_agg = pDef->xFinalize!=0;
88625        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
88626          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
88627          if( n==2 ){
88628            pExpr->iTable = exprProbability(pList->a[1].pExpr);
88629            if( pExpr->iTable<0 ){
88630              sqlite3ErrorMsg(pParse,
88631                "second argument to likelihood() must be a "
88632                "constant between 0.0 and 1.0");
88633              pNC->nErr++;
88634            }
88635          }else{
88636            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
88637            ** equivalent to likelihood(X, 0.0625).
88638            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
88639            ** short-hand for likelihood(X,0.0625).
88640            ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
88641            ** for likelihood(X,0.9375).
88642            ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
88643            ** to likelihood(X,0.9375). */
88644            /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
88645            pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
88646          }
88647        }
88648#ifndef SQLITE_OMIT_AUTHORIZATION
88649        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
88650        if( auth!=SQLITE_OK ){
88651          if( auth==SQLITE_DENY ){
88652            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
88653                                    pDef->zName);
88654            pNC->nErr++;
88655          }
88656          pExpr->op = TK_NULL;
88657          return WRC_Prune;
88658        }
88659#endif
88660        if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
88661          /* For the purposes of the EP_ConstFunc flag, date and time
88662          ** functions and other functions that change slowly are considered
88663          ** constant because they are constant for the duration of one query */
88664          ExprSetProperty(pExpr,EP_ConstFunc);
88665        }
88666        if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
88667          /* Date/time functions that use 'now', and other functions like
88668          ** sqlite_version() that might change over time cannot be used
88669          ** in an index. */
88670          notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
88671        }
88672      }
88673      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
88674        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
88675        pNC->nErr++;
88676        is_agg = 0;
88677      }else if( no_such_func && pParse->db->init.busy==0
88678#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
88679                && pParse->explain==0
88680#endif
88681      ){
88682        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
88683        pNC->nErr++;
88684      }else if( wrong_num_args ){
88685        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
88686             nId, zId);
88687        pNC->nErr++;
88688      }
88689      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
88690      sqlite3WalkExprList(pWalker, pList);
88691      if( is_agg ){
88692        NameContext *pNC2 = pNC;
88693        pExpr->op = TK_AGG_FUNCTION;
88694        pExpr->op2 = 0;
88695        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
88696          pExpr->op2++;
88697          pNC2 = pNC2->pNext;
88698        }
88699        assert( pDef!=0 );
88700        if( pNC2 ){
88701          assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
88702          testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
88703          pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
88704
88705        }
88706        pNC->ncFlags |= NC_AllowAgg;
88707      }
88708      /* FIX ME:  Compute pExpr->affinity based on the expected return
88709      ** type of the function
88710      */
88711      return WRC_Prune;
88712    }
88713#ifndef SQLITE_OMIT_SUBQUERY
88714    case TK_SELECT:
88715    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
88716#endif
88717    case TK_IN: {
88718      testcase( pExpr->op==TK_IN );
88719      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88720        int nRef = pNC->nRef;
88721        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88722        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88723        assert( pNC->nRef>=nRef );
88724        if( nRef!=pNC->nRef ){
88725          ExprSetProperty(pExpr, EP_VarSelect);
88726          pNC->ncFlags |= NC_VarSelect;
88727        }
88728      }
88729      break;
88730    }
88731    case TK_VARIABLE: {
88732      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88733      break;
88734    }
88735  }
88736  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
88737}
88738
88739/*
88740** pEList is a list of expressions which are really the result set of the
88741** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
88742** This routine checks to see if pE is a simple identifier which corresponds
88743** to the AS-name of one of the terms of the expression list.  If it is,
88744** this routine return an integer between 1 and N where N is the number of
88745** elements in pEList, corresponding to the matching entry.  If there is
88746** no match, or if pE is not a simple identifier, then this routine
88747** return 0.
88748**
88749** pEList has been resolved.  pE has not.
88750*/
88751static int resolveAsName(
88752  Parse *pParse,     /* Parsing context for error messages */
88753  ExprList *pEList,  /* List of expressions to scan */
88754  Expr *pE           /* Expression we are trying to match */
88755){
88756  int i;             /* Loop counter */
88757
88758  UNUSED_PARAMETER(pParse);
88759
88760  if( pE->op==TK_ID ){
88761    char *zCol = pE->u.zToken;
88762    for(i=0; i<pEList->nExpr; i++){
88763      char *zAs = pEList->a[i].zName;
88764      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88765        return i+1;
88766      }
88767    }
88768  }
88769  return 0;
88770}
88771
88772/*
88773** pE is a pointer to an expression which is a single term in the
88774** ORDER BY of a compound SELECT.  The expression has not been
88775** name resolved.
88776**
88777** At the point this routine is called, we already know that the
88778** ORDER BY term is not an integer index into the result set.  That
88779** case is handled by the calling routine.
88780**
88781** Attempt to match pE against result set columns in the left-most
88782** SELECT statement.  Return the index i of the matching column,
88783** as an indication to the caller that it should sort by the i-th column.
88784** The left-most column is 1.  In other words, the value returned is the
88785** same integer value that would be used in the SQL statement to indicate
88786** the column.
88787**
88788** If there is no match, return 0.  Return -1 if an error occurs.
88789*/
88790static int resolveOrderByTermToExprList(
88791  Parse *pParse,     /* Parsing context for error messages */
88792  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
88793  Expr *pE           /* The specific ORDER BY term */
88794){
88795  int i;             /* Loop counter */
88796  ExprList *pEList;  /* The columns of the result set */
88797  NameContext nc;    /* Name context for resolving pE */
88798  sqlite3 *db;       /* Database connection */
88799  int rc;            /* Return code from subprocedures */
88800  u8 savedSuppErr;   /* Saved value of db->suppressErr */
88801
88802  assert( sqlite3ExprIsInteger(pE, &i)==0 );
88803  pEList = pSelect->pEList;
88804
88805  /* Resolve all names in the ORDER BY term expression
88806  */
88807  memset(&nc, 0, sizeof(nc));
88808  nc.pParse = pParse;
88809  nc.pSrcList = pSelect->pSrc;
88810  nc.pEList = pEList;
88811  nc.ncFlags = NC_AllowAgg;
88812  nc.nErr = 0;
88813  db = pParse->db;
88814  savedSuppErr = db->suppressErr;
88815  db->suppressErr = 1;
88816  rc = sqlite3ResolveExprNames(&nc, pE);
88817  db->suppressErr = savedSuppErr;
88818  if( rc ) return 0;
88819
88820  /* Try to match the ORDER BY expression against an expression
88821  ** in the result set.  Return an 1-based index of the matching
88822  ** result-set entry.
88823  */
88824  for(i=0; i<pEList->nExpr; i++){
88825    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
88826      return i+1;
88827    }
88828  }
88829
88830  /* If no match, return 0. */
88831  return 0;
88832}
88833
88834/*
88835** Generate an ORDER BY or GROUP BY term out-of-range error.
88836*/
88837static void resolveOutOfRangeError(
88838  Parse *pParse,         /* The error context into which to write the error */
88839  const char *zType,     /* "ORDER" or "GROUP" */
88840  int i,                 /* The index (1-based) of the term out of range */
88841  int mx                 /* Largest permissible value of i */
88842){
88843  sqlite3ErrorMsg(pParse,
88844    "%r %s BY term out of range - should be "
88845    "between 1 and %d", i, zType, mx);
88846}
88847
88848/*
88849** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
88850** each term of the ORDER BY clause is a constant integer between 1
88851** and N where N is the number of columns in the compound SELECT.
88852**
88853** ORDER BY terms that are already an integer between 1 and N are
88854** unmodified.  ORDER BY terms that are integers outside the range of
88855** 1 through N generate an error.  ORDER BY terms that are expressions
88856** are matched against result set expressions of compound SELECT
88857** beginning with the left-most SELECT and working toward the right.
88858** At the first match, the ORDER BY expression is transformed into
88859** the integer column number.
88860**
88861** Return the number of errors seen.
88862*/
88863static int resolveCompoundOrderBy(
88864  Parse *pParse,        /* Parsing context.  Leave error messages here */
88865  Select *pSelect       /* The SELECT statement containing the ORDER BY */
88866){
88867  int i;
88868  ExprList *pOrderBy;
88869  ExprList *pEList;
88870  sqlite3 *db;
88871  int moreToDo = 1;
88872
88873  pOrderBy = pSelect->pOrderBy;
88874  if( pOrderBy==0 ) return 0;
88875  db = pParse->db;
88876#if SQLITE_MAX_COLUMN
88877  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88878    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
88879    return 1;
88880  }
88881#endif
88882  for(i=0; i<pOrderBy->nExpr; i++){
88883    pOrderBy->a[i].done = 0;
88884  }
88885  pSelect->pNext = 0;
88886  while( pSelect->pPrior ){
88887    pSelect->pPrior->pNext = pSelect;
88888    pSelect = pSelect->pPrior;
88889  }
88890  while( pSelect && moreToDo ){
88891    struct ExprList_item *pItem;
88892    moreToDo = 0;
88893    pEList = pSelect->pEList;
88894    assert( pEList!=0 );
88895    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88896      int iCol = -1;
88897      Expr *pE, *pDup;
88898      if( pItem->done ) continue;
88899      pE = sqlite3ExprSkipCollate(pItem->pExpr);
88900      if( sqlite3ExprIsInteger(pE, &iCol) ){
88901        if( iCol<=0 || iCol>pEList->nExpr ){
88902          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
88903          return 1;
88904        }
88905      }else{
88906        iCol = resolveAsName(pParse, pEList, pE);
88907        if( iCol==0 ){
88908          pDup = sqlite3ExprDup(db, pE, 0);
88909          if( !db->mallocFailed ){
88910            assert(pDup);
88911            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
88912          }
88913          sqlite3ExprDelete(db, pDup);
88914        }
88915      }
88916      if( iCol>0 ){
88917        /* Convert the ORDER BY term into an integer column number iCol,
88918        ** taking care to preserve the COLLATE clause if it exists */
88919        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
88920        if( pNew==0 ) return 1;
88921        pNew->flags |= EP_IntValue;
88922        pNew->u.iValue = iCol;
88923        if( pItem->pExpr==pE ){
88924          pItem->pExpr = pNew;
88925        }else{
88926          Expr *pParent = pItem->pExpr;
88927          assert( pParent->op==TK_COLLATE );
88928          while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
88929          assert( pParent->pLeft==pE );
88930          pParent->pLeft = pNew;
88931        }
88932        sqlite3ExprDelete(db, pE);
88933        pItem->u.x.iOrderByCol = (u16)iCol;
88934        pItem->done = 1;
88935      }else{
88936        moreToDo = 1;
88937      }
88938    }
88939    pSelect = pSelect->pNext;
88940  }
88941  for(i=0; i<pOrderBy->nExpr; i++){
88942    if( pOrderBy->a[i].done==0 ){
88943      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
88944            "column in the result set", i+1);
88945      return 1;
88946    }
88947  }
88948  return 0;
88949}
88950
88951/*
88952** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
88953** the SELECT statement pSelect.  If any term is reference to a
88954** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
88955** field) then convert that term into a copy of the corresponding result set
88956** column.
88957**
88958** If any errors are detected, add an error message to pParse and
88959** return non-zero.  Return zero if no errors are seen.
88960*/
88961SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
88962  Parse *pParse,        /* Parsing context.  Leave error messages here */
88963  Select *pSelect,      /* The SELECT statement containing the clause */
88964  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
88965  const char *zType     /* "ORDER" or "GROUP" */
88966){
88967  int i;
88968  sqlite3 *db = pParse->db;
88969  ExprList *pEList;
88970  struct ExprList_item *pItem;
88971
88972  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
88973#if SQLITE_MAX_COLUMN
88974  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88975    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
88976    return 1;
88977  }
88978#endif
88979  pEList = pSelect->pEList;
88980  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
88981  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88982    if( pItem->u.x.iOrderByCol ){
88983      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
88984        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
88985        return 1;
88986      }
88987      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
88988                   zType,0);
88989    }
88990  }
88991  return 0;
88992}
88993
88994/*
88995** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
88996** The Name context of the SELECT statement is pNC.  zType is either
88997** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
88998**
88999** This routine resolves each term of the clause into an expression.
89000** If the order-by term is an integer I between 1 and N (where N is the
89001** number of columns in the result set of the SELECT) then the expression
89002** in the resolution is a copy of the I-th result-set expression.  If
89003** the order-by term is an identifier that corresponds to the AS-name of
89004** a result-set expression, then the term resolves to a copy of the
89005** result-set expression.  Otherwise, the expression is resolved in
89006** the usual way - using sqlite3ResolveExprNames().
89007**
89008** This routine returns the number of errors.  If errors occur, then
89009** an appropriate error message might be left in pParse.  (OOM errors
89010** excepted.)
89011*/
89012static int resolveOrderGroupBy(
89013  NameContext *pNC,     /* The name context of the SELECT statement */
89014  Select *pSelect,      /* The SELECT statement holding pOrderBy */
89015  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
89016  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
89017){
89018  int i, j;                      /* Loop counters */
89019  int iCol;                      /* Column number */
89020  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
89021  Parse *pParse;                 /* Parsing context */
89022  int nResult;                   /* Number of terms in the result set */
89023
89024  if( pOrderBy==0 ) return 0;
89025  nResult = pSelect->pEList->nExpr;
89026  pParse = pNC->pParse;
89027  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89028    Expr *pE = pItem->pExpr;
89029    Expr *pE2 = sqlite3ExprSkipCollate(pE);
89030    if( zType[0]!='G' ){
89031      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
89032      if( iCol>0 ){
89033        /* If an AS-name match is found, mark this ORDER BY column as being
89034        ** a copy of the iCol-th result-set column.  The subsequent call to
89035        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
89036        ** copy of the iCol-th result-set expression. */
89037        pItem->u.x.iOrderByCol = (u16)iCol;
89038        continue;
89039      }
89040    }
89041    if( sqlite3ExprIsInteger(pE2, &iCol) ){
89042      /* The ORDER BY term is an integer constant.  Again, set the column
89043      ** number so that sqlite3ResolveOrderGroupBy() will convert the
89044      ** order-by term to a copy of the result-set expression */
89045      if( iCol<1 || iCol>0xffff ){
89046        resolveOutOfRangeError(pParse, zType, i+1, nResult);
89047        return 1;
89048      }
89049      pItem->u.x.iOrderByCol = (u16)iCol;
89050      continue;
89051    }
89052
89053    /* Otherwise, treat the ORDER BY term as an ordinary expression */
89054    pItem->u.x.iOrderByCol = 0;
89055    if( sqlite3ResolveExprNames(pNC, pE) ){
89056      return 1;
89057    }
89058    for(j=0; j<pSelect->pEList->nExpr; j++){
89059      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
89060        pItem->u.x.iOrderByCol = j+1;
89061      }
89062    }
89063  }
89064  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
89065}
89066
89067/*
89068** Resolve names in the SELECT statement p and all of its descendants.
89069*/
89070static int resolveSelectStep(Walker *pWalker, Select *p){
89071  NameContext *pOuterNC;  /* Context that contains this SELECT */
89072  NameContext sNC;        /* Name context of this SELECT */
89073  int isCompound;         /* True if p is a compound select */
89074  int nCompound;          /* Number of compound terms processed so far */
89075  Parse *pParse;          /* Parsing context */
89076  int i;                  /* Loop counter */
89077  ExprList *pGroupBy;     /* The GROUP BY clause */
89078  Select *pLeftmost;      /* Left-most of SELECT of a compound */
89079  sqlite3 *db;            /* Database connection */
89080
89081
89082  assert( p!=0 );
89083  if( p->selFlags & SF_Resolved ){
89084    return WRC_Prune;
89085  }
89086  pOuterNC = pWalker->u.pNC;
89087  pParse = pWalker->pParse;
89088  db = pParse->db;
89089
89090  /* Normally sqlite3SelectExpand() will be called first and will have
89091  ** already expanded this SELECT.  However, if this is a subquery within
89092  ** an expression, sqlite3ResolveExprNames() will be called without a
89093  ** prior call to sqlite3SelectExpand().  When that happens, let
89094  ** sqlite3SelectPrep() do all of the processing for this SELECT.
89095  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
89096  ** this routine in the correct order.
89097  */
89098  if( (p->selFlags & SF_Expanded)==0 ){
89099    sqlite3SelectPrep(pParse, p, pOuterNC);
89100    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
89101  }
89102
89103  isCompound = p->pPrior!=0;
89104  nCompound = 0;
89105  pLeftmost = p;
89106  while( p ){
89107    assert( (p->selFlags & SF_Expanded)!=0 );
89108    assert( (p->selFlags & SF_Resolved)==0 );
89109    p->selFlags |= SF_Resolved;
89110
89111    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
89112    ** are not allowed to refer to any names, so pass an empty NameContext.
89113    */
89114    memset(&sNC, 0, sizeof(sNC));
89115    sNC.pParse = pParse;
89116    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
89117        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
89118      return WRC_Abort;
89119    }
89120
89121    /* If the SF_Converted flags is set, then this Select object was
89122    ** was created by the convertCompoundSelectToSubquery() function.
89123    ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
89124    ** as if it were part of the sub-query, not the parent. This block
89125    ** moves the pOrderBy down to the sub-query. It will be moved back
89126    ** after the names have been resolved.  */
89127    if( p->selFlags & SF_Converted ){
89128      Select *pSub = p->pSrc->a[0].pSelect;
89129      assert( p->pSrc->nSrc==1 && p->pOrderBy );
89130      assert( pSub->pPrior && pSub->pOrderBy==0 );
89131      pSub->pOrderBy = p->pOrderBy;
89132      p->pOrderBy = 0;
89133    }
89134
89135    /* Recursively resolve names in all subqueries
89136    */
89137    for(i=0; i<p->pSrc->nSrc; i++){
89138      struct SrcList_item *pItem = &p->pSrc->a[i];
89139      if( pItem->pSelect ){
89140        NameContext *pNC;         /* Used to iterate name contexts */
89141        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
89142        const char *zSavedContext = pParse->zAuthContext;
89143
89144        /* Count the total number of references to pOuterNC and all of its
89145        ** parent contexts. After resolving references to expressions in
89146        ** pItem->pSelect, check if this value has changed. If so, then
89147        ** SELECT statement pItem->pSelect must be correlated. Set the
89148        ** pItem->fg.isCorrelated flag if this is the case. */
89149        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
89150
89151        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
89152        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
89153        pParse->zAuthContext = zSavedContext;
89154        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
89155
89156        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
89157        assert( pItem->fg.isCorrelated==0 && nRef<=0 );
89158        pItem->fg.isCorrelated = (nRef!=0);
89159      }
89160    }
89161
89162    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
89163    ** resolve the result-set expression list.
89164    */
89165    sNC.ncFlags = NC_AllowAgg;
89166    sNC.pSrcList = p->pSrc;
89167    sNC.pNext = pOuterNC;
89168
89169    /* Resolve names in the result set. */
89170    if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
89171
89172    /* If there are no aggregate functions in the result-set, and no GROUP BY
89173    ** expression, do not allow aggregates in any of the other expressions.
89174    */
89175    assert( (p->selFlags & SF_Aggregate)==0 );
89176    pGroupBy = p->pGroupBy;
89177    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
89178      assert( NC_MinMaxAgg==SF_MinMaxAgg );
89179      p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
89180    }else{
89181      sNC.ncFlags &= ~NC_AllowAgg;
89182    }
89183
89184    /* If a HAVING clause is present, then there must be a GROUP BY clause.
89185    */
89186    if( p->pHaving && !pGroupBy ){
89187      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
89188      return WRC_Abort;
89189    }
89190
89191    /* Add the output column list to the name-context before parsing the
89192    ** other expressions in the SELECT statement. This is so that
89193    ** expressions in the WHERE clause (etc.) can refer to expressions by
89194    ** aliases in the result set.
89195    **
89196    ** Minor point: If this is the case, then the expression will be
89197    ** re-evaluated for each reference to it.
89198    */
89199    sNC.pEList = p->pEList;
89200    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
89201    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
89202
89203    /* Resolve names in table-valued-function arguments */
89204    for(i=0; i<p->pSrc->nSrc; i++){
89205      struct SrcList_item *pItem = &p->pSrc->a[i];
89206      if( pItem->fg.isTabFunc
89207       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
89208      ){
89209        return WRC_Abort;
89210      }
89211    }
89212
89213    /* The ORDER BY and GROUP BY clauses may not refer to terms in
89214    ** outer queries
89215    */
89216    sNC.pNext = 0;
89217    sNC.ncFlags |= NC_AllowAgg;
89218
89219    /* If this is a converted compound query, move the ORDER BY clause from
89220    ** the sub-query back to the parent query. At this point each term
89221    ** within the ORDER BY clause has been transformed to an integer value.
89222    ** These integers will be replaced by copies of the corresponding result
89223    ** set expressions by the call to resolveOrderGroupBy() below.  */
89224    if( p->selFlags & SF_Converted ){
89225      Select *pSub = p->pSrc->a[0].pSelect;
89226      p->pOrderBy = pSub->pOrderBy;
89227      pSub->pOrderBy = 0;
89228    }
89229
89230    /* Process the ORDER BY clause for singleton SELECT statements.
89231    ** The ORDER BY clause for compounds SELECT statements is handled
89232    ** below, after all of the result-sets for all of the elements of
89233    ** the compound have been resolved.
89234    **
89235    ** If there is an ORDER BY clause on a term of a compound-select other
89236    ** than the right-most term, then that is a syntax error.  But the error
89237    ** is not detected until much later, and so we need to go ahead and
89238    ** resolve those symbols on the incorrect ORDER BY for consistency.
89239    */
89240    if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
89241     && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
89242    ){
89243      return WRC_Abort;
89244    }
89245    if( db->mallocFailed ){
89246      return WRC_Abort;
89247    }
89248
89249    /* Resolve the GROUP BY clause.  At the same time, make sure
89250    ** the GROUP BY clause does not contain aggregate functions.
89251    */
89252    if( pGroupBy ){
89253      struct ExprList_item *pItem;
89254
89255      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
89256        return WRC_Abort;
89257      }
89258      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
89259        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
89260          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
89261              "the GROUP BY clause");
89262          return WRC_Abort;
89263        }
89264      }
89265    }
89266
89267    /* If this is part of a compound SELECT, check that it has the right
89268    ** number of expressions in the select list. */
89269    if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
89270      sqlite3SelectWrongNumTermsError(pParse, p->pNext);
89271      return WRC_Abort;
89272    }
89273
89274    /* Advance to the next term of the compound
89275    */
89276    p = p->pPrior;
89277    nCompound++;
89278  }
89279
89280  /* Resolve the ORDER BY on a compound SELECT after all terms of
89281  ** the compound have been resolved.
89282  */
89283  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
89284    return WRC_Abort;
89285  }
89286
89287  return WRC_Prune;
89288}
89289
89290/*
89291** This routine walks an expression tree and resolves references to
89292** table columns and result-set columns.  At the same time, do error
89293** checking on function usage and set a flag if any aggregate functions
89294** are seen.
89295**
89296** To resolve table columns references we look for nodes (or subtrees) of the
89297** form X.Y.Z or Y.Z or just Z where
89298**
89299**      X:   The name of a database.  Ex:  "main" or "temp" or
89300**           the symbolic name assigned to an ATTACH-ed database.
89301**
89302**      Y:   The name of a table in a FROM clause.  Or in a trigger
89303**           one of the special names "old" or "new".
89304**
89305**      Z:   The name of a column in table Y.
89306**
89307** The node at the root of the subtree is modified as follows:
89308**
89309**    Expr.op        Changed to TK_COLUMN
89310**    Expr.pTab      Points to the Table object for X.Y
89311**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
89312**    Expr.iTable    The VDBE cursor number for X.Y
89313**
89314**
89315** To resolve result-set references, look for expression nodes of the
89316** form Z (with no X and Y prefix) where the Z matches the right-hand
89317** size of an AS clause in the result-set of a SELECT.  The Z expression
89318** is replaced by a copy of the left-hand side of the result-set expression.
89319** Table-name and function resolution occurs on the substituted expression
89320** tree.  For example, in:
89321**
89322**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
89323**
89324** The "x" term of the order by is replaced by "a+b" to render:
89325**
89326**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
89327**
89328** Function calls are checked to make sure that the function is
89329** defined and that the correct number of arguments are specified.
89330** If the function is an aggregate function, then the NC_HasAgg flag is
89331** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
89332** If an expression contains aggregate functions then the EP_Agg
89333** property on the expression is set.
89334**
89335** An error message is left in pParse if anything is amiss.  The number
89336** if errors is returned.
89337*/
89338SQLITE_PRIVATE int sqlite3ResolveExprNames(
89339  NameContext *pNC,       /* Namespace to resolve expressions in. */
89340  Expr *pExpr             /* The expression to be analyzed. */
89341){
89342  u16 savedHasAgg;
89343  Walker w;
89344
89345  if( pExpr==0 ) return 0;
89346#if SQLITE_MAX_EXPR_DEPTH>0
89347  {
89348    Parse *pParse = pNC->pParse;
89349    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
89350      return 1;
89351    }
89352    pParse->nHeight += pExpr->nHeight;
89353  }
89354#endif
89355  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
89356  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
89357  w.pParse = pNC->pParse;
89358  w.xExprCallback = resolveExprStep;
89359  w.xSelectCallback = resolveSelectStep;
89360  w.xSelectCallback2 = 0;
89361  w.walkerDepth = 0;
89362  w.eCode = 0;
89363  w.u.pNC = pNC;
89364  sqlite3WalkExpr(&w, pExpr);
89365#if SQLITE_MAX_EXPR_DEPTH>0
89366  pNC->pParse->nHeight -= pExpr->nHeight;
89367#endif
89368  if( pNC->nErr>0 || w.pParse->nErr>0 ){
89369    ExprSetProperty(pExpr, EP_Error);
89370  }
89371  if( pNC->ncFlags & NC_HasAgg ){
89372    ExprSetProperty(pExpr, EP_Agg);
89373  }
89374  pNC->ncFlags |= savedHasAgg;
89375  return ExprHasProperty(pExpr, EP_Error);
89376}
89377
89378/*
89379** Resolve all names for all expression in an expression list.  This is
89380** just like sqlite3ResolveExprNames() except that it works for an expression
89381** list rather than a single expression.
89382*/
89383SQLITE_PRIVATE int sqlite3ResolveExprListNames(
89384  NameContext *pNC,       /* Namespace to resolve expressions in. */
89385  ExprList *pList         /* The expression list to be analyzed. */
89386){
89387  int i;
89388  if( pList ){
89389    for(i=0; i<pList->nExpr; i++){
89390      if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
89391    }
89392  }
89393  return WRC_Continue;
89394}
89395
89396/*
89397** Resolve all names in all expressions of a SELECT and in all
89398** decendents of the SELECT, including compounds off of p->pPrior,
89399** subqueries in expressions, and subqueries used as FROM clause
89400** terms.
89401**
89402** See sqlite3ResolveExprNames() for a description of the kinds of
89403** transformations that occur.
89404**
89405** All SELECT statements should have been expanded using
89406** sqlite3SelectExpand() prior to invoking this routine.
89407*/
89408SQLITE_PRIVATE void sqlite3ResolveSelectNames(
89409  Parse *pParse,         /* The parser context */
89410  Select *p,             /* The SELECT statement being coded. */
89411  NameContext *pOuterNC  /* Name context for parent SELECT statement */
89412){
89413  Walker w;
89414
89415  assert( p!=0 );
89416  memset(&w, 0, sizeof(w));
89417  w.xExprCallback = resolveExprStep;
89418  w.xSelectCallback = resolveSelectStep;
89419  w.pParse = pParse;
89420  w.u.pNC = pOuterNC;
89421  sqlite3WalkSelect(&w, p);
89422}
89423
89424/*
89425** Resolve names in expressions that can only reference a single table:
89426**
89427**    *   CHECK constraints
89428**    *   WHERE clauses on partial indices
89429**
89430** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
89431** is set to -1 and the Expr.iColumn value is set to the column number.
89432**
89433** Any errors cause an error message to be set in pParse.
89434*/
89435SQLITE_PRIVATE void sqlite3ResolveSelfReference(
89436  Parse *pParse,      /* Parsing context */
89437  Table *pTab,        /* The table being referenced */
89438  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
89439  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
89440  ExprList *pList     /* Expression list to resolve.  May be NUL. */
89441){
89442  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
89443  NameContext sNC;                /* Name context for pParse->pNewTable */
89444
89445  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
89446  memset(&sNC, 0, sizeof(sNC));
89447  memset(&sSrc, 0, sizeof(sSrc));
89448  sSrc.nSrc = 1;
89449  sSrc.a[0].zName = pTab->zName;
89450  sSrc.a[0].pTab = pTab;
89451  sSrc.a[0].iCursor = -1;
89452  sNC.pParse = pParse;
89453  sNC.pSrcList = &sSrc;
89454  sNC.ncFlags = type;
89455  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
89456  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
89457}
89458
89459/************** End of resolve.c *********************************************/
89460/************** Begin file expr.c ********************************************/
89461/*
89462** 2001 September 15
89463**
89464** The author disclaims copyright to this source code.  In place of
89465** a legal notice, here is a blessing:
89466**
89467**    May you do good and not evil.
89468**    May you find forgiveness for yourself and forgive others.
89469**    May you share freely, never taking more than you give.
89470**
89471*************************************************************************
89472** This file contains routines used for analyzing expressions and
89473** for generating VDBE code that evaluates expressions in SQLite.
89474*/
89475/* #include "sqliteInt.h" */
89476
89477/*
89478** Return the 'affinity' of the expression pExpr if any.
89479**
89480** If pExpr is a column, a reference to a column via an 'AS' alias,
89481** or a sub-select with a column as the return value, then the
89482** affinity of that column is returned. Otherwise, 0x00 is returned,
89483** indicating no affinity for the expression.
89484**
89485** i.e. the WHERE clause expressions in the following statements all
89486** have an affinity:
89487**
89488** CREATE TABLE t1(a);
89489** SELECT * FROM t1 WHERE a;
89490** SELECT a AS b FROM t1 WHERE b;
89491** SELECT * FROM t1 WHERE (select a from t1);
89492*/
89493SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
89494  int op;
89495  pExpr = sqlite3ExprSkipCollate(pExpr);
89496  if( pExpr->flags & EP_Generic ) return 0;
89497  op = pExpr->op;
89498  if( op==TK_SELECT ){
89499    assert( pExpr->flags&EP_xIsSelect );
89500    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
89501  }
89502#ifndef SQLITE_OMIT_CAST
89503  if( op==TK_CAST ){
89504    assert( !ExprHasProperty(pExpr, EP_IntValue) );
89505    return sqlite3AffinityType(pExpr->u.zToken, 0);
89506  }
89507#endif
89508  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
89509   && pExpr->pTab!=0
89510  ){
89511    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
89512    ** a TK_COLUMN but was previously evaluated and cached in a register */
89513    int j = pExpr->iColumn;
89514    if( j<0 ) return SQLITE_AFF_INTEGER;
89515    assert( pExpr->pTab && j<pExpr->pTab->nCol );
89516    return pExpr->pTab->aCol[j].affinity;
89517  }
89518  return pExpr->affinity;
89519}
89520
89521/*
89522** Set the collating sequence for expression pExpr to be the collating
89523** sequence named by pToken.   Return a pointer to a new Expr node that
89524** implements the COLLATE operator.
89525**
89526** If a memory allocation error occurs, that fact is recorded in pParse->db
89527** and the pExpr parameter is returned unchanged.
89528*/
89529SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
89530  Parse *pParse,           /* Parsing context */
89531  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
89532  const Token *pCollName,  /* Name of collating sequence */
89533  int dequote              /* True to dequote pCollName */
89534){
89535  if( pCollName->n>0 ){
89536    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89537    if( pNew ){
89538      pNew->pLeft = pExpr;
89539      pNew->flags |= EP_Collate|EP_Skip;
89540      pExpr = pNew;
89541    }
89542  }
89543  return pExpr;
89544}
89545SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
89546  Token s;
89547  assert( zC!=0 );
89548  sqlite3TokenInit(&s, (char*)zC);
89549  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
89550}
89551
89552/*
89553** Skip over any TK_COLLATE operators and any unlikely()
89554** or likelihood() function at the root of an expression.
89555*/
89556SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
89557  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
89558    if( ExprHasProperty(pExpr, EP_Unlikely) ){
89559      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89560      assert( pExpr->x.pList->nExpr>0 );
89561      assert( pExpr->op==TK_FUNCTION );
89562      pExpr = pExpr->x.pList->a[0].pExpr;
89563    }else{
89564      assert( pExpr->op==TK_COLLATE );
89565      pExpr = pExpr->pLeft;
89566    }
89567  }
89568  return pExpr;
89569}
89570
89571/*
89572** Return the collation sequence for the expression pExpr. If
89573** there is no defined collating sequence, return NULL.
89574**
89575** The collating sequence might be determined by a COLLATE operator
89576** or by the presence of a column with a defined collating sequence.
89577** COLLATE operators take first precedence.  Left operands take
89578** precedence over right operands.
89579*/
89580SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
89581  sqlite3 *db = pParse->db;
89582  CollSeq *pColl = 0;
89583  Expr *p = pExpr;
89584  while( p ){
89585    int op = p->op;
89586    if( p->flags & EP_Generic ) break;
89587    if( op==TK_CAST || op==TK_UPLUS ){
89588      p = p->pLeft;
89589      continue;
89590    }
89591    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
89592      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
89593      break;
89594    }
89595    if( (op==TK_AGG_COLUMN || op==TK_COLUMN
89596          || op==TK_REGISTER || op==TK_TRIGGER)
89597     && p->pTab!=0
89598    ){
89599      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
89600      ** a TK_COLUMN but was previously evaluated and cached in a register */
89601      int j = p->iColumn;
89602      if( j>=0 ){
89603        const char *zColl = p->pTab->aCol[j].zColl;
89604        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89605      }
89606      break;
89607    }
89608    if( p->flags & EP_Collate ){
89609      if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
89610        p = p->pLeft;
89611      }else{
89612        Expr *pNext  = p->pRight;
89613        /* The Expr.x union is never used at the same time as Expr.pRight */
89614        assert( p->x.pList==0 || p->pRight==0 );
89615        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
89616        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
89617        ** least one EP_Collate. Thus the following two ALWAYS. */
89618        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
89619          int i;
89620          for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
89621            if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
89622              pNext = p->x.pList->a[i].pExpr;
89623              break;
89624            }
89625          }
89626        }
89627        p = pNext;
89628      }
89629    }else{
89630      break;
89631    }
89632  }
89633  if( sqlite3CheckCollSeq(pParse, pColl) ){
89634    pColl = 0;
89635  }
89636  return pColl;
89637}
89638
89639/*
89640** pExpr is an operand of a comparison operator.  aff2 is the
89641** type affinity of the other operand.  This routine returns the
89642** type affinity that should be used for the comparison operator.
89643*/
89644SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
89645  char aff1 = sqlite3ExprAffinity(pExpr);
89646  if( aff1 && aff2 ){
89647    /* Both sides of the comparison are columns. If one has numeric
89648    ** affinity, use that. Otherwise use no affinity.
89649    */
89650    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
89651      return SQLITE_AFF_NUMERIC;
89652    }else{
89653      return SQLITE_AFF_BLOB;
89654    }
89655  }else if( !aff1 && !aff2 ){
89656    /* Neither side of the comparison is a column.  Compare the
89657    ** results directly.
89658    */
89659    return SQLITE_AFF_BLOB;
89660  }else{
89661    /* One side is a column, the other is not. Use the columns affinity. */
89662    assert( aff1==0 || aff2==0 );
89663    return (aff1 + aff2);
89664  }
89665}
89666
89667/*
89668** pExpr is a comparison operator.  Return the type affinity that should
89669** be applied to both operands prior to doing the comparison.
89670*/
89671static char comparisonAffinity(Expr *pExpr){
89672  char aff;
89673  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
89674          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
89675          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
89676  assert( pExpr->pLeft );
89677  aff = sqlite3ExprAffinity(pExpr->pLeft);
89678  if( pExpr->pRight ){
89679    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
89680  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89681    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
89682  }else if( !aff ){
89683    aff = SQLITE_AFF_BLOB;
89684  }
89685  return aff;
89686}
89687
89688/*
89689** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
89690** idx_affinity is the affinity of an indexed column. Return true
89691** if the index with affinity idx_affinity may be used to implement
89692** the comparison in pExpr.
89693*/
89694SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
89695  char aff = comparisonAffinity(pExpr);
89696  switch( aff ){
89697    case SQLITE_AFF_BLOB:
89698      return 1;
89699    case SQLITE_AFF_TEXT:
89700      return idx_affinity==SQLITE_AFF_TEXT;
89701    default:
89702      return sqlite3IsNumericAffinity(idx_affinity);
89703  }
89704}
89705
89706/*
89707** Return the P5 value that should be used for a binary comparison
89708** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
89709*/
89710static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
89711  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
89712  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
89713  return aff;
89714}
89715
89716/*
89717** Return a pointer to the collation sequence that should be used by
89718** a binary comparison operator comparing pLeft and pRight.
89719**
89720** If the left hand expression has a collating sequence type, then it is
89721** used. Otherwise the collation sequence for the right hand expression
89722** is used, or the default (BINARY) if neither expression has a collating
89723** type.
89724**
89725** Argument pRight (but not pLeft) may be a null pointer. In this case,
89726** it is not considered.
89727*/
89728SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
89729  Parse *pParse,
89730  Expr *pLeft,
89731  Expr *pRight
89732){
89733  CollSeq *pColl;
89734  assert( pLeft );
89735  if( pLeft->flags & EP_Collate ){
89736    pColl = sqlite3ExprCollSeq(pParse, pLeft);
89737  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
89738    pColl = sqlite3ExprCollSeq(pParse, pRight);
89739  }else{
89740    pColl = sqlite3ExprCollSeq(pParse, pLeft);
89741    if( !pColl ){
89742      pColl = sqlite3ExprCollSeq(pParse, pRight);
89743    }
89744  }
89745  return pColl;
89746}
89747
89748/*
89749** Generate code for a comparison operator.
89750*/
89751static int codeCompare(
89752  Parse *pParse,    /* The parsing (and code generating) context */
89753  Expr *pLeft,      /* The left operand */
89754  Expr *pRight,     /* The right operand */
89755  int opcode,       /* The comparison opcode */
89756  int in1, int in2, /* Register holding operands */
89757  int dest,         /* Jump here if true.  */
89758  int jumpIfNull    /* If true, jump if either operand is NULL */
89759){
89760  int p5;
89761  int addr;
89762  CollSeq *p4;
89763
89764  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
89765  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
89766  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
89767                           (void*)p4, P4_COLLSEQ);
89768  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
89769  return addr;
89770}
89771
89772#if SQLITE_MAX_EXPR_DEPTH>0
89773/*
89774** Check that argument nHeight is less than or equal to the maximum
89775** expression depth allowed. If it is not, leave an error message in
89776** pParse.
89777*/
89778SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
89779  int rc = SQLITE_OK;
89780  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
89781  if( nHeight>mxHeight ){
89782    sqlite3ErrorMsg(pParse,
89783       "Expression tree is too large (maximum depth %d)", mxHeight
89784    );
89785    rc = SQLITE_ERROR;
89786  }
89787  return rc;
89788}
89789
89790/* The following three functions, heightOfExpr(), heightOfExprList()
89791** and heightOfSelect(), are used to determine the maximum height
89792** of any expression tree referenced by the structure passed as the
89793** first argument.
89794**
89795** If this maximum height is greater than the current value pointed
89796** to by pnHeight, the second parameter, then set *pnHeight to that
89797** value.
89798*/
89799static void heightOfExpr(Expr *p, int *pnHeight){
89800  if( p ){
89801    if( p->nHeight>*pnHeight ){
89802      *pnHeight = p->nHeight;
89803    }
89804  }
89805}
89806static void heightOfExprList(ExprList *p, int *pnHeight){
89807  if( p ){
89808    int i;
89809    for(i=0; i<p->nExpr; i++){
89810      heightOfExpr(p->a[i].pExpr, pnHeight);
89811    }
89812  }
89813}
89814static void heightOfSelect(Select *p, int *pnHeight){
89815  if( p ){
89816    heightOfExpr(p->pWhere, pnHeight);
89817    heightOfExpr(p->pHaving, pnHeight);
89818    heightOfExpr(p->pLimit, pnHeight);
89819    heightOfExpr(p->pOffset, pnHeight);
89820    heightOfExprList(p->pEList, pnHeight);
89821    heightOfExprList(p->pGroupBy, pnHeight);
89822    heightOfExprList(p->pOrderBy, pnHeight);
89823    heightOfSelect(p->pPrior, pnHeight);
89824  }
89825}
89826
89827/*
89828** Set the Expr.nHeight variable in the structure passed as an
89829** argument. An expression with no children, Expr.pList or
89830** Expr.pSelect member has a height of 1. Any other expression
89831** has a height equal to the maximum height of any other
89832** referenced Expr plus one.
89833**
89834** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
89835** if appropriate.
89836*/
89837static void exprSetHeight(Expr *p){
89838  int nHeight = 0;
89839  heightOfExpr(p->pLeft, &nHeight);
89840  heightOfExpr(p->pRight, &nHeight);
89841  if( ExprHasProperty(p, EP_xIsSelect) ){
89842    heightOfSelect(p->x.pSelect, &nHeight);
89843  }else if( p->x.pList ){
89844    heightOfExprList(p->x.pList, &nHeight);
89845    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
89846  }
89847  p->nHeight = nHeight + 1;
89848}
89849
89850/*
89851** Set the Expr.nHeight variable using the exprSetHeight() function. If
89852** the height is greater than the maximum allowed expression depth,
89853** leave an error in pParse.
89854**
89855** Also 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( pParse->nErr ) return;
89860  exprSetHeight(p);
89861  sqlite3ExprCheckHeight(pParse, p->nHeight);
89862}
89863
89864/*
89865** Return the maximum height of any expression tree referenced
89866** by the select statement passed as an argument.
89867*/
89868SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
89869  int nHeight = 0;
89870  heightOfSelect(p, &nHeight);
89871  return nHeight;
89872}
89873#else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
89874/*
89875** Propagate all EP_Propagate flags from the Expr.x.pList into
89876** Expr.flags.
89877*/
89878SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
89879  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
89880    p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
89881  }
89882}
89883#define exprSetHeight(y)
89884#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
89885
89886/*
89887** This routine is the core allocator for Expr nodes.
89888**
89889** Construct a new expression node and return a pointer to it.  Memory
89890** for this node and for the pToken argument is a single allocation
89891** obtained from sqlite3DbMalloc().  The calling function
89892** is responsible for making sure the node eventually gets freed.
89893**
89894** If dequote is true, then the token (if it exists) is dequoted.
89895** If dequote is false, no dequoting is performed.  The deQuote
89896** parameter is ignored if pToken is NULL or if the token does not
89897** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
89898** then the EP_DblQuoted flag is set on the expression node.
89899**
89900** Special case:  If op==TK_INTEGER and pToken points to a string that
89901** can be translated into a 32-bit integer, then the token is not
89902** stored in u.zToken.  Instead, the integer values is written
89903** into u.iValue and the EP_IntValue flag is set.  No extra storage
89904** is allocated to hold the integer text and the dequote flag is ignored.
89905*/
89906SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
89907  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
89908  int op,                 /* Expression opcode */
89909  const Token *pToken,    /* Token argument.  Might be NULL */
89910  int dequote             /* True to dequote */
89911){
89912  Expr *pNew;
89913  int nExtra = 0;
89914  int iValue = 0;
89915
89916  assert( db!=0 );
89917  if( pToken ){
89918    if( op!=TK_INTEGER || pToken->z==0
89919          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
89920      nExtra = pToken->n+1;
89921      assert( iValue>=0 );
89922    }
89923  }
89924  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
89925  if( pNew ){
89926    memset(pNew, 0, sizeof(Expr));
89927    pNew->op = (u8)op;
89928    pNew->iAgg = -1;
89929    if( pToken ){
89930      if( nExtra==0 ){
89931        pNew->flags |= EP_IntValue;
89932        pNew->u.iValue = iValue;
89933      }else{
89934        pNew->u.zToken = (char*)&pNew[1];
89935        assert( pToken->z!=0 || pToken->n==0 );
89936        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
89937        pNew->u.zToken[pToken->n] = 0;
89938        if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
89939          if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
89940          sqlite3Dequote(pNew->u.zToken);
89941        }
89942      }
89943    }
89944#if SQLITE_MAX_EXPR_DEPTH>0
89945    pNew->nHeight = 1;
89946#endif
89947  }
89948  return pNew;
89949}
89950
89951/*
89952** Allocate a new expression node from a zero-terminated token that has
89953** already been dequoted.
89954*/
89955SQLITE_PRIVATE Expr *sqlite3Expr(
89956  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
89957  int op,                 /* Expression opcode */
89958  const char *zToken      /* Token argument.  Might be NULL */
89959){
89960  Token x;
89961  x.z = zToken;
89962  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
89963  return sqlite3ExprAlloc(db, op, &x, 0);
89964}
89965
89966/*
89967** Attach subtrees pLeft and pRight to the Expr node pRoot.
89968**
89969** If pRoot==NULL that means that a memory allocation error has occurred.
89970** In that case, delete the subtrees pLeft and pRight.
89971*/
89972SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
89973  sqlite3 *db,
89974  Expr *pRoot,
89975  Expr *pLeft,
89976  Expr *pRight
89977){
89978  if( pRoot==0 ){
89979    assert( db->mallocFailed );
89980    sqlite3ExprDelete(db, pLeft);
89981    sqlite3ExprDelete(db, pRight);
89982  }else{
89983    if( pRight ){
89984      pRoot->pRight = pRight;
89985      pRoot->flags |= EP_Propagate & pRight->flags;
89986    }
89987    if( pLeft ){
89988      pRoot->pLeft = pLeft;
89989      pRoot->flags |= EP_Propagate & pLeft->flags;
89990    }
89991    exprSetHeight(pRoot);
89992  }
89993}
89994
89995/*
89996** Allocate an Expr node which joins as many as two subtrees.
89997**
89998** One or both of the subtrees can be NULL.  Return a pointer to the new
89999** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
90000** free the subtrees and return NULL.
90001*/
90002SQLITE_PRIVATE Expr *sqlite3PExpr(
90003  Parse *pParse,          /* Parsing context */
90004  int op,                 /* Expression opcode */
90005  Expr *pLeft,            /* Left operand */
90006  Expr *pRight,           /* Right operand */
90007  const Token *pToken     /* Argument token */
90008){
90009  Expr *p;
90010  if( op==TK_AND && pParse->nErr==0 ){
90011    /* Take advantage of short-circuit false optimization for AND */
90012    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
90013  }else{
90014    p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
90015    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
90016  }
90017  if( p ) {
90018    sqlite3ExprCheckHeight(pParse, p->nHeight);
90019  }
90020  return p;
90021}
90022
90023/*
90024** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
90025** do a memory allocation failure) then delete the pSelect object.
90026*/
90027SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
90028  if( pExpr ){
90029    pExpr->x.pSelect = pSelect;
90030    ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
90031    sqlite3ExprSetHeightAndFlags(pParse, pExpr);
90032  }else{
90033    assert( pParse->db->mallocFailed );
90034    sqlite3SelectDelete(pParse->db, pSelect);
90035  }
90036}
90037
90038
90039/*
90040** If the expression is always either TRUE or FALSE (respectively),
90041** then return 1.  If one cannot determine the truth value of the
90042** expression at compile-time return 0.
90043**
90044** This is an optimization.  If is OK to return 0 here even if
90045** the expression really is always false or false (a false negative).
90046** But it is a bug to return 1 if the expression might have different
90047** boolean values in different circumstances (a false positive.)
90048**
90049** Note that if the expression is part of conditional for a
90050** LEFT JOIN, then we cannot determine at compile-time whether or not
90051** is it true or false, so always return 0.
90052*/
90053static int exprAlwaysTrue(Expr *p){
90054  int v = 0;
90055  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90056  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90057  return v!=0;
90058}
90059static int exprAlwaysFalse(Expr *p){
90060  int v = 0;
90061  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90062  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90063  return v==0;
90064}
90065
90066/*
90067** Join two expressions using an AND operator.  If either expression is
90068** NULL, then just return the other expression.
90069**
90070** If one side or the other of the AND is known to be false, then instead
90071** of returning an AND expression, just return a constant expression with
90072** a value of false.
90073*/
90074SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
90075  if( pLeft==0 ){
90076    return pRight;
90077  }else if( pRight==0 ){
90078    return pLeft;
90079  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
90080    sqlite3ExprDelete(db, pLeft);
90081    sqlite3ExprDelete(db, pRight);
90082    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
90083  }else{
90084    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
90085    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
90086    return pNew;
90087  }
90088}
90089
90090/*
90091** Construct a new expression node for a function with multiple
90092** arguments.
90093*/
90094SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
90095  Expr *pNew;
90096  sqlite3 *db = pParse->db;
90097  assert( pToken );
90098  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
90099  if( pNew==0 ){
90100    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
90101    return 0;
90102  }
90103  pNew->x.pList = pList;
90104  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
90105  sqlite3ExprSetHeightAndFlags(pParse, pNew);
90106  return pNew;
90107}
90108
90109/*
90110** Assign a variable number to an expression that encodes a wildcard
90111** in the original SQL statement.
90112**
90113** Wildcards consisting of a single "?" are assigned the next sequential
90114** variable number.
90115**
90116** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
90117** sure "nnn" is not too be to avoid a denial of service attack when
90118** the SQL statement comes from an external source.
90119**
90120** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
90121** as the previous instance of the same wildcard.  Or if this is the first
90122** instance of the wildcard, the next sequential variable number is
90123** assigned.
90124*/
90125SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
90126  sqlite3 *db = pParse->db;
90127  const char *z;
90128
90129  if( pExpr==0 ) return;
90130  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
90131  z = pExpr->u.zToken;
90132  assert( z!=0 );
90133  assert( z[0]!=0 );
90134  if( z[1]==0 ){
90135    /* Wildcard of the form "?".  Assign the next variable number */
90136    assert( z[0]=='?' );
90137    pExpr->iColumn = (ynVar)(++pParse->nVar);
90138  }else{
90139    ynVar x = 0;
90140    u32 n = sqlite3Strlen30(z);
90141    if( z[0]=='?' ){
90142      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
90143      ** use it as the variable number */
90144      i64 i;
90145      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
90146      pExpr->iColumn = x = (ynVar)i;
90147      testcase( i==0 );
90148      testcase( i==1 );
90149      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
90150      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
90151      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90152        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
90153            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
90154        x = 0;
90155      }
90156      if( i>pParse->nVar ){
90157        pParse->nVar = (int)i;
90158      }
90159    }else{
90160      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
90161      ** number as the prior appearance of the same name, or if the name
90162      ** has never appeared before, reuse the same variable number
90163      */
90164      ynVar i;
90165      for(i=0; i<pParse->nzVar; i++){
90166        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
90167          pExpr->iColumn = x = (ynVar)i+1;
90168          break;
90169        }
90170      }
90171      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
90172    }
90173    if( x>0 ){
90174      if( x>pParse->nzVar ){
90175        char **a;
90176        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
90177        if( a==0 ){
90178          assert( db->mallocFailed ); /* Error reported through mallocFailed */
90179          return;
90180        }
90181        pParse->azVar = a;
90182        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
90183        pParse->nzVar = x;
90184      }
90185      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
90186        sqlite3DbFree(db, pParse->azVar[x-1]);
90187        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
90188      }
90189    }
90190  }
90191  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90192    sqlite3ErrorMsg(pParse, "too many SQL variables");
90193  }
90194}
90195
90196/*
90197** Recursively delete an expression tree.
90198*/
90199static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
90200  assert( p!=0 );
90201  /* Sanity check: Assert that the IntValue is non-negative if it exists */
90202  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
90203  if( !ExprHasProperty(p, EP_TokenOnly) ){
90204    /* The Expr.x union is never used at the same time as Expr.pRight */
90205    assert( p->x.pList==0 || p->pRight==0 );
90206    sqlite3ExprDelete(db, p->pLeft);
90207    sqlite3ExprDelete(db, p->pRight);
90208    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
90209    if( ExprHasProperty(p, EP_xIsSelect) ){
90210      sqlite3SelectDelete(db, p->x.pSelect);
90211    }else{
90212      sqlite3ExprListDelete(db, p->x.pList);
90213    }
90214  }
90215  if( !ExprHasProperty(p, EP_Static) ){
90216    sqlite3DbFree(db, p);
90217  }
90218}
90219SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
90220  if( p ) sqlite3ExprDeleteNN(db, p);
90221}
90222
90223/*
90224** Return the number of bytes allocated for the expression structure
90225** passed as the first argument. This is always one of EXPR_FULLSIZE,
90226** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
90227*/
90228static int exprStructSize(Expr *p){
90229  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
90230  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
90231  return EXPR_FULLSIZE;
90232}
90233
90234/*
90235** The dupedExpr*Size() routines each return the number of bytes required
90236** to store a copy of an expression or expression tree.  They differ in
90237** how much of the tree is measured.
90238**
90239**     dupedExprStructSize()     Size of only the Expr structure
90240**     dupedExprNodeSize()       Size of Expr + space for token
90241**     dupedExprSize()           Expr + token + subtree components
90242**
90243***************************************************************************
90244**
90245** The dupedExprStructSize() function returns two values OR-ed together:
90246** (1) the space required for a copy of the Expr structure only and
90247** (2) the EP_xxx flags that indicate what the structure size should be.
90248** The return values is always one of:
90249**
90250**      EXPR_FULLSIZE
90251**      EXPR_REDUCEDSIZE   | EP_Reduced
90252**      EXPR_TOKENONLYSIZE | EP_TokenOnly
90253**
90254** The size of the structure can be found by masking the return value
90255** of this routine with 0xfff.  The flags can be found by masking the
90256** return value with EP_Reduced|EP_TokenOnly.
90257**
90258** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
90259** (unreduced) Expr objects as they or originally constructed by the parser.
90260** During expression analysis, extra information is computed and moved into
90261** later parts of teh Expr object and that extra information might get chopped
90262** off if the expression is reduced.  Note also that it does not work to
90263** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
90264** to reduce a pristine expression tree from the parser.  The implementation
90265** of dupedExprStructSize() contain multiple assert() statements that attempt
90266** to enforce this constraint.
90267*/
90268static int dupedExprStructSize(Expr *p, int flags){
90269  int nSize;
90270  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
90271  assert( EXPR_FULLSIZE<=0xfff );
90272  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
90273  if( 0==flags ){
90274    nSize = EXPR_FULLSIZE;
90275  }else{
90276    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
90277    assert( !ExprHasProperty(p, EP_FromJoin) );
90278    assert( !ExprHasProperty(p, EP_MemToken) );
90279    assert( !ExprHasProperty(p, EP_NoReduce) );
90280    if( p->pLeft || p->x.pList ){
90281      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
90282    }else{
90283      assert( p->pRight==0 );
90284      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
90285    }
90286  }
90287  return nSize;
90288}
90289
90290/*
90291** This function returns the space in bytes required to store the copy
90292** of the Expr structure and a copy of the Expr.u.zToken string (if that
90293** string is defined.)
90294*/
90295static int dupedExprNodeSize(Expr *p, int flags){
90296  int nByte = dupedExprStructSize(p, flags) & 0xfff;
90297  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90298    nByte += sqlite3Strlen30(p->u.zToken)+1;
90299  }
90300  return ROUND8(nByte);
90301}
90302
90303/*
90304** Return the number of bytes required to create a duplicate of the
90305** expression passed as the first argument. The second argument is a
90306** mask containing EXPRDUP_XXX flags.
90307**
90308** The value returned includes space to create a copy of the Expr struct
90309** itself and the buffer referred to by Expr.u.zToken, if any.
90310**
90311** If the EXPRDUP_REDUCE flag is set, then the return value includes
90312** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
90313** and Expr.pRight variables (but not for any structures pointed to or
90314** descended from the Expr.x.pList or Expr.x.pSelect variables).
90315*/
90316static int dupedExprSize(Expr *p, int flags){
90317  int nByte = 0;
90318  if( p ){
90319    nByte = dupedExprNodeSize(p, flags);
90320    if( flags&EXPRDUP_REDUCE ){
90321      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
90322    }
90323  }
90324  return nByte;
90325}
90326
90327/*
90328** This function is similar to sqlite3ExprDup(), except that if pzBuffer
90329** is not NULL then *pzBuffer is assumed to point to a buffer large enough
90330** to store the copy of expression p, the copies of p->u.zToken
90331** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
90332** if any. Before returning, *pzBuffer is set to the first byte past the
90333** portion of the buffer copied into by this function.
90334*/
90335static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
90336  Expr *pNew;           /* Value to return */
90337  u8 *zAlloc;           /* Memory space from which to build Expr object */
90338  u32 staticFlag;       /* EP_Static if space not obtained from malloc */
90339
90340  assert( db!=0 );
90341  assert( p );
90342  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
90343  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
90344
90345  /* Figure out where to write the new Expr structure. */
90346  if( pzBuffer ){
90347    zAlloc = *pzBuffer;
90348    staticFlag = EP_Static;
90349  }else{
90350    zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
90351    staticFlag = 0;
90352  }
90353  pNew = (Expr *)zAlloc;
90354
90355  if( pNew ){
90356    /* Set nNewSize to the size allocated for the structure pointed to
90357    ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
90358    ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
90359    ** by the copy of the p->u.zToken string (if any).
90360    */
90361    const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
90362    const int nNewSize = nStructSize & 0xfff;
90363    int nToken;
90364    if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90365      nToken = sqlite3Strlen30(p->u.zToken) + 1;
90366    }else{
90367      nToken = 0;
90368    }
90369    if( dupFlags ){
90370      assert( ExprHasProperty(p, EP_Reduced)==0 );
90371      memcpy(zAlloc, p, nNewSize);
90372    }else{
90373      u32 nSize = (u32)exprStructSize(p);
90374      memcpy(zAlloc, p, nSize);
90375      if( nSize<EXPR_FULLSIZE ){
90376        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
90377      }
90378    }
90379
90380    /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
90381    pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
90382    pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
90383    pNew->flags |= staticFlag;
90384
90385    /* Copy the p->u.zToken string, if any. */
90386    if( nToken ){
90387      char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
90388      memcpy(zToken, p->u.zToken, nToken);
90389    }
90390
90391    if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
90392      /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
90393      if( ExprHasProperty(p, EP_xIsSelect) ){
90394        pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
90395      }else{
90396        pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
90397      }
90398    }
90399
90400    /* Fill in pNew->pLeft and pNew->pRight. */
90401    if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
90402      zAlloc += dupedExprNodeSize(p, dupFlags);
90403      if( ExprHasProperty(pNew, EP_Reduced) ){
90404        pNew->pLeft = p->pLeft ?
90405                      exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
90406        pNew->pRight = p->pRight ?
90407                       exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
90408      }
90409      if( pzBuffer ){
90410        *pzBuffer = zAlloc;
90411      }
90412    }else{
90413      if( !ExprHasProperty(p, EP_TokenOnly) ){
90414        pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
90415        pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
90416      }
90417    }
90418  }
90419  return pNew;
90420}
90421
90422/*
90423** Create and return a deep copy of the object passed as the second
90424** argument. If an OOM condition is encountered, NULL is returned
90425** and the db->mallocFailed flag set.
90426*/
90427#ifndef SQLITE_OMIT_CTE
90428static With *withDup(sqlite3 *db, With *p){
90429  With *pRet = 0;
90430  if( p ){
90431    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
90432    pRet = sqlite3DbMallocZero(db, nByte);
90433    if( pRet ){
90434      int i;
90435      pRet->nCte = p->nCte;
90436      for(i=0; i<p->nCte; i++){
90437        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
90438        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
90439        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
90440      }
90441    }
90442  }
90443  return pRet;
90444}
90445#else
90446# define withDup(x,y) 0
90447#endif
90448
90449/*
90450** The following group of routines make deep copies of expressions,
90451** expression lists, ID lists, and select statements.  The copies can
90452** be deleted (by being passed to their respective ...Delete() routines)
90453** without effecting the originals.
90454**
90455** The expression list, ID, and source lists return by sqlite3ExprListDup(),
90456** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
90457** by subsequent calls to sqlite*ListAppend() routines.
90458**
90459** Any tables that the SrcList might point to are not duplicated.
90460**
90461** The flags parameter contains a combination of the EXPRDUP_XXX flags.
90462** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
90463** truncated version of the usual Expr structure that will be stored as
90464** part of the in-memory representation of the database schema.
90465*/
90466SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
90467  assert( flags==0 || flags==EXPRDUP_REDUCE );
90468  return p ? exprDup(db, p, flags, 0) : 0;
90469}
90470SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
90471  ExprList *pNew;
90472  struct ExprList_item *pItem, *pOldItem;
90473  int i;
90474  assert( db!=0 );
90475  if( p==0 ) return 0;
90476  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
90477  if( pNew==0 ) return 0;
90478  pNew->nExpr = i = p->nExpr;
90479  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
90480  pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
90481  if( pItem==0 ){
90482    sqlite3DbFree(db, pNew);
90483    return 0;
90484  }
90485  pOldItem = p->a;
90486  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
90487    Expr *pOldExpr = pOldItem->pExpr;
90488    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
90489    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90490    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
90491    pItem->sortOrder = pOldItem->sortOrder;
90492    pItem->done = 0;
90493    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
90494    pItem->u = pOldItem->u;
90495  }
90496  return pNew;
90497}
90498
90499/*
90500** If cursors, triggers, views and subqueries are all omitted from
90501** the build, then none of the following routines, except for
90502** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
90503** called with a NULL argument.
90504*/
90505#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
90506 || !defined(SQLITE_OMIT_SUBQUERY)
90507SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
90508  SrcList *pNew;
90509  int i;
90510  int nByte;
90511  assert( db!=0 );
90512  if( p==0 ) return 0;
90513  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
90514  pNew = sqlite3DbMallocRawNN(db, nByte );
90515  if( pNew==0 ) return 0;
90516  pNew->nSrc = pNew->nAlloc = p->nSrc;
90517  for(i=0; i<p->nSrc; i++){
90518    struct SrcList_item *pNewItem = &pNew->a[i];
90519    struct SrcList_item *pOldItem = &p->a[i];
90520    Table *pTab;
90521    pNewItem->pSchema = pOldItem->pSchema;
90522    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
90523    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90524    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
90525    pNewItem->fg = pOldItem->fg;
90526    pNewItem->iCursor = pOldItem->iCursor;
90527    pNewItem->addrFillSub = pOldItem->addrFillSub;
90528    pNewItem->regReturn = pOldItem->regReturn;
90529    if( pNewItem->fg.isIndexedBy ){
90530      pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
90531    }
90532    pNewItem->pIBIndex = pOldItem->pIBIndex;
90533    if( pNewItem->fg.isTabFunc ){
90534      pNewItem->u1.pFuncArg =
90535          sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
90536    }
90537    pTab = pNewItem->pTab = pOldItem->pTab;
90538    if( pTab ){
90539      pTab->nRef++;
90540    }
90541    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
90542    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
90543    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
90544    pNewItem->colUsed = pOldItem->colUsed;
90545  }
90546  return pNew;
90547}
90548SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
90549  IdList *pNew;
90550  int i;
90551  assert( db!=0 );
90552  if( p==0 ) return 0;
90553  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
90554  if( pNew==0 ) return 0;
90555  pNew->nId = p->nId;
90556  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
90557  if( pNew->a==0 ){
90558    sqlite3DbFree(db, pNew);
90559    return 0;
90560  }
90561  /* Note that because the size of the allocation for p->a[] is not
90562  ** necessarily a power of two, sqlite3IdListAppend() may not be called
90563  ** on the duplicate created by this function. */
90564  for(i=0; i<p->nId; i++){
90565    struct IdList_item *pNewItem = &pNew->a[i];
90566    struct IdList_item *pOldItem = &p->a[i];
90567    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90568    pNewItem->idx = pOldItem->idx;
90569  }
90570  return pNew;
90571}
90572SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90573  Select *pNew, *pPrior;
90574  assert( db!=0 );
90575  if( p==0 ) return 0;
90576  pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
90577  if( pNew==0 ) return 0;
90578  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
90579  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
90580  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
90581  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
90582  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
90583  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
90584  pNew->op = p->op;
90585  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
90586  if( pPrior ) pPrior->pNext = pNew;
90587  pNew->pNext = 0;
90588  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
90589  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
90590  pNew->iLimit = 0;
90591  pNew->iOffset = 0;
90592  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
90593  pNew->addrOpenEphm[0] = -1;
90594  pNew->addrOpenEphm[1] = -1;
90595  pNew->nSelectRow = p->nSelectRow;
90596  pNew->pWith = withDup(db, p->pWith);
90597  sqlite3SelectSetName(pNew, p->zSelName);
90598  return pNew;
90599}
90600#else
90601SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90602  assert( p==0 );
90603  return 0;
90604}
90605#endif
90606
90607
90608/*
90609** Add a new element to the end of an expression list.  If pList is
90610** initially NULL, then create a new expression list.
90611**
90612** If a memory allocation error occurs, the entire list is freed and
90613** NULL is returned.  If non-NULL is returned, then it is guaranteed
90614** that the new entry was successfully appended.
90615*/
90616SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
90617  Parse *pParse,          /* Parsing context */
90618  ExprList *pList,        /* List to which to append. Might be NULL */
90619  Expr *pExpr             /* Expression to be appended. Might be NULL */
90620){
90621  sqlite3 *db = pParse->db;
90622  assert( db!=0 );
90623  if( pList==0 ){
90624    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
90625    if( pList==0 ){
90626      goto no_mem;
90627    }
90628    pList->nExpr = 0;
90629    pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
90630    if( pList->a==0 ) goto no_mem;
90631  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
90632    struct ExprList_item *a;
90633    assert( pList->nExpr>0 );
90634    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
90635    if( a==0 ){
90636      goto no_mem;
90637    }
90638    pList->a = a;
90639  }
90640  assert( pList->a!=0 );
90641  if( 1 ){
90642    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
90643    memset(pItem, 0, sizeof(*pItem));
90644    pItem->pExpr = pExpr;
90645  }
90646  return pList;
90647
90648no_mem:
90649  /* Avoid leaking memory if malloc has failed. */
90650  sqlite3ExprDelete(db, pExpr);
90651  sqlite3ExprListDelete(db, pList);
90652  return 0;
90653}
90654
90655/*
90656** Set the sort order for the last element on the given ExprList.
90657*/
90658SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
90659  if( p==0 ) return;
90660  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
90661  assert( p->nExpr>0 );
90662  if( iSortOrder<0 ){
90663    assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
90664    return;
90665  }
90666  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
90667}
90668
90669/*
90670** Set the ExprList.a[].zName element of the most recently added item
90671** on the expression list.
90672**
90673** pList might be NULL following an OOM error.  But pName should never be
90674** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
90675** is set.
90676*/
90677SQLITE_PRIVATE void sqlite3ExprListSetName(
90678  Parse *pParse,          /* Parsing context */
90679  ExprList *pList,        /* List to which to add the span. */
90680  Token *pName,           /* Name to be added */
90681  int dequote             /* True to cause the name to be dequoted */
90682){
90683  assert( pList!=0 || pParse->db->mallocFailed!=0 );
90684  if( pList ){
90685    struct ExprList_item *pItem;
90686    assert( pList->nExpr>0 );
90687    pItem = &pList->a[pList->nExpr-1];
90688    assert( pItem->zName==0 );
90689    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
90690    if( dequote ) sqlite3Dequote(pItem->zName);
90691  }
90692}
90693
90694/*
90695** Set the ExprList.a[].zSpan element of the most recently added item
90696** on the expression list.
90697**
90698** pList might be NULL following an OOM error.  But pSpan should never be
90699** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
90700** is set.
90701*/
90702SQLITE_PRIVATE void sqlite3ExprListSetSpan(
90703  Parse *pParse,          /* Parsing context */
90704  ExprList *pList,        /* List to which to add the span. */
90705  ExprSpan *pSpan         /* The span to be added */
90706){
90707  sqlite3 *db = pParse->db;
90708  assert( pList!=0 || db->mallocFailed!=0 );
90709  if( pList ){
90710    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
90711    assert( pList->nExpr>0 );
90712    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
90713    sqlite3DbFree(db, pItem->zSpan);
90714    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
90715                                    (int)(pSpan->zEnd - pSpan->zStart));
90716  }
90717}
90718
90719/*
90720** If the expression list pEList contains more than iLimit elements,
90721** leave an error message in pParse.
90722*/
90723SQLITE_PRIVATE void sqlite3ExprListCheckLength(
90724  Parse *pParse,
90725  ExprList *pEList,
90726  const char *zObject
90727){
90728  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
90729  testcase( pEList && pEList->nExpr==mx );
90730  testcase( pEList && pEList->nExpr==mx+1 );
90731  if( pEList && pEList->nExpr>mx ){
90732    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
90733  }
90734}
90735
90736/*
90737** Delete an entire expression list.
90738*/
90739static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
90740  int i;
90741  struct ExprList_item *pItem;
90742  assert( pList->a!=0 || pList->nExpr==0 );
90743  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
90744    sqlite3ExprDelete(db, pItem->pExpr);
90745    sqlite3DbFree(db, pItem->zName);
90746    sqlite3DbFree(db, pItem->zSpan);
90747  }
90748  sqlite3DbFree(db, pList->a);
90749  sqlite3DbFree(db, pList);
90750}
90751SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
90752  if( pList ) exprListDeleteNN(db, pList);
90753}
90754
90755/*
90756** Return the bitwise-OR of all Expr.flags fields in the given
90757** ExprList.
90758*/
90759SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
90760  int i;
90761  u32 m = 0;
90762  if( pList ){
90763    for(i=0; i<pList->nExpr; i++){
90764       Expr *pExpr = pList->a[i].pExpr;
90765       assert( pExpr!=0 );
90766       m |= pExpr->flags;
90767    }
90768  }
90769  return m;
90770}
90771
90772/*
90773** These routines are Walker callbacks used to check expressions to
90774** see if they are "constant" for some definition of constant.  The
90775** Walker.eCode value determines the type of "constant" we are looking
90776** for.
90777**
90778** These callback routines are used to implement the following:
90779**
90780**     sqlite3ExprIsConstant()                  pWalker->eCode==1
90781**     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
90782**     sqlite3ExprIsTableConstant()             pWalker->eCode==3
90783**     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
90784**
90785** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
90786** is found to not be a constant.
90787**
90788** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
90789** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
90790** an existing schema and 4 when processing a new statement.  A bound
90791** parameter raises an error for new statements, but is silently converted
90792** to NULL for existing schemas.  This allows sqlite_master tables that
90793** contain a bound parameter because they were generated by older versions
90794** of SQLite to be parsed by newer versions of SQLite without raising a
90795** malformed schema error.
90796*/
90797static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
90798
90799  /* If pWalker->eCode is 2 then any term of the expression that comes from
90800  ** the ON or USING clauses of a left join disqualifies the expression
90801  ** from being considered constant. */
90802  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
90803    pWalker->eCode = 0;
90804    return WRC_Abort;
90805  }
90806
90807  switch( pExpr->op ){
90808    /* Consider functions to be constant if all their arguments are constant
90809    ** and either pWalker->eCode==4 or 5 or the function has the
90810    ** SQLITE_FUNC_CONST flag. */
90811    case TK_FUNCTION:
90812      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
90813        return WRC_Continue;
90814      }else{
90815        pWalker->eCode = 0;
90816        return WRC_Abort;
90817      }
90818    case TK_ID:
90819    case TK_COLUMN:
90820    case TK_AGG_FUNCTION:
90821    case TK_AGG_COLUMN:
90822      testcase( pExpr->op==TK_ID );
90823      testcase( pExpr->op==TK_COLUMN );
90824      testcase( pExpr->op==TK_AGG_FUNCTION );
90825      testcase( pExpr->op==TK_AGG_COLUMN );
90826      if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
90827        return WRC_Continue;
90828      }else{
90829        pWalker->eCode = 0;
90830        return WRC_Abort;
90831      }
90832    case TK_VARIABLE:
90833      if( pWalker->eCode==5 ){
90834        /* Silently convert bound parameters that appear inside of CREATE
90835        ** statements into a NULL when parsing the CREATE statement text out
90836        ** of the sqlite_master table */
90837        pExpr->op = TK_NULL;
90838      }else if( pWalker->eCode==4 ){
90839        /* A bound parameter in a CREATE statement that originates from
90840        ** sqlite3_prepare() causes an error */
90841        pWalker->eCode = 0;
90842        return WRC_Abort;
90843      }
90844      /* Fall through */
90845    default:
90846      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
90847      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
90848      return WRC_Continue;
90849  }
90850}
90851static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
90852  UNUSED_PARAMETER(NotUsed);
90853  pWalker->eCode = 0;
90854  return WRC_Abort;
90855}
90856static int exprIsConst(Expr *p, int initFlag, int iCur){
90857  Walker w;
90858  memset(&w, 0, sizeof(w));
90859  w.eCode = initFlag;
90860  w.xExprCallback = exprNodeIsConstant;
90861  w.xSelectCallback = selectNodeIsConstant;
90862  w.u.iCur = iCur;
90863  sqlite3WalkExpr(&w, p);
90864  return w.eCode;
90865}
90866
90867/*
90868** Walk an expression tree.  Return non-zero if the expression is constant
90869** and 0 if it involves variables or function calls.
90870**
90871** For the purposes of this function, a double-quoted string (ex: "abc")
90872** is considered a variable but a single-quoted string (ex: 'abc') is
90873** a constant.
90874*/
90875SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
90876  return exprIsConst(p, 1, 0);
90877}
90878
90879/*
90880** Walk an expression tree.  Return non-zero if the expression is constant
90881** that does no originate from the ON or USING clauses of a join.
90882** Return 0 if it involves variables or function calls or terms from
90883** an ON or USING clause.
90884*/
90885SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
90886  return exprIsConst(p, 2, 0);
90887}
90888
90889/*
90890** Walk an expression tree.  Return non-zero if the expression is constant
90891** for any single row of the table with cursor iCur.  In other words, the
90892** expression must not refer to any non-deterministic function nor any
90893** table other than iCur.
90894*/
90895SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
90896  return exprIsConst(p, 3, iCur);
90897}
90898
90899/*
90900** Walk an expression tree.  Return non-zero if the expression is constant
90901** or a function call with constant arguments.  Return and 0 if there
90902** are any variables.
90903**
90904** For the purposes of this function, a double-quoted string (ex: "abc")
90905** is considered a variable but a single-quoted string (ex: 'abc') is
90906** a constant.
90907*/
90908SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
90909  assert( isInit==0 || isInit==1 );
90910  return exprIsConst(p, 4+isInit, 0);
90911}
90912
90913#ifdef SQLITE_ENABLE_CURSOR_HINTS
90914/*
90915** Walk an expression tree.  Return 1 if the expression contains a
90916** subquery of some kind.  Return 0 if there are no subqueries.
90917*/
90918SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
90919  Walker w;
90920  memset(&w, 0, sizeof(w));
90921  w.eCode = 1;
90922  w.xExprCallback = sqlite3ExprWalkNoop;
90923  w.xSelectCallback = selectNodeIsConstant;
90924  sqlite3WalkExpr(&w, p);
90925  return w.eCode==0;
90926}
90927#endif
90928
90929/*
90930** If the expression p codes a constant integer that is small enough
90931** to fit in a 32-bit integer, return 1 and put the value of the integer
90932** in *pValue.  If the expression is not an integer or if it is too big
90933** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
90934*/
90935SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
90936  int rc = 0;
90937
90938  /* If an expression is an integer literal that fits in a signed 32-bit
90939  ** integer, then the EP_IntValue flag will have already been set */
90940  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
90941           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
90942
90943  if( p->flags & EP_IntValue ){
90944    *pValue = p->u.iValue;
90945    return 1;
90946  }
90947  switch( p->op ){
90948    case TK_UPLUS: {
90949      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
90950      break;
90951    }
90952    case TK_UMINUS: {
90953      int v;
90954      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
90955        assert( v!=(-2147483647-1) );
90956        *pValue = -v;
90957        rc = 1;
90958      }
90959      break;
90960    }
90961    default: break;
90962  }
90963  return rc;
90964}
90965
90966/*
90967** Return FALSE if there is no chance that the expression can be NULL.
90968**
90969** If the expression might be NULL or if the expression is too complex
90970** to tell return TRUE.
90971**
90972** This routine is used as an optimization, to skip OP_IsNull opcodes
90973** when we know that a value cannot be NULL.  Hence, a false positive
90974** (returning TRUE when in fact the expression can never be NULL) might
90975** be a small performance hit but is otherwise harmless.  On the other
90976** hand, a false negative (returning FALSE when the result could be NULL)
90977** will likely result in an incorrect answer.  So when in doubt, return
90978** TRUE.
90979*/
90980SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
90981  u8 op;
90982  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
90983  op = p->op;
90984  if( op==TK_REGISTER ) op = p->op2;
90985  switch( op ){
90986    case TK_INTEGER:
90987    case TK_STRING:
90988    case TK_FLOAT:
90989    case TK_BLOB:
90990      return 0;
90991    case TK_COLUMN:
90992      assert( p->pTab!=0 );
90993      return ExprHasProperty(p, EP_CanBeNull) ||
90994             (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
90995    default:
90996      return 1;
90997  }
90998}
90999
91000/*
91001** Return TRUE if the given expression is a constant which would be
91002** unchanged by OP_Affinity with the affinity given in the second
91003** argument.
91004**
91005** This routine is used to determine if the OP_Affinity operation
91006** can be omitted.  When in doubt return FALSE.  A false negative
91007** is harmless.  A false positive, however, can result in the wrong
91008** answer.
91009*/
91010SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
91011  u8 op;
91012  if( aff==SQLITE_AFF_BLOB ) return 1;
91013  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
91014  op = p->op;
91015  if( op==TK_REGISTER ) op = p->op2;
91016  switch( op ){
91017    case TK_INTEGER: {
91018      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
91019    }
91020    case TK_FLOAT: {
91021      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
91022    }
91023    case TK_STRING: {
91024      return aff==SQLITE_AFF_TEXT;
91025    }
91026    case TK_BLOB: {
91027      return 1;
91028    }
91029    case TK_COLUMN: {
91030      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
91031      return p->iColumn<0
91032          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
91033    }
91034    default: {
91035      return 0;
91036    }
91037  }
91038}
91039
91040/*
91041** Return TRUE if the given string is a row-id column name.
91042*/
91043SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
91044  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
91045  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
91046  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
91047  return 0;
91048}
91049
91050/*
91051** pX is the RHS of an IN operator.  If pX is a SELECT statement
91052** that can be simplified to a direct table access, then return
91053** a pointer to the SELECT statement.  If pX is not a SELECT statement,
91054** or if the SELECT statement needs to be manifested into a transient
91055** table, then return NULL.
91056*/
91057#ifndef SQLITE_OMIT_SUBQUERY
91058static Select *isCandidateForInOpt(Expr *pX){
91059  Select *p;
91060  SrcList *pSrc;
91061  ExprList *pEList;
91062  Expr *pRes;
91063  Table *pTab;
91064  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
91065  if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
91066  p = pX->x.pSelect;
91067  if( p->pPrior ) return 0;              /* Not a compound SELECT */
91068  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
91069    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
91070    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
91071    return 0; /* No DISTINCT keyword and no aggregate functions */
91072  }
91073  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
91074  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
91075  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
91076  if( p->pWhere ) return 0;              /* Has no WHERE clause */
91077  pSrc = p->pSrc;
91078  assert( pSrc!=0 );
91079  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
91080  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
91081  pTab = pSrc->a[0].pTab;
91082  assert( pTab!=0 );
91083  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
91084  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
91085  pEList = p->pEList;
91086  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
91087  pRes = pEList->a[0].pExpr;
91088  if( pRes->op!=TK_COLUMN ) return 0;    /* Result is a column */
91089  assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
91090  return p;
91091}
91092#endif /* SQLITE_OMIT_SUBQUERY */
91093
91094/*
91095** Code an OP_Once instruction and allocate space for its flag. Return the
91096** address of the new instruction.
91097*/
91098SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
91099  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
91100  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
91101}
91102
91103/*
91104** Generate code that checks the left-most column of index table iCur to see if
91105** it contains any NULL entries.  Cause the register at regHasNull to be set
91106** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
91107** to be set to NULL if iCur contains one or more NULL values.
91108*/
91109static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
91110  int addr1;
91111  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
91112  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
91113  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
91114  sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
91115  VdbeComment((v, "first_entry_in(%d)", iCur));
91116  sqlite3VdbeJumpHere(v, addr1);
91117}
91118
91119
91120#ifndef SQLITE_OMIT_SUBQUERY
91121/*
91122** The argument is an IN operator with a list (not a subquery) on the
91123** right-hand side.  Return TRUE if that list is constant.
91124*/
91125static int sqlite3InRhsIsConstant(Expr *pIn){
91126  Expr *pLHS;
91127  int res;
91128  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
91129  pLHS = pIn->pLeft;
91130  pIn->pLeft = 0;
91131  res = sqlite3ExprIsConstant(pIn);
91132  pIn->pLeft = pLHS;
91133  return res;
91134}
91135#endif
91136
91137/*
91138** This function is used by the implementation of the IN (...) operator.
91139** The pX parameter is the expression on the RHS of the IN operator, which
91140** might be either a list of expressions or a subquery.
91141**
91142** The job of this routine is to find or create a b-tree object that can
91143** be used either to test for membership in the RHS set or to iterate through
91144** all members of the RHS set, skipping duplicates.
91145**
91146** A cursor is opened on the b-tree object that is the RHS of the IN operator
91147** and pX->iTable is set to the index of that cursor.
91148**
91149** The returned value of this function indicates the b-tree type, as follows:
91150**
91151**   IN_INDEX_ROWID      - The cursor was opened on a database table.
91152**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
91153**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
91154**   IN_INDEX_EPH        - The cursor was opened on a specially created and
91155**                         populated epheremal table.
91156**   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
91157**                         implemented as a sequence of comparisons.
91158**
91159** An existing b-tree might be used if the RHS expression pX is a simple
91160** subquery such as:
91161**
91162**     SELECT <column> FROM <table>
91163**
91164** If the RHS of the IN operator is a list or a more complex subquery, then
91165** an ephemeral table might need to be generated from the RHS and then
91166** pX->iTable made to point to the ephemeral table instead of an
91167** existing table.
91168**
91169** The inFlags parameter must contain exactly one of the bits
91170** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
91171** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
91172** fast membership test.  When the IN_INDEX_LOOP bit is set, the
91173** IN index will be used to loop over all values of the RHS of the
91174** IN operator.
91175**
91176** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
91177** through the set members) then the b-tree must not contain duplicates.
91178** An epheremal table must be used unless the selected <column> is guaranteed
91179** to be unique - either because it is an INTEGER PRIMARY KEY or it
91180** has a UNIQUE constraint or UNIQUE index.
91181**
91182** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
91183** for fast set membership tests) then an epheremal table must
91184** be used unless <column> is an INTEGER PRIMARY KEY or an index can
91185** be found with <column> as its left-most column.
91186**
91187** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
91188** if the RHS of the IN operator is a list (not a subquery) then this
91189** routine might decide that creating an ephemeral b-tree for membership
91190** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
91191** calling routine should implement the IN operator using a sequence
91192** of Eq or Ne comparison operations.
91193**
91194** When the b-tree is being used for membership tests, the calling function
91195** might need to know whether or not the RHS side of the IN operator
91196** contains a NULL.  If prRhsHasNull is not a NULL pointer and
91197** if there is any chance that the (...) might contain a NULL value at
91198** runtime, then a register is allocated and the register number written
91199** to *prRhsHasNull. If there is no chance that the (...) contains a
91200** NULL value, then *prRhsHasNull is left unchanged.
91201**
91202** If a register is allocated and its location stored in *prRhsHasNull, then
91203** the value in that register will be NULL if the b-tree contains one or more
91204** NULL values, and it will be some non-NULL value if the b-tree contains no
91205** NULL values.
91206*/
91207#ifndef SQLITE_OMIT_SUBQUERY
91208SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
91209  Select *p;                            /* SELECT to the right of IN operator */
91210  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
91211  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
91212  int mustBeUnique;                     /* True if RHS must be unique */
91213  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
91214
91215  assert( pX->op==TK_IN );
91216  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
91217
91218  /* Check to see if an existing table or index can be used to
91219  ** satisfy the query.  This is preferable to generating a new
91220  ** ephemeral table.
91221  */
91222  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
91223    sqlite3 *db = pParse->db;              /* Database connection */
91224    Table *pTab;                           /* Table <table>. */
91225    Expr *pExpr;                           /* Expression <column> */
91226    i16 iCol;                              /* Index of column <column> */
91227    i16 iDb;                               /* Database idx for pTab */
91228
91229    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
91230    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
91231    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
91232    pTab = p->pSrc->a[0].pTab;
91233    pExpr = p->pEList->a[0].pExpr;
91234    iCol = (i16)pExpr->iColumn;
91235
91236    /* Code an OP_Transaction and OP_TableLock for <table>. */
91237    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91238    sqlite3CodeVerifySchema(pParse, iDb);
91239    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91240
91241    /* This function is only called from two places. In both cases the vdbe
91242    ** has already been allocated. So assume sqlite3GetVdbe() is always
91243    ** successful here.
91244    */
91245    assert(v);
91246    if( iCol<0 ){
91247      int iAddr = sqlite3CodeOnce(pParse);
91248      VdbeCoverage(v);
91249
91250      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91251      eType = IN_INDEX_ROWID;
91252
91253      sqlite3VdbeJumpHere(v, iAddr);
91254    }else{
91255      Index *pIdx;                         /* Iterator variable */
91256
91257      /* The collation sequence used by the comparison. If an index is to
91258      ** be used in place of a temp-table, it must be ordered according
91259      ** to this collation sequence.  */
91260      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
91261
91262      /* Check that the affinity that will be used to perform the
91263      ** comparison is the same as the affinity of the column. If
91264      ** it is not, it is not possible to use any index.
91265      */
91266      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
91267
91268      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
91269        if( (pIdx->aiColumn[0]==iCol)
91270         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
91271         && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
91272        ){
91273          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
91274          sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
91275          sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91276          VdbeComment((v, "%s", pIdx->zName));
91277          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
91278          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
91279
91280          if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
91281#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
91282            const i64 sOne = 1;
91283            sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
91284                iTab, 0, 0, (u8*)&sOne, P4_INT64);
91285#endif
91286            *prRhsHasNull = ++pParse->nMem;
91287            sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
91288          }
91289          sqlite3VdbeJumpHere(v, iAddr);
91290        }
91291      }
91292    }
91293  }
91294
91295  /* If no preexisting index is available for the IN clause
91296  ** and IN_INDEX_NOOP is an allowed reply
91297  ** and the RHS of the IN operator is a list, not a subquery
91298  ** and the RHS is not constant or has two or fewer terms,
91299  ** then it is not worth creating an ephemeral table to evaluate
91300  ** the IN operator so return IN_INDEX_NOOP.
91301  */
91302  if( eType==0
91303   && (inFlags & IN_INDEX_NOOP_OK)
91304   && !ExprHasProperty(pX, EP_xIsSelect)
91305   && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
91306  ){
91307    eType = IN_INDEX_NOOP;
91308  }
91309
91310
91311  if( eType==0 ){
91312    /* Could not find an existing table or index to use as the RHS b-tree.
91313    ** We will have to generate an ephemeral table to do the job.
91314    */
91315    u32 savedNQueryLoop = pParse->nQueryLoop;
91316    int rMayHaveNull = 0;
91317    eType = IN_INDEX_EPH;
91318    if( inFlags & IN_INDEX_LOOP ){
91319      pParse->nQueryLoop = 0;
91320      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
91321        eType = IN_INDEX_ROWID;
91322      }
91323    }else if( prRhsHasNull ){
91324      *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
91325    }
91326    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
91327    pParse->nQueryLoop = savedNQueryLoop;
91328  }else{
91329    pX->iTable = iTab;
91330  }
91331  return eType;
91332}
91333#endif
91334
91335/*
91336** Generate code for scalar subqueries used as a subquery expression, EXISTS,
91337** or IN operators.  Examples:
91338**
91339**     (SELECT a FROM b)          -- subquery
91340**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
91341**     x IN (4,5,11)              -- IN operator with list on right-hand side
91342**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
91343**
91344** The pExpr parameter describes the expression that contains the IN
91345** operator or subquery.
91346**
91347** If parameter isRowid is non-zero, then expression pExpr is guaranteed
91348** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
91349** to some integer key column of a table B-Tree. In this case, use an
91350** intkey B-Tree to store the set of IN(...) values instead of the usual
91351** (slower) variable length keys B-Tree.
91352**
91353** If rMayHaveNull is non-zero, that means that the operation is an IN
91354** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
91355** All this routine does is initialize the register given by rMayHaveNull
91356** to NULL.  Calling routines will take care of changing this register
91357** value to non-NULL if the RHS is NULL-free.
91358**
91359** For a SELECT or EXISTS operator, return the register that holds the
91360** result.  For IN operators or if an error occurs, the return value is 0.
91361*/
91362#ifndef SQLITE_OMIT_SUBQUERY
91363SQLITE_PRIVATE int sqlite3CodeSubselect(
91364  Parse *pParse,          /* Parsing context */
91365  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
91366  int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
91367  int isRowid             /* If true, LHS of IN operator is a rowid */
91368){
91369  int jmpIfDynamic = -1;                      /* One-time test address */
91370  int rReg = 0;                           /* Register storing resulting */
91371  Vdbe *v = sqlite3GetVdbe(pParse);
91372  if( NEVER(v==0) ) return 0;
91373  sqlite3ExprCachePush(pParse);
91374
91375  /* This code must be run in its entirety every time it is encountered
91376  ** if any of the following is true:
91377  **
91378  **    *  The right-hand side is a correlated subquery
91379  **    *  The right-hand side is an expression list containing variables
91380  **    *  We are inside a trigger
91381  **
91382  ** If all of the above are false, then we can run this code just once
91383  ** save the results, and reuse the same result on subsequent invocations.
91384  */
91385  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
91386    jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
91387  }
91388
91389#ifndef SQLITE_OMIT_EXPLAIN
91390  if( pParse->explain==2 ){
91391    char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
91392        jmpIfDynamic>=0?"":"CORRELATED ",
91393        pExpr->op==TK_IN?"LIST":"SCALAR",
91394        pParse->iNextSelectId
91395    );
91396    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
91397  }
91398#endif
91399
91400  switch( pExpr->op ){
91401    case TK_IN: {
91402      char affinity;              /* Affinity of the LHS of the IN */
91403      int addr;                   /* Address of OP_OpenEphemeral instruction */
91404      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
91405      KeyInfo *pKeyInfo = 0;      /* Key information */
91406
91407      affinity = sqlite3ExprAffinity(pLeft);
91408
91409      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
91410      ** expression it is handled the same way.  An ephemeral table is
91411      ** filled with single-field index keys representing the results
91412      ** from the SELECT or the <exprlist>.
91413      **
91414      ** If the 'x' expression is a column value, or the SELECT...
91415      ** statement returns a column value, then the affinity of that
91416      ** column is used to build the index keys. If both 'x' and the
91417      ** SELECT... statement are columns, then numeric affinity is used
91418      ** if either column has NUMERIC or INTEGER affinity. If neither
91419      ** 'x' nor the SELECT... statement are columns, then numeric affinity
91420      ** is used.
91421      */
91422      pExpr->iTable = pParse->nTab++;
91423      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
91424      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
91425
91426      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
91427        /* Case 1:     expr IN (SELECT ...)
91428        **
91429        ** Generate code to write the results of the select into the temporary
91430        ** table allocated and opened above.
91431        */
91432        Select *pSelect = pExpr->x.pSelect;
91433        SelectDest dest;
91434        ExprList *pEList;
91435
91436        assert( !isRowid );
91437        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
91438        dest.affSdst = (u8)affinity;
91439        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
91440        pSelect->iLimit = 0;
91441        testcase( pSelect->selFlags & SF_Distinct );
91442        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
91443        if( sqlite3Select(pParse, pSelect, &dest) ){
91444          sqlite3KeyInfoUnref(pKeyInfo);
91445          return 0;
91446        }
91447        pEList = pSelect->pEList;
91448        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
91449        assert( pEList!=0 );
91450        assert( pEList->nExpr>0 );
91451        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
91452        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
91453                                                         pEList->a[0].pExpr);
91454      }else if( ALWAYS(pExpr->x.pList!=0) ){
91455        /* Case 2:     expr IN (exprlist)
91456        **
91457        ** For each expression, build an index key from the evaluation and
91458        ** store it in the temporary table. If <expr> is a column, then use
91459        ** that columns affinity when building index keys. If <expr> is not
91460        ** a column, use numeric affinity.
91461        */
91462        int i;
91463        ExprList *pList = pExpr->x.pList;
91464        struct ExprList_item *pItem;
91465        int r1, r2, r3;
91466
91467        if( !affinity ){
91468          affinity = SQLITE_AFF_BLOB;
91469        }
91470        if( pKeyInfo ){
91471          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
91472          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91473        }
91474
91475        /* Loop through each expression in <exprlist>. */
91476        r1 = sqlite3GetTempReg(pParse);
91477        r2 = sqlite3GetTempReg(pParse);
91478        if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
91479        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
91480          Expr *pE2 = pItem->pExpr;
91481          int iValToIns;
91482
91483          /* If the expression is not constant then we will need to
91484          ** disable the test that was generated above that makes sure
91485          ** this code only executes once.  Because for a non-constant
91486          ** expression we need to rerun this code each time.
91487          */
91488          if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
91489            sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
91490            jmpIfDynamic = -1;
91491          }
91492
91493          /* Evaluate the expression and insert it into the temp table */
91494          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
91495            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
91496          }else{
91497            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
91498            if( isRowid ){
91499              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
91500                                sqlite3VdbeCurrentAddr(v)+2);
91501              VdbeCoverage(v);
91502              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
91503            }else{
91504              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
91505              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
91506              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
91507            }
91508          }
91509        }
91510        sqlite3ReleaseTempReg(pParse, r1);
91511        sqlite3ReleaseTempReg(pParse, r2);
91512      }
91513      if( pKeyInfo ){
91514        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
91515      }
91516      break;
91517    }
91518
91519    case TK_EXISTS:
91520    case TK_SELECT:
91521    default: {
91522      /* If this has to be a scalar SELECT.  Generate code to put the
91523      ** value of this select in a memory cell and record the number
91524      ** of the memory cell in iColumn.  If this is an EXISTS, write
91525      ** an integer 0 (not exists) or 1 (exists) into a memory cell
91526      ** and record that memory cell in iColumn.
91527      */
91528      Select *pSel;                         /* SELECT statement to encode */
91529      SelectDest dest;                      /* How to deal with SELECt result */
91530
91531      testcase( pExpr->op==TK_EXISTS );
91532      testcase( pExpr->op==TK_SELECT );
91533      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
91534
91535      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91536      pSel = pExpr->x.pSelect;
91537      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
91538      if( pExpr->op==TK_SELECT ){
91539        dest.eDest = SRT_Mem;
91540        dest.iSdst = dest.iSDParm;
91541        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
91542        VdbeComment((v, "Init subquery result"));
91543      }else{
91544        dest.eDest = SRT_Exists;
91545        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
91546        VdbeComment((v, "Init EXISTS result"));
91547      }
91548      sqlite3ExprDelete(pParse->db, pSel->pLimit);
91549      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
91550                                  &sqlite3IntTokens[1]);
91551      pSel->iLimit = 0;
91552      pSel->selFlags &= ~SF_MultiValue;
91553      if( sqlite3Select(pParse, pSel, &dest) ){
91554        return 0;
91555      }
91556      rReg = dest.iSDParm;
91557      ExprSetVVAProperty(pExpr, EP_NoReduce);
91558      break;
91559    }
91560  }
91561
91562  if( rHasNullFlag ){
91563    sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
91564  }
91565
91566  if( jmpIfDynamic>=0 ){
91567    sqlite3VdbeJumpHere(v, jmpIfDynamic);
91568  }
91569  sqlite3ExprCachePop(pParse);
91570
91571  return rReg;
91572}
91573#endif /* SQLITE_OMIT_SUBQUERY */
91574
91575#ifndef SQLITE_OMIT_SUBQUERY
91576/*
91577** Generate code for an IN expression.
91578**
91579**      x IN (SELECT ...)
91580**      x IN (value, value, ...)
91581**
91582** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
91583** is an array of zero or more values.  The expression is true if the LHS is
91584** contained within the RHS.  The value of the expression is unknown (NULL)
91585** if the LHS is NULL or if the LHS is not contained within the RHS and the
91586** RHS contains one or more NULL values.
91587**
91588** This routine generates code that jumps to destIfFalse if the LHS is not
91589** contained within the RHS.  If due to NULLs we cannot determine if the LHS
91590** is contained in the RHS then jump to destIfNull.  If the LHS is contained
91591** within the RHS then fall through.
91592*/
91593static void sqlite3ExprCodeIN(
91594  Parse *pParse,        /* Parsing and code generating context */
91595  Expr *pExpr,          /* The IN expression */
91596  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
91597  int destIfNull        /* Jump here if the results are unknown due to NULLs */
91598){
91599  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
91600  char affinity;        /* Comparison affinity to use */
91601  int eType;            /* Type of the RHS */
91602  int r1;               /* Temporary use register */
91603  Vdbe *v;              /* Statement under construction */
91604
91605  /* Compute the RHS.   After this step, the table with cursor
91606  ** pExpr->iTable will contains the values that make up the RHS.
91607  */
91608  v = pParse->pVdbe;
91609  assert( v!=0 );       /* OOM detected prior to this routine */
91610  VdbeNoopComment((v, "begin IN expr"));
91611  eType = sqlite3FindInIndex(pParse, pExpr,
91612                             IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
91613                             destIfFalse==destIfNull ? 0 : &rRhsHasNull);
91614
91615  /* Figure out the affinity to use to create a key from the results
91616  ** of the expression. affinityStr stores a static string suitable for
91617  ** P4 of OP_MakeRecord.
91618  */
91619  affinity = comparisonAffinity(pExpr);
91620
91621  /* Code the LHS, the <expr> from "<expr> IN (...)".
91622  */
91623  sqlite3ExprCachePush(pParse);
91624  r1 = sqlite3GetTempReg(pParse);
91625  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
91626
91627  /* If sqlite3FindInIndex() did not find or create an index that is
91628  ** suitable for evaluating the IN operator, then evaluate using a
91629  ** sequence of comparisons.
91630  */
91631  if( eType==IN_INDEX_NOOP ){
91632    ExprList *pList = pExpr->x.pList;
91633    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91634    int labelOk = sqlite3VdbeMakeLabel(v);
91635    int r2, regToFree;
91636    int regCkNull = 0;
91637    int ii;
91638    assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91639    if( destIfNull!=destIfFalse ){
91640      regCkNull = sqlite3GetTempReg(pParse);
91641      sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
91642    }
91643    for(ii=0; ii<pList->nExpr; ii++){
91644      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
91645      if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
91646        sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
91647      }
91648      if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
91649        sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
91650                          (void*)pColl, P4_COLLSEQ);
91651        VdbeCoverageIf(v, ii<pList->nExpr-1);
91652        VdbeCoverageIf(v, ii==pList->nExpr-1);
91653        sqlite3VdbeChangeP5(v, affinity);
91654      }else{
91655        assert( destIfNull==destIfFalse );
91656        sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
91657                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
91658        sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
91659      }
91660      sqlite3ReleaseTempReg(pParse, regToFree);
91661    }
91662    if( regCkNull ){
91663      sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
91664      sqlite3VdbeGoto(v, destIfFalse);
91665    }
91666    sqlite3VdbeResolveLabel(v, labelOk);
91667    sqlite3ReleaseTempReg(pParse, regCkNull);
91668  }else{
91669
91670    /* If the LHS is NULL, then the result is either false or NULL depending
91671    ** on whether the RHS is empty or not, respectively.
91672    */
91673    if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
91674      if( destIfNull==destIfFalse ){
91675        /* Shortcut for the common case where the false and NULL outcomes are
91676        ** the same. */
91677        sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
91678      }else{
91679        int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
91680        sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
91681        VdbeCoverage(v);
91682        sqlite3VdbeGoto(v, destIfNull);
91683        sqlite3VdbeJumpHere(v, addr1);
91684      }
91685    }
91686
91687    if( eType==IN_INDEX_ROWID ){
91688      /* In this case, the RHS is the ROWID of table b-tree
91689      */
91690      sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
91691      VdbeCoverage(v);
91692    }else{
91693      /* In this case, the RHS is an index b-tree.
91694      */
91695      sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
91696
91697      /* If the set membership test fails, then the result of the
91698      ** "x IN (...)" expression must be either 0 or NULL. If the set
91699      ** contains no NULL values, then the result is 0. If the set
91700      ** contains one or more NULL values, then the result of the
91701      ** expression is also NULL.
91702      */
91703      assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
91704      if( rRhsHasNull==0 ){
91705        /* This branch runs if it is known at compile time that the RHS
91706        ** cannot contain NULL values. This happens as the result
91707        ** of a "NOT NULL" constraint in the database schema.
91708        **
91709        ** Also run this branch if NULL is equivalent to FALSE
91710        ** for this particular IN operator.
91711        */
91712        sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
91713        VdbeCoverage(v);
91714      }else{
91715        /* In this branch, the RHS of the IN might contain a NULL and
91716        ** the presence of a NULL on the RHS makes a difference in the
91717        ** outcome.
91718        */
91719        int addr1;
91720
91721        /* First check to see if the LHS is contained in the RHS.  If so,
91722        ** then the answer is TRUE the presence of NULLs in the RHS does
91723        ** not matter.  If the LHS is not contained in the RHS, then the
91724        ** answer is NULL if the RHS contains NULLs and the answer is
91725        ** FALSE if the RHS is NULL-free.
91726        */
91727        addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
91728        VdbeCoverage(v);
91729        sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
91730        VdbeCoverage(v);
91731        sqlite3VdbeGoto(v, destIfFalse);
91732        sqlite3VdbeJumpHere(v, addr1);
91733      }
91734    }
91735  }
91736  sqlite3ReleaseTempReg(pParse, r1);
91737  sqlite3ExprCachePop(pParse);
91738  VdbeComment((v, "end IN expr"));
91739}
91740#endif /* SQLITE_OMIT_SUBQUERY */
91741
91742#ifndef SQLITE_OMIT_FLOATING_POINT
91743/*
91744** Generate an instruction that will put the floating point
91745** value described by z[0..n-1] into register iMem.
91746**
91747** The z[] string will probably not be zero-terminated.  But the
91748** z[n] character is guaranteed to be something that does not look
91749** like the continuation of the number.
91750*/
91751static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
91752  if( ALWAYS(z!=0) ){
91753    double value;
91754    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
91755    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
91756    if( negateFlag ) value = -value;
91757    sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
91758  }
91759}
91760#endif
91761
91762
91763/*
91764** Generate an instruction that will put the integer describe by
91765** text z[0..n-1] into register iMem.
91766**
91767** Expr.u.zToken is always UTF8 and zero-terminated.
91768*/
91769static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
91770  Vdbe *v = pParse->pVdbe;
91771  if( pExpr->flags & EP_IntValue ){
91772    int i = pExpr->u.iValue;
91773    assert( i>=0 );
91774    if( negFlag ) i = -i;
91775    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
91776  }else{
91777    int c;
91778    i64 value;
91779    const char *z = pExpr->u.zToken;
91780    assert( z!=0 );
91781    c = sqlite3DecOrHexToI64(z, &value);
91782    if( c==0 || (c==2 && negFlag) ){
91783      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
91784      sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
91785    }else{
91786#ifdef SQLITE_OMIT_FLOATING_POINT
91787      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
91788#else
91789#ifndef SQLITE_OMIT_HEX_INTEGER
91790      if( sqlite3_strnicmp(z,"0x",2)==0 ){
91791        sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
91792      }else
91793#endif
91794      {
91795        codeReal(v, z, negFlag, iMem);
91796      }
91797#endif
91798    }
91799  }
91800}
91801
91802#if defined(SQLITE_DEBUG)
91803/*
91804** Verify the consistency of the column cache
91805*/
91806static int cacheIsValid(Parse *pParse){
91807  int i, n;
91808  for(i=n=0; i<SQLITE_N_COLCACHE; i++){
91809    if( pParse->aColCache[i].iReg>0 ) n++;
91810  }
91811  return n==pParse->nColCache;
91812}
91813#endif
91814
91815/*
91816** Clear a cache entry.
91817*/
91818static void cacheEntryClear(Parse *pParse, struct yColCache *p){
91819  if( p->tempReg ){
91820    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
91821      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
91822    }
91823    p->tempReg = 0;
91824  }
91825  p->iReg = 0;
91826  pParse->nColCache--;
91827  assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91828}
91829
91830
91831/*
91832** Record in the column cache that a particular column from a
91833** particular table is stored in a particular register.
91834*/
91835SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
91836  int i;
91837  int minLru;
91838  int idxLru;
91839  struct yColCache *p;
91840
91841  /* Unless an error has occurred, register numbers are always positive. */
91842  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
91843  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
91844
91845  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
91846  ** for testing only - to verify that SQLite always gets the same answer
91847  ** with and without the column cache.
91848  */
91849  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
91850
91851  /* First replace any existing entry.
91852  **
91853  ** Actually, the way the column cache is currently used, we are guaranteed
91854  ** that the object will never already be in cache.  Verify this guarantee.
91855  */
91856#ifndef NDEBUG
91857  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91858    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
91859  }
91860#endif
91861
91862  /* Find an empty slot and replace it */
91863  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91864    if( p->iReg==0 ){
91865      p->iLevel = pParse->iCacheLevel;
91866      p->iTable = iTab;
91867      p->iColumn = iCol;
91868      p->iReg = iReg;
91869      p->tempReg = 0;
91870      p->lru = pParse->iCacheCnt++;
91871      pParse->nColCache++;
91872      assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91873      return;
91874    }
91875  }
91876
91877  /* Replace the last recently used */
91878  minLru = 0x7fffffff;
91879  idxLru = -1;
91880  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91881    if( p->lru<minLru ){
91882      idxLru = i;
91883      minLru = p->lru;
91884    }
91885  }
91886  if( ALWAYS(idxLru>=0) ){
91887    p = &pParse->aColCache[idxLru];
91888    p->iLevel = pParse->iCacheLevel;
91889    p->iTable = iTab;
91890    p->iColumn = iCol;
91891    p->iReg = iReg;
91892    p->tempReg = 0;
91893    p->lru = pParse->iCacheCnt++;
91894    assert( cacheIsValid(pParse) );
91895    return;
91896  }
91897}
91898
91899/*
91900** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
91901** Purge the range of registers from the column cache.
91902*/
91903SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
91904  struct yColCache *p;
91905  if( iReg<=0 || pParse->nColCache==0 ) return;
91906  p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
91907  while(1){
91908    if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
91909    if( p==pParse->aColCache ) break;
91910    p--;
91911  }
91912}
91913
91914/*
91915** Remember the current column cache context.  Any new entries added
91916** added to the column cache after this call are removed when the
91917** corresponding pop occurs.
91918*/
91919SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
91920  pParse->iCacheLevel++;
91921#ifdef SQLITE_DEBUG
91922  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91923    printf("PUSH to %d\n", pParse->iCacheLevel);
91924  }
91925#endif
91926}
91927
91928/*
91929** Remove from the column cache any entries that were added since the
91930** the previous sqlite3ExprCachePush operation.  In other words, restore
91931** the cache to the state it was in prior the most recent Push.
91932*/
91933SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
91934  int i;
91935  struct yColCache *p;
91936  assert( pParse->iCacheLevel>=1 );
91937  pParse->iCacheLevel--;
91938#ifdef SQLITE_DEBUG
91939  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91940    printf("POP  to %d\n", pParse->iCacheLevel);
91941  }
91942#endif
91943  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91944    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
91945      cacheEntryClear(pParse, p);
91946    }
91947  }
91948}
91949
91950/*
91951** When a cached column is reused, make sure that its register is
91952** no longer available as a temp register.  ticket #3879:  that same
91953** register might be in the cache in multiple places, so be sure to
91954** get them all.
91955*/
91956static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
91957  int i;
91958  struct yColCache *p;
91959  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91960    if( p->iReg==iReg ){
91961      p->tempReg = 0;
91962    }
91963  }
91964}
91965
91966/* Generate code that will load into register regOut a value that is
91967** appropriate for the iIdxCol-th column of index pIdx.
91968*/
91969SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
91970  Parse *pParse,  /* The parsing context */
91971  Index *pIdx,    /* The index whose column is to be loaded */
91972  int iTabCur,    /* Cursor pointing to a table row */
91973  int iIdxCol,    /* The column of the index to be loaded */
91974  int regOut      /* Store the index column value in this register */
91975){
91976  i16 iTabCol = pIdx->aiColumn[iIdxCol];
91977  if( iTabCol==XN_EXPR ){
91978    assert( pIdx->aColExpr );
91979    assert( pIdx->aColExpr->nExpr>iIdxCol );
91980    pParse->iSelfTab = iTabCur;
91981    sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
91982  }else{
91983    sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
91984                                    iTabCol, regOut);
91985  }
91986}
91987
91988/*
91989** Generate code to extract the value of the iCol-th column of a table.
91990*/
91991SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
91992  Vdbe *v,        /* The VDBE under construction */
91993  Table *pTab,    /* The table containing the value */
91994  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
91995  int iCol,       /* Index of the column to extract */
91996  int regOut      /* Extract the value into this register */
91997){
91998  if( iCol<0 || iCol==pTab->iPKey ){
91999    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
92000  }else{
92001    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
92002    int x = iCol;
92003    if( !HasRowid(pTab) && !IsVirtual(pTab) ){
92004      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
92005    }
92006    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
92007  }
92008  if( iCol>=0 ){
92009    sqlite3ColumnDefault(v, pTab, iCol, regOut);
92010  }
92011}
92012
92013/*
92014** Generate code that will extract the iColumn-th column from
92015** table pTab and store the column value in a register.
92016**
92017** An effort is made to store the column value in register iReg.  This
92018** is not garanteeed for GetColumn() - the result can be stored in
92019** any register.  But the result is guaranteed to land in register iReg
92020** for GetColumnToReg().
92021**
92022** There must be an open cursor to pTab in iTable when this routine
92023** is called.  If iColumn<0 then code is generated that extracts the rowid.
92024*/
92025SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
92026  Parse *pParse,   /* Parsing and code generating context */
92027  Table *pTab,     /* Description of the table we are reading from */
92028  int iColumn,     /* Index of the table column */
92029  int iTable,      /* The cursor pointing to the table */
92030  int iReg,        /* Store results here */
92031  u8 p5            /* P5 value for OP_Column + FLAGS */
92032){
92033  Vdbe *v = pParse->pVdbe;
92034  int i;
92035  struct yColCache *p;
92036
92037  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92038    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
92039      p->lru = pParse->iCacheCnt++;
92040      sqlite3ExprCachePinRegister(pParse, p->iReg);
92041      return p->iReg;
92042    }
92043  }
92044  assert( v!=0 );
92045  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
92046  if( p5 ){
92047    sqlite3VdbeChangeP5(v, p5);
92048  }else{
92049    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
92050  }
92051  return iReg;
92052}
92053SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
92054  Parse *pParse,   /* Parsing and code generating context */
92055  Table *pTab,     /* Description of the table we are reading from */
92056  int iColumn,     /* Index of the table column */
92057  int iTable,      /* The cursor pointing to the table */
92058  int iReg         /* Store results here */
92059){
92060  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
92061  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
92062}
92063
92064
92065/*
92066** Clear all column cache entries.
92067*/
92068SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
92069  int i;
92070  struct yColCache *p;
92071
92072#if SQLITE_DEBUG
92073  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92074    printf("CLEAR\n");
92075  }
92076#endif
92077  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92078    if( p->iReg ){
92079      cacheEntryClear(pParse, p);
92080    }
92081  }
92082}
92083
92084/*
92085** Record the fact that an affinity change has occurred on iCount
92086** registers starting with iStart.
92087*/
92088SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
92089  sqlite3ExprCacheRemove(pParse, iStart, iCount);
92090}
92091
92092/*
92093** Generate code to move content from registers iFrom...iFrom+nReg-1
92094** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
92095*/
92096SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
92097  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
92098  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
92099  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
92100}
92101
92102#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
92103/*
92104** Return true if any register in the range iFrom..iTo (inclusive)
92105** is used as part of the column cache.
92106**
92107** This routine is used within assert() and testcase() macros only
92108** and does not appear in a normal build.
92109*/
92110static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
92111  int i;
92112  struct yColCache *p;
92113  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92114    int r = p->iReg;
92115    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
92116  }
92117  return 0;
92118}
92119#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
92120
92121
92122/*
92123** Convert an expression node to a TK_REGISTER
92124*/
92125static void exprToRegister(Expr *p, int iReg){
92126  p->op2 = p->op;
92127  p->op = TK_REGISTER;
92128  p->iTable = iReg;
92129  ExprClearProperty(p, EP_Skip);
92130}
92131
92132/*
92133** Generate code into the current Vdbe to evaluate the given
92134** expression.  Attempt to store the results in register "target".
92135** Return the register where results are stored.
92136**
92137** With this routine, there is no guarantee that results will
92138** be stored in target.  The result might be stored in some other
92139** register if it is convenient to do so.  The calling function
92140** must check the return code and move the results to the desired
92141** register.
92142*/
92143SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
92144  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
92145  int op;                   /* The opcode being coded */
92146  int inReg = target;       /* Results stored in register inReg */
92147  int regFree1 = 0;         /* If non-zero free this temporary register */
92148  int regFree2 = 0;         /* If non-zero free this temporary register */
92149  int r1, r2, r3, r4;       /* Various register numbers */
92150  sqlite3 *db = pParse->db; /* The database connection */
92151  Expr tempX;               /* Temporary expression node */
92152
92153  assert( target>0 && target<=pParse->nMem );
92154  if( v==0 ){
92155    assert( pParse->db->mallocFailed );
92156    return 0;
92157  }
92158
92159  if( pExpr==0 ){
92160    op = TK_NULL;
92161  }else{
92162    op = pExpr->op;
92163  }
92164  switch( op ){
92165    case TK_AGG_COLUMN: {
92166      AggInfo *pAggInfo = pExpr->pAggInfo;
92167      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
92168      if( !pAggInfo->directMode ){
92169        assert( pCol->iMem>0 );
92170        inReg = pCol->iMem;
92171        break;
92172      }else if( pAggInfo->useSortingIdx ){
92173        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
92174                              pCol->iSorterColumn, target);
92175        break;
92176      }
92177      /* Otherwise, fall thru into the TK_COLUMN case */
92178    }
92179    case TK_COLUMN: {
92180      int iTab = pExpr->iTable;
92181      if( iTab<0 ){
92182        if( pParse->ckBase>0 ){
92183          /* Generating CHECK constraints or inserting into partial index */
92184          inReg = pExpr->iColumn + pParse->ckBase;
92185          break;
92186        }else{
92187          /* Coding an expression that is part of an index where column names
92188          ** in the index refer to the table to which the index belongs */
92189          iTab = pParse->iSelfTab;
92190        }
92191      }
92192      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
92193                               pExpr->iColumn, iTab, target,
92194                               pExpr->op2);
92195      break;
92196    }
92197    case TK_INTEGER: {
92198      codeInteger(pParse, pExpr, 0, target);
92199      break;
92200    }
92201#ifndef SQLITE_OMIT_FLOATING_POINT
92202    case TK_FLOAT: {
92203      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92204      codeReal(v, pExpr->u.zToken, 0, target);
92205      break;
92206    }
92207#endif
92208    case TK_STRING: {
92209      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92210      sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
92211      break;
92212    }
92213    case TK_NULL: {
92214      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92215      break;
92216    }
92217#ifndef SQLITE_OMIT_BLOB_LITERAL
92218    case TK_BLOB: {
92219      int n;
92220      const char *z;
92221      char *zBlob;
92222      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92223      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
92224      assert( pExpr->u.zToken[1]=='\'' );
92225      z = &pExpr->u.zToken[2];
92226      n = sqlite3Strlen30(z) - 1;
92227      assert( z[n]=='\'' );
92228      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
92229      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
92230      break;
92231    }
92232#endif
92233    case TK_VARIABLE: {
92234      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92235      assert( pExpr->u.zToken!=0 );
92236      assert( pExpr->u.zToken[0]!=0 );
92237      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
92238      if( pExpr->u.zToken[1]!=0 ){
92239        assert( pExpr->u.zToken[0]=='?'
92240             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
92241        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
92242      }
92243      break;
92244    }
92245    case TK_REGISTER: {
92246      inReg = pExpr->iTable;
92247      break;
92248    }
92249#ifndef SQLITE_OMIT_CAST
92250    case TK_CAST: {
92251      /* Expressions of the form:   CAST(pLeft AS token) */
92252      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92253      if( inReg!=target ){
92254        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
92255        inReg = target;
92256      }
92257      sqlite3VdbeAddOp2(v, OP_Cast, target,
92258                        sqlite3AffinityType(pExpr->u.zToken, 0));
92259      testcase( usedAsColumnCache(pParse, inReg, inReg) );
92260      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
92261      break;
92262    }
92263#endif /* SQLITE_OMIT_CAST */
92264    case TK_LT:
92265    case TK_LE:
92266    case TK_GT:
92267    case TK_GE:
92268    case TK_NE:
92269    case TK_EQ: {
92270      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92271      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92272      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92273                  r1, r2, inReg, SQLITE_STOREP2);
92274      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
92275      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
92276      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
92277      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
92278      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
92279      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
92280      testcase( regFree1==0 );
92281      testcase( regFree2==0 );
92282      break;
92283    }
92284    case TK_IS:
92285    case TK_ISNOT: {
92286      testcase( op==TK_IS );
92287      testcase( op==TK_ISNOT );
92288      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92289      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92290      op = (op==TK_IS) ? TK_EQ : TK_NE;
92291      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92292                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
92293      VdbeCoverageIf(v, op==TK_EQ);
92294      VdbeCoverageIf(v, op==TK_NE);
92295      testcase( regFree1==0 );
92296      testcase( regFree2==0 );
92297      break;
92298    }
92299    case TK_AND:
92300    case TK_OR:
92301    case TK_PLUS:
92302    case TK_STAR:
92303    case TK_MINUS:
92304    case TK_REM:
92305    case TK_BITAND:
92306    case TK_BITOR:
92307    case TK_SLASH:
92308    case TK_LSHIFT:
92309    case TK_RSHIFT:
92310    case TK_CONCAT: {
92311      assert( TK_AND==OP_And );            testcase( op==TK_AND );
92312      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
92313      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
92314      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
92315      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
92316      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
92317      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
92318      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
92319      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
92320      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
92321      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
92322      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92323      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92324      sqlite3VdbeAddOp3(v, op, r2, r1, target);
92325      testcase( regFree1==0 );
92326      testcase( regFree2==0 );
92327      break;
92328    }
92329    case TK_UMINUS: {
92330      Expr *pLeft = pExpr->pLeft;
92331      assert( pLeft );
92332      if( pLeft->op==TK_INTEGER ){
92333        codeInteger(pParse, pLeft, 1, target);
92334#ifndef SQLITE_OMIT_FLOATING_POINT
92335      }else if( pLeft->op==TK_FLOAT ){
92336        assert( !ExprHasProperty(pExpr, EP_IntValue) );
92337        codeReal(v, pLeft->u.zToken, 1, target);
92338#endif
92339      }else{
92340        tempX.op = TK_INTEGER;
92341        tempX.flags = EP_IntValue|EP_TokenOnly;
92342        tempX.u.iValue = 0;
92343        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
92344        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
92345        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
92346        testcase( regFree2==0 );
92347      }
92348      inReg = target;
92349      break;
92350    }
92351    case TK_BITNOT:
92352    case TK_NOT: {
92353      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
92354      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
92355      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92356      testcase( regFree1==0 );
92357      inReg = target;
92358      sqlite3VdbeAddOp2(v, op, r1, inReg);
92359      break;
92360    }
92361    case TK_ISNULL:
92362    case TK_NOTNULL: {
92363      int addr;
92364      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
92365      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
92366      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
92367      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92368      testcase( regFree1==0 );
92369      addr = sqlite3VdbeAddOp1(v, op, r1);
92370      VdbeCoverageIf(v, op==TK_ISNULL);
92371      VdbeCoverageIf(v, op==TK_NOTNULL);
92372      sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
92373      sqlite3VdbeJumpHere(v, addr);
92374      break;
92375    }
92376    case TK_AGG_FUNCTION: {
92377      AggInfo *pInfo = pExpr->pAggInfo;
92378      if( pInfo==0 ){
92379        assert( !ExprHasProperty(pExpr, EP_IntValue) );
92380        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
92381      }else{
92382        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
92383      }
92384      break;
92385    }
92386    case TK_FUNCTION: {
92387      ExprList *pFarg;       /* List of function arguments */
92388      int nFarg;             /* Number of function arguments */
92389      FuncDef *pDef;         /* The function definition object */
92390      const char *zId;       /* The function name */
92391      u32 constMask = 0;     /* Mask of function arguments that are constant */
92392      int i;                 /* Loop counter */
92393      u8 enc = ENC(db);      /* The text encoding used by this database */
92394      CollSeq *pColl = 0;    /* A collating sequence */
92395
92396      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92397      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
92398        pFarg = 0;
92399      }else{
92400        pFarg = pExpr->x.pList;
92401      }
92402      nFarg = pFarg ? pFarg->nExpr : 0;
92403      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92404      zId = pExpr->u.zToken;
92405      pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
92406#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
92407      if( pDef==0 && pParse->explain ){
92408        pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
92409      }
92410#endif
92411      if( pDef==0 || pDef->xFinalize!=0 ){
92412        sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
92413        break;
92414      }
92415
92416      /* Attempt a direct implementation of the built-in COALESCE() and
92417      ** IFNULL() functions.  This avoids unnecessary evaluation of
92418      ** arguments past the first non-NULL argument.
92419      */
92420      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
92421        int endCoalesce = sqlite3VdbeMakeLabel(v);
92422        assert( nFarg>=2 );
92423        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
92424        for(i=1; i<nFarg; i++){
92425          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
92426          VdbeCoverage(v);
92427          sqlite3ExprCacheRemove(pParse, target, 1);
92428          sqlite3ExprCachePush(pParse);
92429          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
92430          sqlite3ExprCachePop(pParse);
92431        }
92432        sqlite3VdbeResolveLabel(v, endCoalesce);
92433        break;
92434      }
92435
92436      /* The UNLIKELY() function is a no-op.  The result is the value
92437      ** of the first argument.
92438      */
92439      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
92440        assert( nFarg>=1 );
92441        inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
92442        break;
92443      }
92444
92445      for(i=0; i<nFarg; i++){
92446        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
92447          testcase( i==31 );
92448          constMask |= MASKBIT32(i);
92449        }
92450        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
92451          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
92452        }
92453      }
92454      if( pFarg ){
92455        if( constMask ){
92456          r1 = pParse->nMem+1;
92457          pParse->nMem += nFarg;
92458        }else{
92459          r1 = sqlite3GetTempRange(pParse, nFarg);
92460        }
92461
92462        /* For length() and typeof() functions with a column argument,
92463        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
92464        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
92465        ** loading.
92466        */
92467        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
92468          u8 exprOp;
92469          assert( nFarg==1 );
92470          assert( pFarg->a[0].pExpr!=0 );
92471          exprOp = pFarg->a[0].pExpr->op;
92472          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
92473            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
92474            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
92475            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
92476            pFarg->a[0].pExpr->op2 =
92477                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
92478          }
92479        }
92480
92481        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
92482        sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
92483                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
92484        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
92485      }else{
92486        r1 = 0;
92487      }
92488#ifndef SQLITE_OMIT_VIRTUALTABLE
92489      /* Possibly overload the function if the first argument is
92490      ** a virtual table column.
92491      **
92492      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
92493      ** second argument, not the first, as the argument to test to
92494      ** see if it is a column in a virtual table.  This is done because
92495      ** the left operand of infix functions (the operand we want to
92496      ** control overloading) ends up as the second argument to the
92497      ** function.  The expression "A glob B" is equivalent to
92498      ** "glob(B,A).  We want to use the A in "A glob B" to test
92499      ** for function overloading.  But we use the B term in "glob(B,A)".
92500      */
92501      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
92502        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
92503      }else if( nFarg>0 ){
92504        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
92505      }
92506#endif
92507      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
92508        if( !pColl ) pColl = db->pDfltColl;
92509        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
92510      }
92511      sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
92512                        (char*)pDef, P4_FUNCDEF);
92513      sqlite3VdbeChangeP5(v, (u8)nFarg);
92514      if( nFarg && constMask==0 ){
92515        sqlite3ReleaseTempRange(pParse, r1, nFarg);
92516      }
92517      break;
92518    }
92519#ifndef SQLITE_OMIT_SUBQUERY
92520    case TK_EXISTS:
92521    case TK_SELECT: {
92522      testcase( op==TK_EXISTS );
92523      testcase( op==TK_SELECT );
92524      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
92525      break;
92526    }
92527    case TK_IN: {
92528      int destIfFalse = sqlite3VdbeMakeLabel(v);
92529      int destIfNull = sqlite3VdbeMakeLabel(v);
92530      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92531      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
92532      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
92533      sqlite3VdbeResolveLabel(v, destIfFalse);
92534      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
92535      sqlite3VdbeResolveLabel(v, destIfNull);
92536      break;
92537    }
92538#endif /* SQLITE_OMIT_SUBQUERY */
92539
92540
92541    /*
92542    **    x BETWEEN y AND z
92543    **
92544    ** This is equivalent to
92545    **
92546    **    x>=y AND x<=z
92547    **
92548    ** X is stored in pExpr->pLeft.
92549    ** Y is stored in pExpr->pList->a[0].pExpr.
92550    ** Z is stored in pExpr->pList->a[1].pExpr.
92551    */
92552    case TK_BETWEEN: {
92553      Expr *pLeft = pExpr->pLeft;
92554      struct ExprList_item *pLItem = pExpr->x.pList->a;
92555      Expr *pRight = pLItem->pExpr;
92556
92557      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
92558      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92559      testcase( regFree1==0 );
92560      testcase( regFree2==0 );
92561      r3 = sqlite3GetTempReg(pParse);
92562      r4 = sqlite3GetTempReg(pParse);
92563      codeCompare(pParse, pLeft, pRight, OP_Ge,
92564                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
92565      pLItem++;
92566      pRight = pLItem->pExpr;
92567      sqlite3ReleaseTempReg(pParse, regFree2);
92568      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92569      testcase( regFree2==0 );
92570      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
92571      VdbeCoverage(v);
92572      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
92573      sqlite3ReleaseTempReg(pParse, r3);
92574      sqlite3ReleaseTempReg(pParse, r4);
92575      break;
92576    }
92577    case TK_SPAN:
92578    case TK_COLLATE:
92579    case TK_UPLUS: {
92580      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92581      break;
92582    }
92583
92584    case TK_TRIGGER: {
92585      /* If the opcode is TK_TRIGGER, then the expression is a reference
92586      ** to a column in the new.* or old.* pseudo-tables available to
92587      ** trigger programs. In this case Expr.iTable is set to 1 for the
92588      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
92589      ** is set to the column of the pseudo-table to read, or to -1 to
92590      ** read the rowid field.
92591      **
92592      ** The expression is implemented using an OP_Param opcode. The p1
92593      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
92594      ** to reference another column of the old.* pseudo-table, where
92595      ** i is the index of the column. For a new.rowid reference, p1 is
92596      ** set to (n+1), where n is the number of columns in each pseudo-table.
92597      ** For a reference to any other column in the new.* pseudo-table, p1
92598      ** is set to (n+2+i), where n and i are as defined previously. For
92599      ** example, if the table on which triggers are being fired is
92600      ** declared as:
92601      **
92602      **   CREATE TABLE t1(a, b);
92603      **
92604      ** Then p1 is interpreted as follows:
92605      **
92606      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
92607      **   p1==1   ->    old.a         p1==4   ->    new.a
92608      **   p1==2   ->    old.b         p1==5   ->    new.b
92609      */
92610      Table *pTab = pExpr->pTab;
92611      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
92612
92613      assert( pExpr->iTable==0 || pExpr->iTable==1 );
92614      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
92615      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
92616      assert( p1>=0 && p1<(pTab->nCol*2+2) );
92617
92618      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
92619      VdbeComment((v, "%s.%s -> $%d",
92620        (pExpr->iTable ? "new" : "old"),
92621        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
92622        target
92623      ));
92624
92625#ifndef SQLITE_OMIT_FLOATING_POINT
92626      /* If the column has REAL affinity, it may currently be stored as an
92627      ** integer. Use OP_RealAffinity to make sure it is really real.
92628      **
92629      ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
92630      ** floating point when extracting it from the record.  */
92631      if( pExpr->iColumn>=0
92632       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
92633      ){
92634        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
92635      }
92636#endif
92637      break;
92638    }
92639
92640
92641    /*
92642    ** Form A:
92643    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92644    **
92645    ** Form B:
92646    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92647    **
92648    ** Form A is can be transformed into the equivalent form B as follows:
92649    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
92650    **        WHEN x=eN THEN rN ELSE y END
92651    **
92652    ** X (if it exists) is in pExpr->pLeft.
92653    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
92654    ** odd.  The Y is also optional.  If the number of elements in x.pList
92655    ** is even, then Y is omitted and the "otherwise" result is NULL.
92656    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
92657    **
92658    ** The result of the expression is the Ri for the first matching Ei,
92659    ** or if there is no matching Ei, the ELSE term Y, or if there is
92660    ** no ELSE term, NULL.
92661    */
92662    default: assert( op==TK_CASE ); {
92663      int endLabel;                     /* GOTO label for end of CASE stmt */
92664      int nextCase;                     /* GOTO label for next WHEN clause */
92665      int nExpr;                        /* 2x number of WHEN terms */
92666      int i;                            /* Loop counter */
92667      ExprList *pEList;                 /* List of WHEN terms */
92668      struct ExprList_item *aListelem;  /* Array of WHEN terms */
92669      Expr opCompare;                   /* The X==Ei expression */
92670      Expr *pX;                         /* The X expression */
92671      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
92672      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
92673
92674      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
92675      assert(pExpr->x.pList->nExpr > 0);
92676      pEList = pExpr->x.pList;
92677      aListelem = pEList->a;
92678      nExpr = pEList->nExpr;
92679      endLabel = sqlite3VdbeMakeLabel(v);
92680      if( (pX = pExpr->pLeft)!=0 ){
92681        tempX = *pX;
92682        testcase( pX->op==TK_COLUMN );
92683        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
92684        testcase( regFree1==0 );
92685        opCompare.op = TK_EQ;
92686        opCompare.pLeft = &tempX;
92687        pTest = &opCompare;
92688        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
92689        ** The value in regFree1 might get SCopy-ed into the file result.
92690        ** So make sure that the regFree1 register is not reused for other
92691        ** purposes and possibly overwritten.  */
92692        regFree1 = 0;
92693      }
92694      for(i=0; i<nExpr-1; i=i+2){
92695        sqlite3ExprCachePush(pParse);
92696        if( pX ){
92697          assert( pTest!=0 );
92698          opCompare.pRight = aListelem[i].pExpr;
92699        }else{
92700          pTest = aListelem[i].pExpr;
92701        }
92702        nextCase = sqlite3VdbeMakeLabel(v);
92703        testcase( pTest->op==TK_COLUMN );
92704        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
92705        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
92706        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
92707        sqlite3VdbeGoto(v, endLabel);
92708        sqlite3ExprCachePop(pParse);
92709        sqlite3VdbeResolveLabel(v, nextCase);
92710      }
92711      if( (nExpr&1)!=0 ){
92712        sqlite3ExprCachePush(pParse);
92713        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
92714        sqlite3ExprCachePop(pParse);
92715      }else{
92716        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92717      }
92718      assert( db->mallocFailed || pParse->nErr>0
92719           || pParse->iCacheLevel==iCacheLevel );
92720      sqlite3VdbeResolveLabel(v, endLabel);
92721      break;
92722    }
92723#ifndef SQLITE_OMIT_TRIGGER
92724    case TK_RAISE: {
92725      assert( pExpr->affinity==OE_Rollback
92726           || pExpr->affinity==OE_Abort
92727           || pExpr->affinity==OE_Fail
92728           || pExpr->affinity==OE_Ignore
92729      );
92730      if( !pParse->pTriggerTab ){
92731        sqlite3ErrorMsg(pParse,
92732                       "RAISE() may only be used within a trigger-program");
92733        return 0;
92734      }
92735      if( pExpr->affinity==OE_Abort ){
92736        sqlite3MayAbort(pParse);
92737      }
92738      assert( !ExprHasProperty(pExpr, EP_IntValue) );
92739      if( pExpr->affinity==OE_Ignore ){
92740        sqlite3VdbeAddOp4(
92741            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
92742        VdbeCoverage(v);
92743      }else{
92744        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
92745                              pExpr->affinity, pExpr->u.zToken, 0, 0);
92746      }
92747
92748      break;
92749    }
92750#endif
92751  }
92752  sqlite3ReleaseTempReg(pParse, regFree1);
92753  sqlite3ReleaseTempReg(pParse, regFree2);
92754  return inReg;
92755}
92756
92757/*
92758** Factor out the code of the given expression to initialization time.
92759*/
92760SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
92761  Parse *pParse,    /* Parsing context */
92762  Expr *pExpr,      /* The expression to code when the VDBE initializes */
92763  int regDest,      /* Store the value in this register */
92764  u8 reusable       /* True if this expression is reusable */
92765){
92766  ExprList *p;
92767  assert( ConstFactorOk(pParse) );
92768  p = pParse->pConstExpr;
92769  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
92770  p = sqlite3ExprListAppend(pParse, p, pExpr);
92771  if( p ){
92772     struct ExprList_item *pItem = &p->a[p->nExpr-1];
92773     pItem->u.iConstExprReg = regDest;
92774     pItem->reusable = reusable;
92775  }
92776  pParse->pConstExpr = p;
92777}
92778
92779/*
92780** Generate code to evaluate an expression and store the results
92781** into a register.  Return the register number where the results
92782** are stored.
92783**
92784** If the register is a temporary register that can be deallocated,
92785** then write its number into *pReg.  If the result register is not
92786** a temporary, then set *pReg to zero.
92787**
92788** If pExpr is a constant, then this routine might generate this
92789** code to fill the register in the initialization section of the
92790** VDBE program, in order to factor it out of the evaluation loop.
92791*/
92792SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
92793  int r2;
92794  pExpr = sqlite3ExprSkipCollate(pExpr);
92795  if( ConstFactorOk(pParse)
92796   && pExpr->op!=TK_REGISTER
92797   && sqlite3ExprIsConstantNotJoin(pExpr)
92798  ){
92799    ExprList *p = pParse->pConstExpr;
92800    int i;
92801    *pReg  = 0;
92802    if( p ){
92803      struct ExprList_item *pItem;
92804      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
92805        if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
92806          return pItem->u.iConstExprReg;
92807        }
92808      }
92809    }
92810    r2 = ++pParse->nMem;
92811    sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
92812  }else{
92813    int r1 = sqlite3GetTempReg(pParse);
92814    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
92815    if( r2==r1 ){
92816      *pReg = r1;
92817    }else{
92818      sqlite3ReleaseTempReg(pParse, r1);
92819      *pReg = 0;
92820    }
92821  }
92822  return r2;
92823}
92824
92825/*
92826** Generate code that will evaluate expression pExpr and store the
92827** results in register target.  The results are guaranteed to appear
92828** in register target.
92829*/
92830SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
92831  int inReg;
92832
92833  assert( target>0 && target<=pParse->nMem );
92834  if( pExpr && pExpr->op==TK_REGISTER ){
92835    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
92836  }else{
92837    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
92838    assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
92839    if( inReg!=target && pParse->pVdbe ){
92840      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
92841    }
92842  }
92843}
92844
92845/*
92846** Make a transient copy of expression pExpr and then code it using
92847** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
92848** except that the input expression is guaranteed to be unchanged.
92849*/
92850SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
92851  sqlite3 *db = pParse->db;
92852  pExpr = sqlite3ExprDup(db, pExpr, 0);
92853  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
92854  sqlite3ExprDelete(db, pExpr);
92855}
92856
92857/*
92858** Generate code that will evaluate expression pExpr and store the
92859** results in register target.  The results are guaranteed to appear
92860** in register target.  If the expression is constant, then this routine
92861** might choose to code the expression at initialization time.
92862*/
92863SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
92864  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
92865    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
92866  }else{
92867    sqlite3ExprCode(pParse, pExpr, target);
92868  }
92869}
92870
92871/*
92872** Generate code that evaluates the given expression and puts the result
92873** in register target.
92874**
92875** Also make a copy of the expression results into another "cache" register
92876** and modify the expression so that the next time it is evaluated,
92877** the result is a copy of the cache register.
92878**
92879** This routine is used for expressions that are used multiple
92880** times.  They are evaluated once and the results of the expression
92881** are reused.
92882*/
92883SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
92884  Vdbe *v = pParse->pVdbe;
92885  int iMem;
92886
92887  assert( target>0 );
92888  assert( pExpr->op!=TK_REGISTER );
92889  sqlite3ExprCode(pParse, pExpr, target);
92890  iMem = ++pParse->nMem;
92891  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
92892  exprToRegister(pExpr, iMem);
92893}
92894
92895/*
92896** Generate code that pushes the value of every element of the given
92897** expression list into a sequence of registers beginning at target.
92898**
92899** Return the number of elements evaluated.
92900**
92901** The SQLITE_ECEL_DUP flag prevents the arguments from being
92902** filled using OP_SCopy.  OP_Copy must be used instead.
92903**
92904** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
92905** factored out into initialization code.
92906**
92907** The SQLITE_ECEL_REF flag means that expressions in the list with
92908** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
92909** in registers at srcReg, and so the value can be copied from there.
92910*/
92911SQLITE_PRIVATE int sqlite3ExprCodeExprList(
92912  Parse *pParse,     /* Parsing context */
92913  ExprList *pList,   /* The expression list to be coded */
92914  int target,        /* Where to write results */
92915  int srcReg,        /* Source registers if SQLITE_ECEL_REF */
92916  u8 flags           /* SQLITE_ECEL_* flags */
92917){
92918  struct ExprList_item *pItem;
92919  int i, j, n;
92920  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
92921  Vdbe *v = pParse->pVdbe;
92922  assert( pList!=0 );
92923  assert( target>0 );
92924  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
92925  n = pList->nExpr;
92926  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
92927  for(pItem=pList->a, i=0; i<n; i++, pItem++){
92928    Expr *pExpr = pItem->pExpr;
92929    if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
92930      sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
92931    }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
92932      sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
92933    }else{
92934      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
92935      if( inReg!=target+i ){
92936        VdbeOp *pOp;
92937        if( copyOp==OP_Copy
92938         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
92939         && pOp->p1+pOp->p3+1==inReg
92940         && pOp->p2+pOp->p3+1==target+i
92941        ){
92942          pOp->p3++;
92943        }else{
92944          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
92945        }
92946      }
92947    }
92948  }
92949  return n;
92950}
92951
92952/*
92953** Generate code for a BETWEEN operator.
92954**
92955**    x BETWEEN y AND z
92956**
92957** The above is equivalent to
92958**
92959**    x>=y AND x<=z
92960**
92961** Code it as such, taking care to do the common subexpression
92962** elimination of x.
92963*/
92964static void exprCodeBetween(
92965  Parse *pParse,    /* Parsing and code generating context */
92966  Expr *pExpr,      /* The BETWEEN expression */
92967  int dest,         /* Jump here if the jump is taken */
92968  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
92969  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
92970){
92971  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
92972  Expr compLeft;    /* The  x>=y  term */
92973  Expr compRight;   /* The  x<=z  term */
92974  Expr exprX;       /* The  x  subexpression */
92975  int regFree1 = 0; /* Temporary use register */
92976
92977  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92978  exprX = *pExpr->pLeft;
92979  exprAnd.op = TK_AND;
92980  exprAnd.pLeft = &compLeft;
92981  exprAnd.pRight = &compRight;
92982  compLeft.op = TK_GE;
92983  compLeft.pLeft = &exprX;
92984  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
92985  compRight.op = TK_LE;
92986  compRight.pLeft = &exprX;
92987  compRight.pRight = pExpr->x.pList->a[1].pExpr;
92988  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
92989  if( jumpIfTrue ){
92990    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
92991  }else{
92992    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
92993  }
92994  sqlite3ReleaseTempReg(pParse, regFree1);
92995
92996  /* Ensure adequate test coverage */
92997  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
92998  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
92999  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
93000  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
93001  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
93002  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
93003  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
93004  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
93005}
93006
93007/*
93008** Generate code for a boolean expression such that a jump is made
93009** to the label "dest" if the expression is true but execution
93010** continues straight thru if the expression is false.
93011**
93012** If the expression evaluates to NULL (neither true nor false), then
93013** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
93014**
93015** This code depends on the fact that certain token values (ex: TK_EQ)
93016** are the same as opcode values (ex: OP_Eq) that implement the corresponding
93017** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
93018** the make process cause these values to align.  Assert()s in the code
93019** below verify that the numbers are aligned correctly.
93020*/
93021SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93022  Vdbe *v = pParse->pVdbe;
93023  int op = 0;
93024  int regFree1 = 0;
93025  int regFree2 = 0;
93026  int r1, r2;
93027
93028  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93029  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
93030  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
93031  op = pExpr->op;
93032  switch( op ){
93033    case TK_AND: {
93034      int d2 = sqlite3VdbeMakeLabel(v);
93035      testcase( jumpIfNull==0 );
93036      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
93037      sqlite3ExprCachePush(pParse);
93038      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93039      sqlite3VdbeResolveLabel(v, d2);
93040      sqlite3ExprCachePop(pParse);
93041      break;
93042    }
93043    case TK_OR: {
93044      testcase( jumpIfNull==0 );
93045      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93046      sqlite3ExprCachePush(pParse);
93047      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93048      sqlite3ExprCachePop(pParse);
93049      break;
93050    }
93051    case TK_NOT: {
93052      testcase( jumpIfNull==0 );
93053      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93054      break;
93055    }
93056    case TK_IS:
93057    case TK_ISNOT:
93058      testcase( op==TK_IS );
93059      testcase( op==TK_ISNOT );
93060      op = (op==TK_IS) ? TK_EQ : TK_NE;
93061      jumpIfNull = SQLITE_NULLEQ;
93062      /* Fall thru */
93063    case TK_LT:
93064    case TK_LE:
93065    case TK_GT:
93066    case TK_GE:
93067    case TK_NE:
93068    case TK_EQ: {
93069      testcase( jumpIfNull==0 );
93070      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93071      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93072      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93073                  r1, r2, dest, jumpIfNull);
93074      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93075      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93076      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93077      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93078      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93079      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93080      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93081      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93082      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93083      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93084      testcase( regFree1==0 );
93085      testcase( regFree2==0 );
93086      break;
93087    }
93088    case TK_ISNULL:
93089    case TK_NOTNULL: {
93090      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
93091      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
93092      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93093      sqlite3VdbeAddOp2(v, op, r1, dest);
93094      VdbeCoverageIf(v, op==TK_ISNULL);
93095      VdbeCoverageIf(v, op==TK_NOTNULL);
93096      testcase( regFree1==0 );
93097      break;
93098    }
93099    case TK_BETWEEN: {
93100      testcase( jumpIfNull==0 );
93101      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
93102      break;
93103    }
93104#ifndef SQLITE_OMIT_SUBQUERY
93105    case TK_IN: {
93106      int destIfFalse = sqlite3VdbeMakeLabel(v);
93107      int destIfNull = jumpIfNull ? dest : destIfFalse;
93108      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
93109      sqlite3VdbeGoto(v, dest);
93110      sqlite3VdbeResolveLabel(v, destIfFalse);
93111      break;
93112    }
93113#endif
93114    default: {
93115      if( exprAlwaysTrue(pExpr) ){
93116        sqlite3VdbeGoto(v, dest);
93117      }else if( exprAlwaysFalse(pExpr) ){
93118        /* No-op */
93119      }else{
93120        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
93121        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
93122        VdbeCoverage(v);
93123        testcase( regFree1==0 );
93124        testcase( jumpIfNull==0 );
93125      }
93126      break;
93127    }
93128  }
93129  sqlite3ReleaseTempReg(pParse, regFree1);
93130  sqlite3ReleaseTempReg(pParse, regFree2);
93131}
93132
93133/*
93134** Generate code for a boolean expression such that a jump is made
93135** to the label "dest" if the expression is false but execution
93136** continues straight thru if the expression is true.
93137**
93138** If the expression evaluates to NULL (neither true nor false) then
93139** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
93140** is 0.
93141*/
93142SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93143  Vdbe *v = pParse->pVdbe;
93144  int op = 0;
93145  int regFree1 = 0;
93146  int regFree2 = 0;
93147  int r1, r2;
93148
93149  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93150  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
93151  if( pExpr==0 )    return;
93152
93153  /* The value of pExpr->op and op are related as follows:
93154  **
93155  **       pExpr->op            op
93156  **       ---------          ----------
93157  **       TK_ISNULL          OP_NotNull
93158  **       TK_NOTNULL         OP_IsNull
93159  **       TK_NE              OP_Eq
93160  **       TK_EQ              OP_Ne
93161  **       TK_GT              OP_Le
93162  **       TK_LE              OP_Gt
93163  **       TK_GE              OP_Lt
93164  **       TK_LT              OP_Ge
93165  **
93166  ** For other values of pExpr->op, op is undefined and unused.
93167  ** The value of TK_ and OP_ constants are arranged such that we
93168  ** can compute the mapping above using the following expression.
93169  ** Assert()s verify that the computation is correct.
93170  */
93171  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
93172
93173  /* Verify correct alignment of TK_ and OP_ constants
93174  */
93175  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
93176  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
93177  assert( pExpr->op!=TK_NE || op==OP_Eq );
93178  assert( pExpr->op!=TK_EQ || op==OP_Ne );
93179  assert( pExpr->op!=TK_LT || op==OP_Ge );
93180  assert( pExpr->op!=TK_LE || op==OP_Gt );
93181  assert( pExpr->op!=TK_GT || op==OP_Le );
93182  assert( pExpr->op!=TK_GE || op==OP_Lt );
93183
93184  switch( pExpr->op ){
93185    case TK_AND: {
93186      testcase( jumpIfNull==0 );
93187      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93188      sqlite3ExprCachePush(pParse);
93189      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
93190      sqlite3ExprCachePop(pParse);
93191      break;
93192    }
93193    case TK_OR: {
93194      int d2 = sqlite3VdbeMakeLabel(v);
93195      testcase( jumpIfNull==0 );
93196      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
93197      sqlite3ExprCachePush(pParse);
93198      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
93199      sqlite3VdbeResolveLabel(v, d2);
93200      sqlite3ExprCachePop(pParse);
93201      break;
93202    }
93203    case TK_NOT: {
93204      testcase( jumpIfNull==0 );
93205      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93206      break;
93207    }
93208    case TK_IS:
93209    case TK_ISNOT:
93210      testcase( pExpr->op==TK_IS );
93211      testcase( pExpr->op==TK_ISNOT );
93212      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
93213      jumpIfNull = SQLITE_NULLEQ;
93214      /* Fall thru */
93215    case TK_LT:
93216    case TK_LE:
93217    case TK_GT:
93218    case TK_GE:
93219    case TK_NE:
93220    case TK_EQ: {
93221      testcase( jumpIfNull==0 );
93222      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93223      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93224      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93225                  r1, r2, dest, jumpIfNull);
93226      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93227      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93228      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93229      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93230      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93231      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93232      VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93233      assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93234      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93235      VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93236      testcase( regFree1==0 );
93237      testcase( regFree2==0 );
93238      break;
93239    }
93240    case TK_ISNULL:
93241    case TK_NOTNULL: {
93242      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93243      sqlite3VdbeAddOp2(v, op, r1, dest);
93244      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
93245      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
93246      testcase( regFree1==0 );
93247      break;
93248    }
93249    case TK_BETWEEN: {
93250      testcase( jumpIfNull==0 );
93251      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
93252      break;
93253    }
93254#ifndef SQLITE_OMIT_SUBQUERY
93255    case TK_IN: {
93256      if( jumpIfNull ){
93257        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
93258      }else{
93259        int destIfNull = sqlite3VdbeMakeLabel(v);
93260        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
93261        sqlite3VdbeResolveLabel(v, destIfNull);
93262      }
93263      break;
93264    }
93265#endif
93266    default: {
93267      if( exprAlwaysFalse(pExpr) ){
93268        sqlite3VdbeGoto(v, dest);
93269      }else if( exprAlwaysTrue(pExpr) ){
93270        /* no-op */
93271      }else{
93272        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
93273        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
93274        VdbeCoverage(v);
93275        testcase( regFree1==0 );
93276        testcase( jumpIfNull==0 );
93277      }
93278      break;
93279    }
93280  }
93281  sqlite3ReleaseTempReg(pParse, regFree1);
93282  sqlite3ReleaseTempReg(pParse, regFree2);
93283}
93284
93285/*
93286** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
93287** code generation, and that copy is deleted after code generation. This
93288** ensures that the original pExpr is unchanged.
93289*/
93290SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
93291  sqlite3 *db = pParse->db;
93292  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
93293  if( db->mallocFailed==0 ){
93294    sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
93295  }
93296  sqlite3ExprDelete(db, pCopy);
93297}
93298
93299
93300/*
93301** Do a deep comparison of two expression trees.  Return 0 if the two
93302** expressions are completely identical.  Return 1 if they differ only
93303** by a COLLATE operator at the top level.  Return 2 if there are differences
93304** other than the top-level COLLATE operator.
93305**
93306** If any subelement of pB has Expr.iTable==(-1) then it is allowed
93307** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
93308**
93309** The pA side might be using TK_REGISTER.  If that is the case and pB is
93310** not using TK_REGISTER but is otherwise equivalent, then still return 0.
93311**
93312** Sometimes this routine will return 2 even if the two expressions
93313** really are equivalent.  If we cannot prove that the expressions are
93314** identical, we return 2 just to be safe.  So if this routine
93315** returns 2, then you do not really know for certain if the two
93316** expressions are the same.  But if you get a 0 or 1 return, then you
93317** can be sure the expressions are the same.  In the places where
93318** this routine is used, it does not hurt to get an extra 2 - that
93319** just might result in some slightly slower code.  But returning
93320** an incorrect 0 or 1 could lead to a malfunction.
93321*/
93322SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
93323  u32 combinedFlags;
93324  if( pA==0 || pB==0 ){
93325    return pB==pA ? 0 : 2;
93326  }
93327  combinedFlags = pA->flags | pB->flags;
93328  if( combinedFlags & EP_IntValue ){
93329    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
93330      return 0;
93331    }
93332    return 2;
93333  }
93334  if( pA->op!=pB->op ){
93335    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
93336      return 1;
93337    }
93338    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
93339      return 1;
93340    }
93341    return 2;
93342  }
93343  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
93344    if( pA->op==TK_FUNCTION ){
93345      if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
93346    }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
93347      return pA->op==TK_COLLATE ? 1 : 2;
93348    }
93349  }
93350  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
93351  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
93352    if( combinedFlags & EP_xIsSelect ) return 2;
93353    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
93354    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
93355    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
93356    if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
93357      if( pA->iColumn!=pB->iColumn ) return 2;
93358      if( pA->iTable!=pB->iTable
93359       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
93360    }
93361  }
93362  return 0;
93363}
93364
93365/*
93366** Compare two ExprList objects.  Return 0 if they are identical and
93367** non-zero if they differ in any way.
93368**
93369** If any subelement of pB has Expr.iTable==(-1) then it is allowed
93370** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
93371**
93372** This routine might return non-zero for equivalent ExprLists.  The
93373** only consequence will be disabled optimizations.  But this routine
93374** must never return 0 if the two ExprList objects are different, or
93375** a malfunction will result.
93376**
93377** Two NULL pointers are considered to be the same.  But a NULL pointer
93378** always differs from a non-NULL pointer.
93379*/
93380SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
93381  int i;
93382  if( pA==0 && pB==0 ) return 0;
93383  if( pA==0 || pB==0 ) return 1;
93384  if( pA->nExpr!=pB->nExpr ) return 1;
93385  for(i=0; i<pA->nExpr; i++){
93386    Expr *pExprA = pA->a[i].pExpr;
93387    Expr *pExprB = pB->a[i].pExpr;
93388    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
93389    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
93390  }
93391  return 0;
93392}
93393
93394/*
93395** Return true if we can prove the pE2 will always be true if pE1 is
93396** true.  Return false if we cannot complete the proof or if pE2 might
93397** be false.  Examples:
93398**
93399**     pE1: x==5       pE2: x==5             Result: true
93400**     pE1: x>0        pE2: x==5             Result: false
93401**     pE1: x=21       pE2: x=21 OR y=43     Result: true
93402**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
93403**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
93404**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
93405**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
93406**
93407** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
93408** Expr.iTable<0 then assume a table number given by iTab.
93409**
93410** When in doubt, return false.  Returning true might give a performance
93411** improvement.  Returning false might cause a performance reduction, but
93412** it will always give the correct answer and is hence always safe.
93413*/
93414SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
93415  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
93416    return 1;
93417  }
93418  if( pE2->op==TK_OR
93419   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
93420             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
93421  ){
93422    return 1;
93423  }
93424  if( pE2->op==TK_NOTNULL
93425   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
93426   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
93427  ){
93428    return 1;
93429  }
93430  return 0;
93431}
93432
93433/*
93434** An instance of the following structure is used by the tree walker
93435** to determine if an expression can be evaluated by reference to the
93436** index only, without having to do a search for the corresponding
93437** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
93438** is the cursor for the table.
93439*/
93440struct IdxCover {
93441  Index *pIdx;     /* The index to be tested for coverage */
93442  int iCur;        /* Cursor number for the table corresponding to the index */
93443};
93444
93445/*
93446** Check to see if there are references to columns in table
93447** pWalker->u.pIdxCover->iCur can be satisfied using the index
93448** pWalker->u.pIdxCover->pIdx.
93449*/
93450static int exprIdxCover(Walker *pWalker, Expr *pExpr){
93451  if( pExpr->op==TK_COLUMN
93452   && pExpr->iTable==pWalker->u.pIdxCover->iCur
93453   && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
93454  ){
93455    pWalker->eCode = 1;
93456    return WRC_Abort;
93457  }
93458  return WRC_Continue;
93459}
93460
93461/*
93462** Determine if an index pIdx on table with cursor iCur contains will
93463** the expression pExpr.  Return true if the index does cover the
93464** expression and false if the pExpr expression references table columns
93465** that are not found in the index pIdx.
93466**
93467** An index covering an expression means that the expression can be
93468** evaluated using only the index and without having to lookup the
93469** corresponding table entry.
93470*/
93471SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
93472  Expr *pExpr,        /* The index to be tested */
93473  int iCur,           /* The cursor number for the corresponding table */
93474  Index *pIdx         /* The index that might be used for coverage */
93475){
93476  Walker w;
93477  struct IdxCover xcov;
93478  memset(&w, 0, sizeof(w));
93479  xcov.iCur = iCur;
93480  xcov.pIdx = pIdx;
93481  w.xExprCallback = exprIdxCover;
93482  w.u.pIdxCover = &xcov;
93483  sqlite3WalkExpr(&w, pExpr);
93484  return !w.eCode;
93485}
93486
93487
93488/*
93489** An instance of the following structure is used by the tree walker
93490** to count references to table columns in the arguments of an
93491** aggregate function, in order to implement the
93492** sqlite3FunctionThisSrc() routine.
93493*/
93494struct SrcCount {
93495  SrcList *pSrc;   /* One particular FROM clause in a nested query */
93496  int nThis;       /* Number of references to columns in pSrcList */
93497  int nOther;      /* Number of references to columns in other FROM clauses */
93498};
93499
93500/*
93501** Count the number of references to columns.
93502*/
93503static int exprSrcCount(Walker *pWalker, Expr *pExpr){
93504  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
93505  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
93506  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
93507  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
93508  ** NEVER() will need to be removed. */
93509  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
93510    int i;
93511    struct SrcCount *p = pWalker->u.pSrcCount;
93512    SrcList *pSrc = p->pSrc;
93513    int nSrc = pSrc ? pSrc->nSrc : 0;
93514    for(i=0; i<nSrc; i++){
93515      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
93516    }
93517    if( i<nSrc ){
93518      p->nThis++;
93519    }else{
93520      p->nOther++;
93521    }
93522  }
93523  return WRC_Continue;
93524}
93525
93526/*
93527** Determine if any of the arguments to the pExpr Function reference
93528** pSrcList.  Return true if they do.  Also return true if the function
93529** has no arguments or has only constant arguments.  Return false if pExpr
93530** references columns but not columns of tables found in pSrcList.
93531*/
93532SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
93533  Walker w;
93534  struct SrcCount cnt;
93535  assert( pExpr->op==TK_AGG_FUNCTION );
93536  memset(&w, 0, sizeof(w));
93537  w.xExprCallback = exprSrcCount;
93538  w.u.pSrcCount = &cnt;
93539  cnt.pSrc = pSrcList;
93540  cnt.nThis = 0;
93541  cnt.nOther = 0;
93542  sqlite3WalkExprList(&w, pExpr->x.pList);
93543  return cnt.nThis>0 || cnt.nOther==0;
93544}
93545
93546/*
93547** Add a new element to the pAggInfo->aCol[] array.  Return the index of
93548** the new element.  Return a negative number if malloc fails.
93549*/
93550static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
93551  int i;
93552  pInfo->aCol = sqlite3ArrayAllocate(
93553       db,
93554       pInfo->aCol,
93555       sizeof(pInfo->aCol[0]),
93556       &pInfo->nColumn,
93557       &i
93558  );
93559  return i;
93560}
93561
93562/*
93563** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
93564** the new element.  Return a negative number if malloc fails.
93565*/
93566static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
93567  int i;
93568  pInfo->aFunc = sqlite3ArrayAllocate(
93569       db,
93570       pInfo->aFunc,
93571       sizeof(pInfo->aFunc[0]),
93572       &pInfo->nFunc,
93573       &i
93574  );
93575  return i;
93576}
93577
93578/*
93579** This is the xExprCallback for a tree walker.  It is used to
93580** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
93581** for additional information.
93582*/
93583static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
93584  int i;
93585  NameContext *pNC = pWalker->u.pNC;
93586  Parse *pParse = pNC->pParse;
93587  SrcList *pSrcList = pNC->pSrcList;
93588  AggInfo *pAggInfo = pNC->pAggInfo;
93589
93590  switch( pExpr->op ){
93591    case TK_AGG_COLUMN:
93592    case TK_COLUMN: {
93593      testcase( pExpr->op==TK_AGG_COLUMN );
93594      testcase( pExpr->op==TK_COLUMN );
93595      /* Check to see if the column is in one of the tables in the FROM
93596      ** clause of the aggregate query */
93597      if( ALWAYS(pSrcList!=0) ){
93598        struct SrcList_item *pItem = pSrcList->a;
93599        for(i=0; i<pSrcList->nSrc; i++, pItem++){
93600          struct AggInfo_col *pCol;
93601          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
93602          if( pExpr->iTable==pItem->iCursor ){
93603            /* If we reach this point, it means that pExpr refers to a table
93604            ** that is in the FROM clause of the aggregate query.
93605            **
93606            ** Make an entry for the column in pAggInfo->aCol[] if there
93607            ** is not an entry there already.
93608            */
93609            int k;
93610            pCol = pAggInfo->aCol;
93611            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
93612              if( pCol->iTable==pExpr->iTable &&
93613                  pCol->iColumn==pExpr->iColumn ){
93614                break;
93615              }
93616            }
93617            if( (k>=pAggInfo->nColumn)
93618             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
93619            ){
93620              pCol = &pAggInfo->aCol[k];
93621              pCol->pTab = pExpr->pTab;
93622              pCol->iTable = pExpr->iTable;
93623              pCol->iColumn = pExpr->iColumn;
93624              pCol->iMem = ++pParse->nMem;
93625              pCol->iSorterColumn = -1;
93626              pCol->pExpr = pExpr;
93627              if( pAggInfo->pGroupBy ){
93628                int j, n;
93629                ExprList *pGB = pAggInfo->pGroupBy;
93630                struct ExprList_item *pTerm = pGB->a;
93631                n = pGB->nExpr;
93632                for(j=0; j<n; j++, pTerm++){
93633                  Expr *pE = pTerm->pExpr;
93634                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
93635                      pE->iColumn==pExpr->iColumn ){
93636                    pCol->iSorterColumn = j;
93637                    break;
93638                  }
93639                }
93640              }
93641              if( pCol->iSorterColumn<0 ){
93642                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
93643              }
93644            }
93645            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
93646            ** because it was there before or because we just created it).
93647            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
93648            ** pAggInfo->aCol[] entry.
93649            */
93650            ExprSetVVAProperty(pExpr, EP_NoReduce);
93651            pExpr->pAggInfo = pAggInfo;
93652            pExpr->op = TK_AGG_COLUMN;
93653            pExpr->iAgg = (i16)k;
93654            break;
93655          } /* endif pExpr->iTable==pItem->iCursor */
93656        } /* end loop over pSrcList */
93657      }
93658      return WRC_Prune;
93659    }
93660    case TK_AGG_FUNCTION: {
93661      if( (pNC->ncFlags & NC_InAggFunc)==0
93662       && pWalker->walkerDepth==pExpr->op2
93663      ){
93664        /* Check to see if pExpr is a duplicate of another aggregate
93665        ** function that is already in the pAggInfo structure
93666        */
93667        struct AggInfo_func *pItem = pAggInfo->aFunc;
93668        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
93669          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
93670            break;
93671          }
93672        }
93673        if( i>=pAggInfo->nFunc ){
93674          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
93675          */
93676          u8 enc = ENC(pParse->db);
93677          i = addAggInfoFunc(pParse->db, pAggInfo);
93678          if( i>=0 ){
93679            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93680            pItem = &pAggInfo->aFunc[i];
93681            pItem->pExpr = pExpr;
93682            pItem->iMem = ++pParse->nMem;
93683            assert( !ExprHasProperty(pExpr, EP_IntValue) );
93684            pItem->pFunc = sqlite3FindFunction(pParse->db,
93685                   pExpr->u.zToken,
93686                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
93687            if( pExpr->flags & EP_Distinct ){
93688              pItem->iDistinct = pParse->nTab++;
93689            }else{
93690              pItem->iDistinct = -1;
93691            }
93692          }
93693        }
93694        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
93695        */
93696        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
93697        ExprSetVVAProperty(pExpr, EP_NoReduce);
93698        pExpr->iAgg = (i16)i;
93699        pExpr->pAggInfo = pAggInfo;
93700        return WRC_Prune;
93701      }else{
93702        return WRC_Continue;
93703      }
93704    }
93705  }
93706  return WRC_Continue;
93707}
93708static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
93709  UNUSED_PARAMETER(pWalker);
93710  UNUSED_PARAMETER(pSelect);
93711  return WRC_Continue;
93712}
93713
93714/*
93715** Analyze the pExpr expression looking for aggregate functions and
93716** for variables that need to be added to AggInfo object that pNC->pAggInfo
93717** points to.  Additional entries are made on the AggInfo object as
93718** necessary.
93719**
93720** This routine should only be called after the expression has been
93721** analyzed by sqlite3ResolveExprNames().
93722*/
93723SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
93724  Walker w;
93725  memset(&w, 0, sizeof(w));
93726  w.xExprCallback = analyzeAggregate;
93727  w.xSelectCallback = analyzeAggregatesInSelect;
93728  w.u.pNC = pNC;
93729  assert( pNC->pSrcList!=0 );
93730  sqlite3WalkExpr(&w, pExpr);
93731}
93732
93733/*
93734** Call sqlite3ExprAnalyzeAggregates() for every expression in an
93735** expression list.  Return the number of errors.
93736**
93737** If an error is found, the analysis is cut short.
93738*/
93739SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
93740  struct ExprList_item *pItem;
93741  int i;
93742  if( pList ){
93743    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
93744      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
93745    }
93746  }
93747}
93748
93749/*
93750** Allocate a single new register for use to hold some intermediate result.
93751*/
93752SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
93753  if( pParse->nTempReg==0 ){
93754    return ++pParse->nMem;
93755  }
93756  return pParse->aTempReg[--pParse->nTempReg];
93757}
93758
93759/*
93760** Deallocate a register, making available for reuse for some other
93761** purpose.
93762**
93763** If a register is currently being used by the column cache, then
93764** the deallocation is deferred until the column cache line that uses
93765** the register becomes stale.
93766*/
93767SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
93768  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
93769    int i;
93770    struct yColCache *p;
93771    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
93772      if( p->iReg==iReg ){
93773        p->tempReg = 1;
93774        return;
93775      }
93776    }
93777    pParse->aTempReg[pParse->nTempReg++] = iReg;
93778  }
93779}
93780
93781/*
93782** Allocate or deallocate a block of nReg consecutive registers
93783*/
93784SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
93785  int i, n;
93786  i = pParse->iRangeReg;
93787  n = pParse->nRangeReg;
93788  if( nReg<=n ){
93789    assert( !usedAsColumnCache(pParse, i, i+n-1) );
93790    pParse->iRangeReg += nReg;
93791    pParse->nRangeReg -= nReg;
93792  }else{
93793    i = pParse->nMem+1;
93794    pParse->nMem += nReg;
93795  }
93796  return i;
93797}
93798SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
93799  sqlite3ExprCacheRemove(pParse, iReg, nReg);
93800  if( nReg>pParse->nRangeReg ){
93801    pParse->nRangeReg = nReg;
93802    pParse->iRangeReg = iReg;
93803  }
93804}
93805
93806/*
93807** Mark all temporary registers as being unavailable for reuse.
93808*/
93809SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
93810  pParse->nTempReg = 0;
93811  pParse->nRangeReg = 0;
93812}
93813
93814/*
93815** Validate that no temporary register falls within the range of
93816** iFirst..iLast, inclusive.  This routine is only call from within assert()
93817** statements.
93818*/
93819#ifdef SQLITE_DEBUG
93820SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
93821  int i;
93822  if( pParse->nRangeReg>0
93823   && pParse->iRangeReg+pParse->nRangeReg<iLast
93824   && pParse->iRangeReg>=iFirst
93825  ){
93826     return 0;
93827  }
93828  for(i=0; i<pParse->nTempReg; i++){
93829    if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
93830      return 0;
93831    }
93832  }
93833  return 1;
93834}
93835#endif /* SQLITE_DEBUG */
93836
93837/************** End of expr.c ************************************************/
93838/************** Begin file alter.c *******************************************/
93839/*
93840** 2005 February 15
93841**
93842** The author disclaims copyright to this source code.  In place of
93843** a legal notice, here is a blessing:
93844**
93845**    May you do good and not evil.
93846**    May you find forgiveness for yourself and forgive others.
93847**    May you share freely, never taking more than you give.
93848**
93849*************************************************************************
93850** This file contains C code routines that used to generate VDBE code
93851** that implements the ALTER TABLE command.
93852*/
93853/* #include "sqliteInt.h" */
93854
93855/*
93856** The code in this file only exists if we are not omitting the
93857** ALTER TABLE logic from the build.
93858*/
93859#ifndef SQLITE_OMIT_ALTERTABLE
93860
93861
93862/*
93863** This function is used by SQL generated to implement the
93864** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
93865** CREATE INDEX command. The second is a table name. The table name in
93866** the CREATE TABLE or CREATE INDEX statement is replaced with the third
93867** argument and the result returned. Examples:
93868**
93869** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
93870**     -> 'CREATE TABLE def(a, b, c)'
93871**
93872** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
93873**     -> 'CREATE INDEX i ON def(a, b, c)'
93874*/
93875static void renameTableFunc(
93876  sqlite3_context *context,
93877  int NotUsed,
93878  sqlite3_value **argv
93879){
93880  unsigned char const *zSql = sqlite3_value_text(argv[0]);
93881  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
93882
93883  int token;
93884  Token tname;
93885  unsigned char const *zCsr = zSql;
93886  int len = 0;
93887  char *zRet;
93888
93889  sqlite3 *db = sqlite3_context_db_handle(context);
93890
93891  UNUSED_PARAMETER(NotUsed);
93892
93893  /* The principle used to locate the table name in the CREATE TABLE
93894  ** statement is that the table name is the first non-space token that
93895  ** is immediately followed by a TK_LP or TK_USING token.
93896  */
93897  if( zSql ){
93898    do {
93899      if( !*zCsr ){
93900        /* Ran out of input before finding an opening bracket. Return NULL. */
93901        return;
93902      }
93903
93904      /* Store the token that zCsr points to in tname. */
93905      tname.z = (char*)zCsr;
93906      tname.n = len;
93907
93908      /* Advance zCsr to the next token. Store that token type in 'token',
93909      ** and its length in 'len' (to be used next iteration of this loop).
93910      */
93911      do {
93912        zCsr += len;
93913        len = sqlite3GetToken(zCsr, &token);
93914      } while( token==TK_SPACE );
93915      assert( len>0 );
93916    } while( token!=TK_LP && token!=TK_USING );
93917
93918    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
93919       zSql, zTableName, tname.z+tname.n);
93920    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
93921  }
93922}
93923
93924/*
93925** This C function implements an SQL user function that is used by SQL code
93926** generated by the ALTER TABLE ... RENAME command to modify the definition
93927** of any foreign key constraints that use the table being renamed as the
93928** parent table. It is passed three arguments:
93929**
93930**   1) The complete text of the CREATE TABLE statement being modified,
93931**   2) The old name of the table being renamed, and
93932**   3) The new name of the table being renamed.
93933**
93934** It returns the new CREATE TABLE statement. For example:
93935**
93936**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
93937**       -> 'CREATE TABLE t1(a REFERENCES t3)'
93938*/
93939#ifndef SQLITE_OMIT_FOREIGN_KEY
93940static void renameParentFunc(
93941  sqlite3_context *context,
93942  int NotUsed,
93943  sqlite3_value **argv
93944){
93945  sqlite3 *db = sqlite3_context_db_handle(context);
93946  char *zOutput = 0;
93947  char *zResult;
93948  unsigned char const *zInput = sqlite3_value_text(argv[0]);
93949  unsigned char const *zOld = sqlite3_value_text(argv[1]);
93950  unsigned char const *zNew = sqlite3_value_text(argv[2]);
93951
93952  unsigned const char *z;         /* Pointer to token */
93953  int n;                          /* Length of token z */
93954  int token;                      /* Type of token */
93955
93956  UNUSED_PARAMETER(NotUsed);
93957  if( zInput==0 || zOld==0 ) return;
93958  for(z=zInput; *z; z=z+n){
93959    n = sqlite3GetToken(z, &token);
93960    if( token==TK_REFERENCES ){
93961      char *zParent;
93962      do {
93963        z += n;
93964        n = sqlite3GetToken(z, &token);
93965      }while( token==TK_SPACE );
93966
93967      if( token==TK_ILLEGAL ) break;
93968      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
93969      if( zParent==0 ) break;
93970      sqlite3Dequote(zParent);
93971      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
93972        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
93973            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
93974        );
93975        sqlite3DbFree(db, zOutput);
93976        zOutput = zOut;
93977        zInput = &z[n];
93978      }
93979      sqlite3DbFree(db, zParent);
93980    }
93981  }
93982
93983  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
93984  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
93985  sqlite3DbFree(db, zOutput);
93986}
93987#endif
93988
93989#ifndef SQLITE_OMIT_TRIGGER
93990/* This function is used by SQL generated to implement the
93991** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
93992** statement. The second is a table name. The table name in the CREATE
93993** TRIGGER statement is replaced with the third argument and the result
93994** returned. This is analagous to renameTableFunc() above, except for CREATE
93995** TRIGGER, not CREATE INDEX and CREATE TABLE.
93996*/
93997static void renameTriggerFunc(
93998  sqlite3_context *context,
93999  int NotUsed,
94000  sqlite3_value **argv
94001){
94002  unsigned char const *zSql = sqlite3_value_text(argv[0]);
94003  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
94004
94005  int token;
94006  Token tname;
94007  int dist = 3;
94008  unsigned char const *zCsr = zSql;
94009  int len = 0;
94010  char *zRet;
94011  sqlite3 *db = sqlite3_context_db_handle(context);
94012
94013  UNUSED_PARAMETER(NotUsed);
94014
94015  /* The principle used to locate the table name in the CREATE TRIGGER
94016  ** statement is that the table name is the first token that is immediately
94017  ** preceded by either TK_ON or TK_DOT and immediately followed by one
94018  ** of TK_WHEN, TK_BEGIN or TK_FOR.
94019  */
94020  if( zSql ){
94021    do {
94022
94023      if( !*zCsr ){
94024        /* Ran out of input before finding the table name. Return NULL. */
94025        return;
94026      }
94027
94028      /* Store the token that zCsr points to in tname. */
94029      tname.z = (char*)zCsr;
94030      tname.n = len;
94031
94032      /* Advance zCsr to the next token. Store that token type in 'token',
94033      ** and its length in 'len' (to be used next iteration of this loop).
94034      */
94035      do {
94036        zCsr += len;
94037        len = sqlite3GetToken(zCsr, &token);
94038      }while( token==TK_SPACE );
94039      assert( len>0 );
94040
94041      /* Variable 'dist' stores the number of tokens read since the most
94042      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
94043      ** token is read and 'dist' equals 2, the condition stated above
94044      ** to be met.
94045      **
94046      ** Note that ON cannot be a database, table or column name, so
94047      ** there is no need to worry about syntax like
94048      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
94049      */
94050      dist++;
94051      if( token==TK_DOT || token==TK_ON ){
94052        dist = 0;
94053      }
94054    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
94055
94056    /* Variable tname now contains the token that is the old table-name
94057    ** in the CREATE TRIGGER statement.
94058    */
94059    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94060       zSql, zTableName, tname.z+tname.n);
94061    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94062  }
94063}
94064#endif   /* !SQLITE_OMIT_TRIGGER */
94065
94066/*
94067** Register built-in functions used to help implement ALTER TABLE
94068*/
94069SQLITE_PRIVATE void sqlite3AlterFunctions(void){
94070  static FuncDef aAlterTableFuncs[] = {
94071    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
94072#ifndef SQLITE_OMIT_TRIGGER
94073    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
94074#endif
94075#ifndef SQLITE_OMIT_FOREIGN_KEY
94076    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
94077#endif
94078  };
94079  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
94080}
94081
94082/*
94083** This function is used to create the text of expressions of the form:
94084**
94085**   name=<constant1> OR name=<constant2> OR ...
94086**
94087** If argument zWhere is NULL, then a pointer string containing the text
94088** "name=<constant>" is returned, where <constant> is the quoted version
94089** of the string passed as argument zConstant. The returned buffer is
94090** allocated using sqlite3DbMalloc(). It is the responsibility of the
94091** caller to ensure that it is eventually freed.
94092**
94093** If argument zWhere is not NULL, then the string returned is
94094** "<where> OR name=<constant>", where <where> is the contents of zWhere.
94095** In this case zWhere is passed to sqlite3DbFree() before returning.
94096**
94097*/
94098static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
94099  char *zNew;
94100  if( !zWhere ){
94101    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
94102  }else{
94103    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
94104    sqlite3DbFree(db, zWhere);
94105  }
94106  return zNew;
94107}
94108
94109#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94110/*
94111** Generate the text of a WHERE expression which can be used to select all
94112** tables that have foreign key constraints that refer to table pTab (i.e.
94113** constraints for which pTab is the parent table) from the sqlite_master
94114** table.
94115*/
94116static char *whereForeignKeys(Parse *pParse, Table *pTab){
94117  FKey *p;
94118  char *zWhere = 0;
94119  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
94120    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
94121  }
94122  return zWhere;
94123}
94124#endif
94125
94126/*
94127** Generate the text of a WHERE expression which can be used to select all
94128** temporary triggers on table pTab from the sqlite_temp_master table. If
94129** table pTab has no temporary triggers, or is itself stored in the
94130** temporary database, NULL is returned.
94131*/
94132static char *whereTempTriggers(Parse *pParse, Table *pTab){
94133  Trigger *pTrig;
94134  char *zWhere = 0;
94135  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
94136
94137  /* If the table is not located in the temp-db (in which case NULL is
94138  ** returned, loop through the tables list of triggers. For each trigger
94139  ** that is not part of the temp-db schema, add a clause to the WHERE
94140  ** expression being built up in zWhere.
94141  */
94142  if( pTab->pSchema!=pTempSchema ){
94143    sqlite3 *db = pParse->db;
94144    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
94145      if( pTrig->pSchema==pTempSchema ){
94146        zWhere = whereOrName(db, zWhere, pTrig->zName);
94147      }
94148    }
94149  }
94150  if( zWhere ){
94151    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
94152    sqlite3DbFree(pParse->db, zWhere);
94153    zWhere = zNew;
94154  }
94155  return zWhere;
94156}
94157
94158/*
94159** Generate code to drop and reload the internal representation of table
94160** pTab from the database, including triggers and temporary triggers.
94161** Argument zName is the name of the table in the database schema at
94162** the time the generated code is executed. This can be different from
94163** pTab->zName if this function is being called to code part of an
94164** "ALTER TABLE RENAME TO" statement.
94165*/
94166static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
94167  Vdbe *v;
94168  char *zWhere;
94169  int iDb;                   /* Index of database containing pTab */
94170#ifndef SQLITE_OMIT_TRIGGER
94171  Trigger *pTrig;
94172#endif
94173
94174  v = sqlite3GetVdbe(pParse);
94175  if( NEVER(v==0) ) return;
94176  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
94177  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94178  assert( iDb>=0 );
94179
94180#ifndef SQLITE_OMIT_TRIGGER
94181  /* Drop any table triggers from the internal schema. */
94182  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
94183    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
94184    assert( iTrigDb==iDb || iTrigDb==1 );
94185    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
94186  }
94187#endif
94188
94189  /* Drop the table and index from the internal schema.  */
94190  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
94191
94192  /* Reload the table, index and permanent trigger schemas. */
94193  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
94194  if( !zWhere ) return;
94195  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
94196
94197#ifndef SQLITE_OMIT_TRIGGER
94198  /* Now, if the table is not stored in the temp database, reload any temp
94199  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
94200  */
94201  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
94202    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
94203  }
94204#endif
94205}
94206
94207/*
94208** Parameter zName is the name of a table that is about to be altered
94209** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
94210** If the table is a system table, this function leaves an error message
94211** in pParse->zErr (system tables may not be altered) and returns non-zero.
94212**
94213** Or, if zName is not a system table, zero is returned.
94214*/
94215static int isSystemTable(Parse *pParse, const char *zName){
94216  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
94217    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
94218    return 1;
94219  }
94220  return 0;
94221}
94222
94223/*
94224** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
94225** command.
94226*/
94227SQLITE_PRIVATE void sqlite3AlterRenameTable(
94228  Parse *pParse,            /* Parser context. */
94229  SrcList *pSrc,            /* The table to rename. */
94230  Token *pName              /* The new table name. */
94231){
94232  int iDb;                  /* Database that contains the table */
94233  char *zDb;                /* Name of database iDb */
94234  Table *pTab;              /* Table being renamed */
94235  char *zName = 0;          /* NULL-terminated version of pName */
94236  sqlite3 *db = pParse->db; /* Database connection */
94237  int nTabName;             /* Number of UTF-8 characters in zTabName */
94238  const char *zTabName;     /* Original name of the table */
94239  Vdbe *v;
94240#ifndef SQLITE_OMIT_TRIGGER
94241  char *zWhere = 0;         /* Where clause to locate temp triggers */
94242#endif
94243  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
94244  int savedDbFlags;         /* Saved value of db->flags */
94245
94246  savedDbFlags = db->flags;
94247  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
94248  assert( pSrc->nSrc==1 );
94249  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
94250
94251  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
94252  if( !pTab ) goto exit_rename_table;
94253  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94254  zDb = db->aDb[iDb].zName;
94255  db->flags |= SQLITE_PreferBuiltin;
94256
94257  /* Get a NULL terminated version of the new table name. */
94258  zName = sqlite3NameFromToken(db, pName);
94259  if( !zName ) goto exit_rename_table;
94260
94261  /* Check that a table or index named 'zName' does not already exist
94262  ** in database iDb. If so, this is an error.
94263  */
94264  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
94265    sqlite3ErrorMsg(pParse,
94266        "there is already another table or index with this name: %s", zName);
94267    goto exit_rename_table;
94268  }
94269
94270  /* Make sure it is not a system table being altered, or a reserved name
94271  ** that the table is being renamed to.
94272  */
94273  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
94274    goto exit_rename_table;
94275  }
94276  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
94277    exit_rename_table;
94278  }
94279
94280#ifndef SQLITE_OMIT_VIEW
94281  if( pTab->pSelect ){
94282    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
94283    goto exit_rename_table;
94284  }
94285#endif
94286
94287#ifndef SQLITE_OMIT_AUTHORIZATION
94288  /* Invoke the authorization callback. */
94289  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
94290    goto exit_rename_table;
94291  }
94292#endif
94293
94294#ifndef SQLITE_OMIT_VIRTUALTABLE
94295  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
94296    goto exit_rename_table;
94297  }
94298  if( IsVirtual(pTab) ){
94299    pVTab = sqlite3GetVTable(db, pTab);
94300    if( pVTab->pVtab->pModule->xRename==0 ){
94301      pVTab = 0;
94302    }
94303  }
94304#endif
94305
94306  /* Begin a transaction for database iDb.
94307  ** Then modify the schema cookie (since the ALTER TABLE modifies the
94308  ** schema). Open a statement transaction if the table is a virtual
94309  ** table.
94310  */
94311  v = sqlite3GetVdbe(pParse);
94312  if( v==0 ){
94313    goto exit_rename_table;
94314  }
94315  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
94316  sqlite3ChangeCookie(pParse, iDb);
94317
94318  /* If this is a virtual table, invoke the xRename() function if
94319  ** one is defined. The xRename() callback will modify the names
94320  ** of any resources used by the v-table implementation (including other
94321  ** SQLite tables) that are identified by the name of the virtual table.
94322  */
94323#ifndef SQLITE_OMIT_VIRTUALTABLE
94324  if( pVTab ){
94325    int i = ++pParse->nMem;
94326    sqlite3VdbeLoadString(v, i, zName);
94327    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
94328    sqlite3MayAbort(pParse);
94329  }
94330#endif
94331
94332  /* figure out how many UTF-8 characters are in zName */
94333  zTabName = pTab->zName;
94334  nTabName = sqlite3Utf8CharLen(zTabName, -1);
94335
94336#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94337  if( db->flags&SQLITE_ForeignKeys ){
94338    /* If foreign-key support is enabled, rewrite the CREATE TABLE
94339    ** statements corresponding to all child tables of foreign key constraints
94340    ** for which the renamed table is the parent table.  */
94341    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
94342      sqlite3NestedParse(pParse,
94343          "UPDATE \"%w\".%s SET "
94344              "sql = sqlite_rename_parent(sql, %Q, %Q) "
94345              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
94346      sqlite3DbFree(db, zWhere);
94347    }
94348  }
94349#endif
94350
94351  /* Modify the sqlite_master table to use the new table name. */
94352  sqlite3NestedParse(pParse,
94353      "UPDATE %Q.%s SET "
94354#ifdef SQLITE_OMIT_TRIGGER
94355          "sql = sqlite_rename_table(sql, %Q), "
94356#else
94357          "sql = CASE "
94358            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
94359            "ELSE sqlite_rename_table(sql, %Q) END, "
94360#endif
94361          "tbl_name = %Q, "
94362          "name = CASE "
94363            "WHEN type='table' THEN %Q "
94364            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
94365             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
94366            "ELSE name END "
94367      "WHERE tbl_name=%Q COLLATE nocase AND "
94368          "(type='table' OR type='index' OR type='trigger');",
94369      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
94370#ifndef SQLITE_OMIT_TRIGGER
94371      zName,
94372#endif
94373      zName, nTabName, zTabName
94374  );
94375
94376#ifndef SQLITE_OMIT_AUTOINCREMENT
94377  /* If the sqlite_sequence table exists in this database, then update
94378  ** it with the new table name.
94379  */
94380  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
94381    sqlite3NestedParse(pParse,
94382        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
94383        zDb, zName, pTab->zName);
94384  }
94385#endif
94386
94387#ifndef SQLITE_OMIT_TRIGGER
94388  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
94389  ** table. Don't do this if the table being ALTERed is itself located in
94390  ** the temp database.
94391  */
94392  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
94393    sqlite3NestedParse(pParse,
94394        "UPDATE sqlite_temp_master SET "
94395            "sql = sqlite_rename_trigger(sql, %Q), "
94396            "tbl_name = %Q "
94397            "WHERE %s;", zName, zName, zWhere);
94398    sqlite3DbFree(db, zWhere);
94399  }
94400#endif
94401
94402#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94403  if( db->flags&SQLITE_ForeignKeys ){
94404    FKey *p;
94405    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
94406      Table *pFrom = p->pFrom;
94407      if( pFrom!=pTab ){
94408        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
94409      }
94410    }
94411  }
94412#endif
94413
94414  /* Drop and reload the internal table schema. */
94415  reloadTableSchema(pParse, pTab, zName);
94416
94417exit_rename_table:
94418  sqlite3SrcListDelete(db, pSrc);
94419  sqlite3DbFree(db, zName);
94420  db->flags = savedDbFlags;
94421}
94422
94423/*
94424** This function is called after an "ALTER TABLE ... ADD" statement
94425** has been parsed. Argument pColDef contains the text of the new
94426** column definition.
94427**
94428** The Table structure pParse->pNewTable was extended to include
94429** the new column during parsing.
94430*/
94431SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
94432  Table *pNew;              /* Copy of pParse->pNewTable */
94433  Table *pTab;              /* Table being altered */
94434  int iDb;                  /* Database number */
94435  const char *zDb;          /* Database name */
94436  const char *zTab;         /* Table name */
94437  char *zCol;               /* Null-terminated column definition */
94438  Column *pCol;             /* The new column */
94439  Expr *pDflt;              /* Default value for the new column */
94440  sqlite3 *db;              /* The database connection; */
94441  Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
94442  int r1;                   /* Temporary registers */
94443
94444  db = pParse->db;
94445  if( pParse->nErr || db->mallocFailed ) return;
94446  assert( v!=0 );
94447  pNew = pParse->pNewTable;
94448  assert( pNew );
94449
94450  assert( sqlite3BtreeHoldsAllMutexes(db) );
94451  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
94452  zDb = db->aDb[iDb].zName;
94453  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
94454  pCol = &pNew->aCol[pNew->nCol-1];
94455  pDflt = pCol->pDflt;
94456  pTab = sqlite3FindTable(db, zTab, zDb);
94457  assert( pTab );
94458
94459#ifndef SQLITE_OMIT_AUTHORIZATION
94460  /* Invoke the authorization callback. */
94461  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
94462    return;
94463  }
94464#endif
94465
94466  /* If the default value for the new column was specified with a
94467  ** literal NULL, then set pDflt to 0. This simplifies checking
94468  ** for an SQL NULL default below.
94469  */
94470  assert( pDflt==0 || pDflt->op==TK_SPAN );
94471  if( pDflt && pDflt->pLeft->op==TK_NULL ){
94472    pDflt = 0;
94473  }
94474
94475  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
94476  ** If there is a NOT NULL constraint, then the default value for the
94477  ** column must not be NULL.
94478  */
94479  if( pCol->colFlags & COLFLAG_PRIMKEY ){
94480    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
94481    return;
94482  }
94483  if( pNew->pIndex ){
94484    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
94485    return;
94486  }
94487  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
94488    sqlite3ErrorMsg(pParse,
94489        "Cannot add a REFERENCES column with non-NULL default value");
94490    return;
94491  }
94492  if( pCol->notNull && !pDflt ){
94493    sqlite3ErrorMsg(pParse,
94494        "Cannot add a NOT NULL column with default value NULL");
94495    return;
94496  }
94497
94498  /* Ensure the default expression is something that sqlite3ValueFromExpr()
94499  ** can handle (i.e. not CURRENT_TIME etc.)
94500  */
94501  if( pDflt ){
94502    sqlite3_value *pVal = 0;
94503    int rc;
94504    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
94505    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
94506    if( rc!=SQLITE_OK ){
94507      assert( db->mallocFailed == 1 );
94508      return;
94509    }
94510    if( !pVal ){
94511      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
94512      return;
94513    }
94514    sqlite3ValueFree(pVal);
94515  }
94516
94517  /* Modify the CREATE TABLE statement. */
94518  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
94519  if( zCol ){
94520    char *zEnd = &zCol[pColDef->n-1];
94521    int savedDbFlags = db->flags;
94522    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
94523      *zEnd-- = '\0';
94524    }
94525    db->flags |= SQLITE_PreferBuiltin;
94526    sqlite3NestedParse(pParse,
94527        "UPDATE \"%w\".%s SET "
94528          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
94529        "WHERE type = 'table' AND name = %Q",
94530      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
94531      zTab
94532    );
94533    sqlite3DbFree(db, zCol);
94534    db->flags = savedDbFlags;
94535  }
94536
94537  /* Make sure the schema version is at least 3.  But do not upgrade
94538  ** from less than 3 to 4, as that will corrupt any preexisting DESC
94539  ** index.
94540  */
94541  r1 = sqlite3GetTempReg(pParse);
94542  sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
94543  sqlite3VdbeUsesBtree(v, iDb);
94544  sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
94545  sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
94546  VdbeCoverage(v);
94547  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
94548  sqlite3ReleaseTempReg(pParse, r1);
94549
94550  /* Reload the schema of the modified table. */
94551  reloadTableSchema(pParse, pTab, pTab->zName);
94552}
94553
94554/*
94555** This function is called by the parser after the table-name in
94556** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
94557** pSrc is the full-name of the table being altered.
94558**
94559** This routine makes a (partial) copy of the Table structure
94560** for the table being altered and sets Parse.pNewTable to point
94561** to it. Routines called by the parser as the column definition
94562** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
94563** the copy. The copy of the Table structure is deleted by tokenize.c
94564** after parsing is finished.
94565**
94566** Routine sqlite3AlterFinishAddColumn() will be called to complete
94567** coding the "ALTER TABLE ... ADD" statement.
94568*/
94569SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
94570  Table *pNew;
94571  Table *pTab;
94572  Vdbe *v;
94573  int iDb;
94574  int i;
94575  int nAlloc;
94576  sqlite3 *db = pParse->db;
94577
94578  /* Look up the table being altered. */
94579  assert( pParse->pNewTable==0 );
94580  assert( sqlite3BtreeHoldsAllMutexes(db) );
94581  if( db->mallocFailed ) goto exit_begin_add_column;
94582  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
94583  if( !pTab ) goto exit_begin_add_column;
94584
94585#ifndef SQLITE_OMIT_VIRTUALTABLE
94586  if( IsVirtual(pTab) ){
94587    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
94588    goto exit_begin_add_column;
94589  }
94590#endif
94591
94592  /* Make sure this is not an attempt to ALTER a view. */
94593  if( pTab->pSelect ){
94594    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
94595    goto exit_begin_add_column;
94596  }
94597  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
94598    goto exit_begin_add_column;
94599  }
94600
94601  assert( pTab->addColOffset>0 );
94602  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94603
94604  /* Put a copy of the Table struct in Parse.pNewTable for the
94605  ** sqlite3AddColumn() function and friends to modify.  But modify
94606  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
94607  ** prefix, we insure that the name will not collide with an existing
94608  ** table because user table are not allowed to have the "sqlite_"
94609  ** prefix on their name.
94610  */
94611  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
94612  if( !pNew ) goto exit_begin_add_column;
94613  pParse->pNewTable = pNew;
94614  pNew->nRef = 1;
94615  pNew->nCol = pTab->nCol;
94616  assert( pNew->nCol>0 );
94617  nAlloc = (((pNew->nCol-1)/8)*8)+8;
94618  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
94619  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
94620  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
94621  if( !pNew->aCol || !pNew->zName ){
94622    assert( db->mallocFailed );
94623    goto exit_begin_add_column;
94624  }
94625  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
94626  for(i=0; i<pNew->nCol; i++){
94627    Column *pCol = &pNew->aCol[i];
94628    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
94629    pCol->zColl = 0;
94630    pCol->pDflt = 0;
94631  }
94632  pNew->pSchema = db->aDb[iDb].pSchema;
94633  pNew->addColOffset = pTab->addColOffset;
94634  pNew->nRef = 1;
94635
94636  /* Begin a transaction and increment the schema cookie.  */
94637  sqlite3BeginWriteOperation(pParse, 0, iDb);
94638  v = sqlite3GetVdbe(pParse);
94639  if( !v ) goto exit_begin_add_column;
94640  sqlite3ChangeCookie(pParse, iDb);
94641
94642exit_begin_add_column:
94643  sqlite3SrcListDelete(db, pSrc);
94644  return;
94645}
94646#endif  /* SQLITE_ALTER_TABLE */
94647
94648/************** End of alter.c ***********************************************/
94649/************** Begin file analyze.c *****************************************/
94650/*
94651** 2005-07-08
94652**
94653** The author disclaims copyright to this source code.  In place of
94654** a legal notice, here is a blessing:
94655**
94656**    May you do good and not evil.
94657**    May you find forgiveness for yourself and forgive others.
94658**    May you share freely, never taking more than you give.
94659**
94660*************************************************************************
94661** This file contains code associated with the ANALYZE command.
94662**
94663** The ANALYZE command gather statistics about the content of tables
94664** and indices.  These statistics are made available to the query planner
94665** to help it make better decisions about how to perform queries.
94666**
94667** The following system tables are or have been supported:
94668**
94669**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
94670**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
94671**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
94672**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
94673**
94674** Additional tables might be added in future releases of SQLite.
94675** The sqlite_stat2 table is not created or used unless the SQLite version
94676** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
94677** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
94678** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
94679** created and used by SQLite versions 3.7.9 and later and with
94680** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
94681** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
94682** version of sqlite_stat3 and is only available when compiled with
94683** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
94684** not possible to enable both STAT3 and STAT4 at the same time.  If they
94685** are both enabled, then STAT4 takes precedence.
94686**
94687** For most applications, sqlite_stat1 provides all the statistics required
94688** for the query planner to make good choices.
94689**
94690** Format of sqlite_stat1:
94691**
94692** There is normally one row per index, with the index identified by the
94693** name in the idx column.  The tbl column is the name of the table to
94694** which the index belongs.  In each such row, the stat column will be
94695** a string consisting of a list of integers.  The first integer in this
94696** list is the number of rows in the index.  (This is the same as the
94697** number of rows in the table, except for partial indices.)  The second
94698** integer is the average number of rows in the index that have the same
94699** value in the first column of the index.  The third integer is the average
94700** number of rows in the index that have the same value for the first two
94701** columns.  The N-th integer (for N>1) is the average number of rows in
94702** the index which have the same value for the first N-1 columns.  For
94703** a K-column index, there will be K+1 integers in the stat column.  If
94704** the index is unique, then the last integer will be 1.
94705**
94706** The list of integers in the stat column can optionally be followed
94707** by the keyword "unordered".  The "unordered" keyword, if it is present,
94708** must be separated from the last integer by a single space.  If the
94709** "unordered" keyword is present, then the query planner assumes that
94710** the index is unordered and will not use the index for a range query.
94711**
94712** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
94713** column contains a single integer which is the (estimated) number of
94714** rows in the table identified by sqlite_stat1.tbl.
94715**
94716** Format of sqlite_stat2:
94717**
94718** The sqlite_stat2 is only created and is only used if SQLite is compiled
94719** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
94720** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
94721** about the distribution of keys within an index.  The index is identified by
94722** the "idx" column and the "tbl" column is the name of the table to which
94723** the index belongs.  There are usually 10 rows in the sqlite_stat2
94724** table for each index.
94725**
94726** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
94727** inclusive are samples of the left-most key value in the index taken at
94728** evenly spaced points along the index.  Let the number of samples be S
94729** (10 in the standard build) and let C be the number of rows in the index.
94730** Then the sampled rows are given by:
94731**
94732**     rownumber = (i*C*2 + C)/(S*2)
94733**
94734** For i between 0 and S-1.  Conceptually, the index space is divided into
94735** S uniform buckets and the samples are the middle row from each bucket.
94736**
94737** The format for sqlite_stat2 is recorded here for legacy reference.  This
94738** version of SQLite does not support sqlite_stat2.  It neither reads nor
94739** writes the sqlite_stat2 table.  This version of SQLite only supports
94740** sqlite_stat3.
94741**
94742** Format for sqlite_stat3:
94743**
94744** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
94745** sqlite_stat4 format will be described first.  Further information
94746** about sqlite_stat3 follows the sqlite_stat4 description.
94747**
94748** Format for sqlite_stat4:
94749**
94750** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
94751** to aid the query planner in choosing good indices based on the values
94752** that indexed columns are compared against in the WHERE clauses of
94753** queries.
94754**
94755** The sqlite_stat4 table contains multiple entries for each index.
94756** The idx column names the index and the tbl column is the table of the
94757** index.  If the idx and tbl columns are the same, then the sample is
94758** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
94759** binary encoding of a key from the index.  The nEq column is a
94760** list of integers.  The first integer is the approximate number
94761** of entries in the index whose left-most column exactly matches
94762** the left-most column of the sample.  The second integer in nEq
94763** is the approximate number of entries in the index where the
94764** first two columns match the first two columns of the sample.
94765** And so forth.  nLt is another list of integers that show the approximate
94766** number of entries that are strictly less than the sample.  The first
94767** integer in nLt contains the number of entries in the index where the
94768** left-most column is less than the left-most column of the sample.
94769** The K-th integer in the nLt entry is the number of index entries
94770** where the first K columns are less than the first K columns of the
94771** sample.  The nDLt column is like nLt except that it contains the
94772** number of distinct entries in the index that are less than the
94773** sample.
94774**
94775** There can be an arbitrary number of sqlite_stat4 entries per index.
94776** The ANALYZE command will typically generate sqlite_stat4 tables
94777** that contain between 10 and 40 samples which are distributed across
94778** the key space, though not uniformly, and which include samples with
94779** large nEq values.
94780**
94781** Format for sqlite_stat3 redux:
94782**
94783** The sqlite_stat3 table is like sqlite_stat4 except that it only
94784** looks at the left-most column of the index.  The sqlite_stat3.sample
94785** column contains the actual value of the left-most column instead
94786** of a blob encoding of the complete index key as is found in
94787** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
94788** all contain just a single integer which is the same as the first
94789** integer in the equivalent columns in sqlite_stat4.
94790*/
94791#ifndef SQLITE_OMIT_ANALYZE
94792/* #include "sqliteInt.h" */
94793
94794#if defined(SQLITE_ENABLE_STAT4)
94795# define IsStat4     1
94796# define IsStat3     0
94797#elif defined(SQLITE_ENABLE_STAT3)
94798# define IsStat4     0
94799# define IsStat3     1
94800#else
94801# define IsStat4     0
94802# define IsStat3     0
94803# undef SQLITE_STAT4_SAMPLES
94804# define SQLITE_STAT4_SAMPLES 1
94805#endif
94806#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
94807
94808/*
94809** This routine generates code that opens the sqlite_statN tables.
94810** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
94811** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
94812** appropriate compile-time options are provided.
94813**
94814** If the sqlite_statN tables do not previously exist, it is created.
94815**
94816** Argument zWhere may be a pointer to a buffer containing a table name,
94817** or it may be a NULL pointer. If it is not NULL, then all entries in
94818** the sqlite_statN tables associated with the named table are deleted.
94819** If zWhere==0, then code is generated to delete all stat table entries.
94820*/
94821static void openStatTable(
94822  Parse *pParse,          /* Parsing context */
94823  int iDb,                /* The database we are looking in */
94824  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
94825  const char *zWhere,     /* Delete entries for this table or index */
94826  const char *zWhereType  /* Either "tbl" or "idx" */
94827){
94828  static const struct {
94829    const char *zName;
94830    const char *zCols;
94831  } aTable[] = {
94832    { "sqlite_stat1", "tbl,idx,stat" },
94833#if defined(SQLITE_ENABLE_STAT4)
94834    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
94835    { "sqlite_stat3", 0 },
94836#elif defined(SQLITE_ENABLE_STAT3)
94837    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
94838    { "sqlite_stat4", 0 },
94839#else
94840    { "sqlite_stat3", 0 },
94841    { "sqlite_stat4", 0 },
94842#endif
94843  };
94844  int i;
94845  sqlite3 *db = pParse->db;
94846  Db *pDb;
94847  Vdbe *v = sqlite3GetVdbe(pParse);
94848  int aRoot[ArraySize(aTable)];
94849  u8 aCreateTbl[ArraySize(aTable)];
94850
94851  if( v==0 ) return;
94852  assert( sqlite3BtreeHoldsAllMutexes(db) );
94853  assert( sqlite3VdbeDb(v)==db );
94854  pDb = &db->aDb[iDb];
94855
94856  /* Create new statistic tables if they do not exist, or clear them
94857  ** if they do already exist.
94858  */
94859  for(i=0; i<ArraySize(aTable); i++){
94860    const char *zTab = aTable[i].zName;
94861    Table *pStat;
94862    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
94863      if( aTable[i].zCols ){
94864        /* The sqlite_statN table does not exist. Create it. Note that a
94865        ** side-effect of the CREATE TABLE statement is to leave the rootpage
94866        ** of the new table in register pParse->regRoot. This is important
94867        ** because the OpenWrite opcode below will be needing it. */
94868        sqlite3NestedParse(pParse,
94869            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
94870        );
94871        aRoot[i] = pParse->regRoot;
94872        aCreateTbl[i] = OPFLAG_P2ISREG;
94873      }
94874    }else{
94875      /* The table already exists. If zWhere is not NULL, delete all entries
94876      ** associated with the table zWhere. If zWhere is NULL, delete the
94877      ** entire contents of the table. */
94878      aRoot[i] = pStat->tnum;
94879      aCreateTbl[i] = 0;
94880      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
94881      if( zWhere ){
94882        sqlite3NestedParse(pParse,
94883           "DELETE FROM %Q.%s WHERE %s=%Q",
94884           pDb->zName, zTab, zWhereType, zWhere
94885        );
94886      }else{
94887        /* The sqlite_stat[134] table already exists.  Delete all rows. */
94888        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
94889      }
94890    }
94891  }
94892
94893  /* Open the sqlite_stat[134] tables for writing. */
94894  for(i=0; aTable[i].zCols; i++){
94895    assert( i<ArraySize(aTable) );
94896    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
94897    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
94898    VdbeComment((v, aTable[i].zName));
94899  }
94900}
94901
94902/*
94903** Recommended number of samples for sqlite_stat4
94904*/
94905#ifndef SQLITE_STAT4_SAMPLES
94906# define SQLITE_STAT4_SAMPLES 24
94907#endif
94908
94909/*
94910** Three SQL functions - stat_init(), stat_push(), and stat_get() -
94911** share an instance of the following structure to hold their state
94912** information.
94913*/
94914typedef struct Stat4Accum Stat4Accum;
94915typedef struct Stat4Sample Stat4Sample;
94916struct Stat4Sample {
94917  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
94918  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
94919#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94920  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
94921  union {
94922    i64 iRowid;                     /* Rowid in main table of the key */
94923    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
94924  } u;
94925  u32 nRowid;                     /* Sizeof aRowid[] */
94926  u8 isPSample;                   /* True if a periodic sample */
94927  int iCol;                       /* If !isPSample, the reason for inclusion */
94928  u32 iHash;                      /* Tiebreaker hash */
94929#endif
94930};
94931struct Stat4Accum {
94932  tRowcnt nRow;             /* Number of rows in the entire table */
94933  tRowcnt nPSample;         /* How often to do a periodic sample */
94934  int nCol;                 /* Number of columns in index + pk/rowid */
94935  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
94936  int mxSample;             /* Maximum number of samples to accumulate */
94937  Stat4Sample current;      /* Current row as a Stat4Sample */
94938  u32 iPrn;                 /* Pseudo-random number used for sampling */
94939  Stat4Sample *aBest;       /* Array of nCol best samples */
94940  int iMin;                 /* Index in a[] of entry with minimum score */
94941  int nSample;              /* Current number of samples */
94942  int iGet;                 /* Index of current sample accessed by stat_get() */
94943  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
94944  sqlite3 *db;              /* Database connection, for malloc() */
94945};
94946
94947/* Reclaim memory used by a Stat4Sample
94948*/
94949#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94950static void sampleClear(sqlite3 *db, Stat4Sample *p){
94951  assert( db!=0 );
94952  if( p->nRowid ){
94953    sqlite3DbFree(db, p->u.aRowid);
94954    p->nRowid = 0;
94955  }
94956}
94957#endif
94958
94959/* Initialize the BLOB value of a ROWID
94960*/
94961#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94962static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
94963  assert( db!=0 );
94964  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94965  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
94966  if( p->u.aRowid ){
94967    p->nRowid = n;
94968    memcpy(p->u.aRowid, pData, n);
94969  }else{
94970    p->nRowid = 0;
94971  }
94972}
94973#endif
94974
94975/* Initialize the INTEGER value of a ROWID.
94976*/
94977#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94978static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
94979  assert( db!=0 );
94980  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94981  p->nRowid = 0;
94982  p->u.iRowid = iRowid;
94983}
94984#endif
94985
94986
94987/*
94988** Copy the contents of object (*pFrom) into (*pTo).
94989*/
94990#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94991static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
94992  pTo->isPSample = pFrom->isPSample;
94993  pTo->iCol = pFrom->iCol;
94994  pTo->iHash = pFrom->iHash;
94995  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
94996  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
94997  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
94998  if( pFrom->nRowid ){
94999    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
95000  }else{
95001    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
95002  }
95003}
95004#endif
95005
95006/*
95007** Reclaim all memory of a Stat4Accum structure.
95008*/
95009static void stat4Destructor(void *pOld){
95010  Stat4Accum *p = (Stat4Accum*)pOld;
95011#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95012  int i;
95013  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
95014  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
95015  sampleClear(p->db, &p->current);
95016#endif
95017  sqlite3DbFree(p->db, p);
95018}
95019
95020/*
95021** Implementation of the stat_init(N,K,C) SQL function. The three parameters
95022** are:
95023**     N:    The number of columns in the index including the rowid/pk (note 1)
95024**     K:    The number of columns in the index excluding the rowid/pk.
95025**     C:    The number of rows in the index (note 2)
95026**
95027** Note 1:  In the special case of the covering index that implements a
95028** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
95029** total number of columns in the table.
95030**
95031** Note 2:  C is only used for STAT3 and STAT4.
95032**
95033** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
95034** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
95035** PRIMARY KEY of the table.  The covering index that implements the
95036** original WITHOUT ROWID table as N==K as a special case.
95037**
95038** This routine allocates the Stat4Accum object in heap memory. The return
95039** value is a pointer to the Stat4Accum object.  The datatype of the
95040** return value is BLOB, but it is really just a pointer to the Stat4Accum
95041** object.
95042*/
95043static void statInit(
95044  sqlite3_context *context,
95045  int argc,
95046  sqlite3_value **argv
95047){
95048  Stat4Accum *p;
95049  int nCol;                       /* Number of columns in index being sampled */
95050  int nKeyCol;                    /* Number of key columns */
95051  int nColUp;                     /* nCol rounded up for alignment */
95052  int n;                          /* Bytes of space to allocate */
95053  sqlite3 *db;                    /* Database connection */
95054#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95055  int mxSample = SQLITE_STAT4_SAMPLES;
95056#endif
95057
95058  /* Decode the three function arguments */
95059  UNUSED_PARAMETER(argc);
95060  nCol = sqlite3_value_int(argv[0]);
95061  assert( nCol>0 );
95062  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
95063  nKeyCol = sqlite3_value_int(argv[1]);
95064  assert( nKeyCol<=nCol );
95065  assert( nKeyCol>0 );
95066
95067  /* Allocate the space required for the Stat4Accum object */
95068  n = sizeof(*p)
95069    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
95070    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
95071#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95072    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
95073    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
95074    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
95075#endif
95076  ;
95077  db = sqlite3_context_db_handle(context);
95078  p = sqlite3DbMallocZero(db, n);
95079  if( p==0 ){
95080    sqlite3_result_error_nomem(context);
95081    return;
95082  }
95083
95084  p->db = db;
95085  p->nRow = 0;
95086  p->nCol = nCol;
95087  p->nKeyCol = nKeyCol;
95088  p->current.anDLt = (tRowcnt*)&p[1];
95089  p->current.anEq = &p->current.anDLt[nColUp];
95090
95091#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95092  {
95093    u8 *pSpace;                     /* Allocated space not yet assigned */
95094    int i;                          /* Used to iterate through p->aSample[] */
95095
95096    p->iGet = -1;
95097    p->mxSample = mxSample;
95098    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
95099    p->current.anLt = &p->current.anEq[nColUp];
95100    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
95101
95102    /* Set up the Stat4Accum.a[] and aBest[] arrays */
95103    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
95104    p->aBest = &p->a[mxSample];
95105    pSpace = (u8*)(&p->a[mxSample+nCol]);
95106    for(i=0; i<(mxSample+nCol); i++){
95107      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95108      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95109      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95110    }
95111    assert( (pSpace - (u8*)p)==n );
95112
95113    for(i=0; i<nCol; i++){
95114      p->aBest[i].iCol = i;
95115    }
95116  }
95117#endif
95118
95119  /* Return a pointer to the allocated object to the caller.  Note that
95120  ** only the pointer (the 2nd parameter) matters.  The size of the object
95121  ** (given by the 3rd parameter) is never used and can be any positive
95122  ** value. */
95123  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
95124}
95125static const FuncDef statInitFuncdef = {
95126  2+IsStat34,      /* nArg */
95127  SQLITE_UTF8,     /* funcFlags */
95128  0,               /* pUserData */
95129  0,               /* pNext */
95130  statInit,        /* xSFunc */
95131  0,               /* xFinalize */
95132  "stat_init",     /* zName */
95133  {0}
95134};
95135
95136#ifdef SQLITE_ENABLE_STAT4
95137/*
95138** pNew and pOld are both candidate non-periodic samples selected for
95139** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
95140** considering only any trailing columns and the sample hash value, this
95141** function returns true if sample pNew is to be preferred over pOld.
95142** In other words, if we assume that the cardinalities of the selected
95143** column for pNew and pOld are equal, is pNew to be preferred over pOld.
95144**
95145** This function assumes that for each argument sample, the contents of
95146** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
95147*/
95148static int sampleIsBetterPost(
95149  Stat4Accum *pAccum,
95150  Stat4Sample *pNew,
95151  Stat4Sample *pOld
95152){
95153  int nCol = pAccum->nCol;
95154  int i;
95155  assert( pNew->iCol==pOld->iCol );
95156  for(i=pNew->iCol+1; i<nCol; i++){
95157    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
95158    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
95159  }
95160  if( pNew->iHash>pOld->iHash ) return 1;
95161  return 0;
95162}
95163#endif
95164
95165#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95166/*
95167** Return true if pNew is to be preferred over pOld.
95168**
95169** This function assumes that for each argument sample, the contents of
95170** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
95171*/
95172static int sampleIsBetter(
95173  Stat4Accum *pAccum,
95174  Stat4Sample *pNew,
95175  Stat4Sample *pOld
95176){
95177  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
95178  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
95179
95180  assert( pOld->isPSample==0 && pNew->isPSample==0 );
95181  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
95182
95183  if( (nEqNew>nEqOld) ) return 1;
95184#ifdef SQLITE_ENABLE_STAT4
95185  if( nEqNew==nEqOld ){
95186    if( pNew->iCol<pOld->iCol ) return 1;
95187    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
95188  }
95189  return 0;
95190#else
95191  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
95192#endif
95193}
95194
95195/*
95196** Copy the contents of sample *pNew into the p->a[] array. If necessary,
95197** remove the least desirable sample from p->a[] to make room.
95198*/
95199static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
95200  Stat4Sample *pSample = 0;
95201  int i;
95202
95203  assert( IsStat4 || nEqZero==0 );
95204
95205#ifdef SQLITE_ENABLE_STAT4
95206  if( pNew->isPSample==0 ){
95207    Stat4Sample *pUpgrade = 0;
95208    assert( pNew->anEq[pNew->iCol]>0 );
95209
95210    /* This sample is being added because the prefix that ends in column
95211    ** iCol occurs many times in the table. However, if we have already
95212    ** added a sample that shares this prefix, there is no need to add
95213    ** this one. Instead, upgrade the priority of the highest priority
95214    ** existing sample that shares this prefix.  */
95215    for(i=p->nSample-1; i>=0; i--){
95216      Stat4Sample *pOld = &p->a[i];
95217      if( pOld->anEq[pNew->iCol]==0 ){
95218        if( pOld->isPSample ) return;
95219        assert( pOld->iCol>pNew->iCol );
95220        assert( sampleIsBetter(p, pNew, pOld) );
95221        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
95222          pUpgrade = pOld;
95223        }
95224      }
95225    }
95226    if( pUpgrade ){
95227      pUpgrade->iCol = pNew->iCol;
95228      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
95229      goto find_new_min;
95230    }
95231  }
95232#endif
95233
95234  /* If necessary, remove sample iMin to make room for the new sample. */
95235  if( p->nSample>=p->mxSample ){
95236    Stat4Sample *pMin = &p->a[p->iMin];
95237    tRowcnt *anEq = pMin->anEq;
95238    tRowcnt *anLt = pMin->anLt;
95239    tRowcnt *anDLt = pMin->anDLt;
95240    sampleClear(p->db, pMin);
95241    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
95242    pSample = &p->a[p->nSample-1];
95243    pSample->nRowid = 0;
95244    pSample->anEq = anEq;
95245    pSample->anDLt = anDLt;
95246    pSample->anLt = anLt;
95247    p->nSample = p->mxSample-1;
95248  }
95249
95250  /* The "rows less-than" for the rowid column must be greater than that
95251  ** for the last sample in the p->a[] array. Otherwise, the samples would
95252  ** be out of order. */
95253#ifdef SQLITE_ENABLE_STAT4
95254  assert( p->nSample==0
95255       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
95256#endif
95257
95258  /* Insert the new sample */
95259  pSample = &p->a[p->nSample];
95260  sampleCopy(p, pSample, pNew);
95261  p->nSample++;
95262
95263  /* Zero the first nEqZero entries in the anEq[] array. */
95264  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
95265
95266#ifdef SQLITE_ENABLE_STAT4
95267 find_new_min:
95268#endif
95269  if( p->nSample>=p->mxSample ){
95270    int iMin = -1;
95271    for(i=0; i<p->mxSample; i++){
95272      if( p->a[i].isPSample ) continue;
95273      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
95274        iMin = i;
95275      }
95276    }
95277    assert( iMin>=0 );
95278    p->iMin = iMin;
95279  }
95280}
95281#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95282
95283/*
95284** Field iChng of the index being scanned has changed. So at this point
95285** p->current contains a sample that reflects the previous row of the
95286** index. The value of anEq[iChng] and subsequent anEq[] elements are
95287** correct at this point.
95288*/
95289static void samplePushPrevious(Stat4Accum *p, int iChng){
95290#ifdef SQLITE_ENABLE_STAT4
95291  int i;
95292
95293  /* Check if any samples from the aBest[] array should be pushed
95294  ** into IndexSample.a[] at this point.  */
95295  for(i=(p->nCol-2); i>=iChng; i--){
95296    Stat4Sample *pBest = &p->aBest[i];
95297    pBest->anEq[i] = p->current.anEq[i];
95298    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
95299      sampleInsert(p, pBest, i);
95300    }
95301  }
95302
95303  /* Update the anEq[] fields of any samples already collected. */
95304  for(i=p->nSample-1; i>=0; i--){
95305    int j;
95306    for(j=iChng; j<p->nCol; j++){
95307      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
95308    }
95309  }
95310#endif
95311
95312#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
95313  if( iChng==0 ){
95314    tRowcnt nLt = p->current.anLt[0];
95315    tRowcnt nEq = p->current.anEq[0];
95316
95317    /* Check if this is to be a periodic sample. If so, add it. */
95318    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
95319      p->current.isPSample = 1;
95320      sampleInsert(p, &p->current, 0);
95321      p->current.isPSample = 0;
95322    }else
95323
95324    /* Or if it is a non-periodic sample. Add it in this case too. */
95325    if( p->nSample<p->mxSample
95326     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
95327    ){
95328      sampleInsert(p, &p->current, 0);
95329    }
95330  }
95331#endif
95332
95333#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
95334  UNUSED_PARAMETER( p );
95335  UNUSED_PARAMETER( iChng );
95336#endif
95337}
95338
95339/*
95340** Implementation of the stat_push SQL function:  stat_push(P,C,R)
95341** Arguments:
95342**
95343**    P     Pointer to the Stat4Accum object created by stat_init()
95344**    C     Index of left-most column to differ from previous row
95345**    R     Rowid for the current row.  Might be a key record for
95346**          WITHOUT ROWID tables.
95347**
95348** This SQL function always returns NULL.  It's purpose it to accumulate
95349** statistical data and/or samples in the Stat4Accum object about the
95350** index being analyzed.  The stat_get() SQL function will later be used to
95351** extract relevant information for constructing the sqlite_statN tables.
95352**
95353** The R parameter is only used for STAT3 and STAT4
95354*/
95355static void statPush(
95356  sqlite3_context *context,
95357  int argc,
95358  sqlite3_value **argv
95359){
95360  int i;
95361
95362  /* The three function arguments */
95363  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
95364  int iChng = sqlite3_value_int(argv[1]);
95365
95366  UNUSED_PARAMETER( argc );
95367  UNUSED_PARAMETER( context );
95368  assert( p->nCol>0 );
95369  assert( iChng<p->nCol );
95370
95371  if( p->nRow==0 ){
95372    /* This is the first call to this function. Do initialization. */
95373    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
95374  }else{
95375    /* Second and subsequent calls get processed here */
95376    samplePushPrevious(p, iChng);
95377
95378    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
95379    ** to the current row of the index. */
95380    for(i=0; i<iChng; i++){
95381      p->current.anEq[i]++;
95382    }
95383    for(i=iChng; i<p->nCol; i++){
95384      p->current.anDLt[i]++;
95385#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95386      p->current.anLt[i] += p->current.anEq[i];
95387#endif
95388      p->current.anEq[i] = 1;
95389    }
95390  }
95391  p->nRow++;
95392#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95393  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
95394    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
95395  }else{
95396    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
95397                                       sqlite3_value_blob(argv[2]));
95398  }
95399  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
95400#endif
95401
95402#ifdef SQLITE_ENABLE_STAT4
95403  {
95404    tRowcnt nLt = p->current.anLt[p->nCol-1];
95405
95406    /* Check if this is to be a periodic sample. If so, add it. */
95407    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
95408      p->current.isPSample = 1;
95409      p->current.iCol = 0;
95410      sampleInsert(p, &p->current, p->nCol-1);
95411      p->current.isPSample = 0;
95412    }
95413
95414    /* Update the aBest[] array. */
95415    for(i=0; i<(p->nCol-1); i++){
95416      p->current.iCol = i;
95417      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
95418        sampleCopy(p, &p->aBest[i], &p->current);
95419      }
95420    }
95421  }
95422#endif
95423}
95424static const FuncDef statPushFuncdef = {
95425  2+IsStat34,      /* nArg */
95426  SQLITE_UTF8,     /* funcFlags */
95427  0,               /* pUserData */
95428  0,               /* pNext */
95429  statPush,        /* xSFunc */
95430  0,               /* xFinalize */
95431  "stat_push",     /* zName */
95432  {0}
95433};
95434
95435#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
95436#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
95437#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
95438#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
95439#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
95440
95441/*
95442** Implementation of the stat_get(P,J) SQL function.  This routine is
95443** used to query statistical information that has been gathered into
95444** the Stat4Accum object by prior calls to stat_push().  The P parameter
95445** has type BLOB but it is really just a pointer to the Stat4Accum object.
95446** The content to returned is determined by the parameter J
95447** which is one of the STAT_GET_xxxx values defined above.
95448**
95449** If neither STAT3 nor STAT4 are enabled, then J is always
95450** STAT_GET_STAT1 and is hence omitted and this routine becomes
95451** a one-parameter function, stat_get(P), that always returns the
95452** stat1 table entry information.
95453*/
95454static void statGet(
95455  sqlite3_context *context,
95456  int argc,
95457  sqlite3_value **argv
95458){
95459  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
95460#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95461  /* STAT3 and STAT4 have a parameter on this routine. */
95462  int eCall = sqlite3_value_int(argv[1]);
95463  assert( argc==2 );
95464  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
95465       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
95466       || eCall==STAT_GET_NDLT
95467  );
95468  if( eCall==STAT_GET_STAT1 )
95469#else
95470  assert( argc==1 );
95471#endif
95472  {
95473    /* Return the value to store in the "stat" column of the sqlite_stat1
95474    ** table for this index.
95475    **
95476    ** The value is a string composed of a list of integers describing
95477    ** the index. The first integer in the list is the total number of
95478    ** entries in the index. There is one additional integer in the list
95479    ** for each indexed column. This additional integer is an estimate of
95480    ** the number of rows matched by a stabbing query on the index using
95481    ** a key with the corresponding number of fields. In other words,
95482    ** if the index is on columns (a,b) and the sqlite_stat1 value is
95483    ** "100 10 2", then SQLite estimates that:
95484    **
95485    **   * the index contains 100 rows,
95486    **   * "WHERE a=?" matches 10 rows, and
95487    **   * "WHERE a=? AND b=?" matches 2 rows.
95488    **
95489    ** If D is the count of distinct values and K is the total number of
95490    ** rows, then each estimate is computed as:
95491    **
95492    **        I = (K+D-1)/D
95493    */
95494    char *z;
95495    int i;
95496
95497    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
95498    if( zRet==0 ){
95499      sqlite3_result_error_nomem(context);
95500      return;
95501    }
95502
95503    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
95504    z = zRet + sqlite3Strlen30(zRet);
95505    for(i=0; i<p->nKeyCol; i++){
95506      u64 nDistinct = p->current.anDLt[i] + 1;
95507      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
95508      sqlite3_snprintf(24, z, " %llu", iVal);
95509      z += sqlite3Strlen30(z);
95510      assert( p->current.anEq[i] );
95511    }
95512    assert( z[0]=='\0' && z>zRet );
95513
95514    sqlite3_result_text(context, zRet, -1, sqlite3_free);
95515  }
95516#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95517  else if( eCall==STAT_GET_ROWID ){
95518    if( p->iGet<0 ){
95519      samplePushPrevious(p, 0);
95520      p->iGet = 0;
95521    }
95522    if( p->iGet<p->nSample ){
95523      Stat4Sample *pS = p->a + p->iGet;
95524      if( pS->nRowid==0 ){
95525        sqlite3_result_int64(context, pS->u.iRowid);
95526      }else{
95527        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
95528                            SQLITE_TRANSIENT);
95529      }
95530    }
95531  }else{
95532    tRowcnt *aCnt = 0;
95533
95534    assert( p->iGet<p->nSample );
95535    switch( eCall ){
95536      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
95537      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
95538      default: {
95539        aCnt = p->a[p->iGet].anDLt;
95540        p->iGet++;
95541        break;
95542      }
95543    }
95544
95545    if( IsStat3 ){
95546      sqlite3_result_int64(context, (i64)aCnt[0]);
95547    }else{
95548      char *zRet = sqlite3MallocZero(p->nCol * 25);
95549      if( zRet==0 ){
95550        sqlite3_result_error_nomem(context);
95551      }else{
95552        int i;
95553        char *z = zRet;
95554        for(i=0; i<p->nCol; i++){
95555          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
95556          z += sqlite3Strlen30(z);
95557        }
95558        assert( z[0]=='\0' && z>zRet );
95559        z[-1] = '\0';
95560        sqlite3_result_text(context, zRet, -1, sqlite3_free);
95561      }
95562    }
95563  }
95564#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95565#ifndef SQLITE_DEBUG
95566  UNUSED_PARAMETER( argc );
95567#endif
95568}
95569static const FuncDef statGetFuncdef = {
95570  1+IsStat34,      /* nArg */
95571  SQLITE_UTF8,     /* funcFlags */
95572  0,               /* pUserData */
95573  0,               /* pNext */
95574  statGet,         /* xSFunc */
95575  0,               /* xFinalize */
95576  "stat_get",      /* zName */
95577  {0}
95578};
95579
95580static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
95581  assert( regOut!=regStat4 && regOut!=regStat4+1 );
95582#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95583  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
95584#elif SQLITE_DEBUG
95585  assert( iParam==STAT_GET_STAT1 );
95586#else
95587  UNUSED_PARAMETER( iParam );
95588#endif
95589  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
95590                    (char*)&statGetFuncdef, P4_FUNCDEF);
95591  sqlite3VdbeChangeP5(v, 1 + IsStat34);
95592}
95593
95594/*
95595** Generate code to do an analysis of all indices associated with
95596** a single table.
95597*/
95598static void analyzeOneTable(
95599  Parse *pParse,   /* Parser context */
95600  Table *pTab,     /* Table whose indices are to be analyzed */
95601  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
95602  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
95603  int iMem,        /* Available memory locations begin here */
95604  int iTab         /* Next available cursor */
95605){
95606  sqlite3 *db = pParse->db;    /* Database handle */
95607  Index *pIdx;                 /* An index to being analyzed */
95608  int iIdxCur;                 /* Cursor open on index being analyzed */
95609  int iTabCur;                 /* Table cursor */
95610  Vdbe *v;                     /* The virtual machine being built up */
95611  int i;                       /* Loop counter */
95612  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
95613  int iDb;                     /* Index of database containing pTab */
95614  u8 needTableCnt = 1;         /* True to count the table */
95615  int regNewRowid = iMem++;    /* Rowid for the inserted record */
95616  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
95617  int regChng = iMem++;        /* Index of changed index field */
95618#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95619  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
95620#endif
95621  int regTemp = iMem++;        /* Temporary use register */
95622  int regTabname = iMem++;     /* Register containing table name */
95623  int regIdxname = iMem++;     /* Register containing index name */
95624  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
95625  int regPrev = iMem;          /* MUST BE LAST (see below) */
95626
95627  pParse->nMem = MAX(pParse->nMem, iMem);
95628  v = sqlite3GetVdbe(pParse);
95629  if( v==0 || NEVER(pTab==0) ){
95630    return;
95631  }
95632  if( pTab->tnum==0 ){
95633    /* Do not gather statistics on views or virtual tables */
95634    return;
95635  }
95636  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
95637    /* Do not gather statistics on system tables */
95638    return;
95639  }
95640  assert( sqlite3BtreeHoldsAllMutexes(db) );
95641  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95642  assert( iDb>=0 );
95643  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95644#ifndef SQLITE_OMIT_AUTHORIZATION
95645  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
95646      db->aDb[iDb].zName ) ){
95647    return;
95648  }
95649#endif
95650
95651  /* Establish a read-lock on the table at the shared-cache level.
95652  ** Open a read-only cursor on the table. Also allocate a cursor number
95653  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
95654  ** this time though.  */
95655  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
95656  iTabCur = iTab++;
95657  iIdxCur = iTab++;
95658  pParse->nTab = MAX(pParse->nTab, iTab);
95659  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
95660  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
95661
95662  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95663    int nCol;                     /* Number of columns in pIdx. "N" */
95664    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
95665    int addrNextRow;              /* Address of "next_row:" */
95666    const char *zIdxName;         /* Name of the index */
95667    int nColTest;                 /* Number of columns to test for changes */
95668
95669    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
95670    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
95671    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
95672      nCol = pIdx->nKeyCol;
95673      zIdxName = pTab->zName;
95674      nColTest = nCol - 1;
95675    }else{
95676      nCol = pIdx->nColumn;
95677      zIdxName = pIdx->zName;
95678      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
95679    }
95680
95681    /* Populate the register containing the index name. */
95682    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
95683    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
95684
95685    /*
95686    ** Pseudo-code for loop that calls stat_push():
95687    **
95688    **   Rewind csr
95689    **   if eof(csr) goto end_of_scan;
95690    **   regChng = 0
95691    **   goto chng_addr_0;
95692    **
95693    **  next_row:
95694    **   regChng = 0
95695    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
95696    **   regChng = 1
95697    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
95698    **   ...
95699    **   regChng = N
95700    **   goto chng_addr_N
95701    **
95702    **  chng_addr_0:
95703    **   regPrev(0) = idx(0)
95704    **  chng_addr_1:
95705    **   regPrev(1) = idx(1)
95706    **  ...
95707    **
95708    **  endDistinctTest:
95709    **   regRowid = idx(rowid)
95710    **   stat_push(P, regChng, regRowid)
95711    **   Next csr
95712    **   if !eof(csr) goto next_row;
95713    **
95714    **  end_of_scan:
95715    */
95716
95717    /* Make sure there are enough memory cells allocated to accommodate
95718    ** the regPrev array and a trailing rowid (the rowid slot is required
95719    ** when building a record to insert into the sample column of
95720    ** the sqlite_stat4 table.  */
95721    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
95722
95723    /* Open a read-only cursor on the index being analyzed. */
95724    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
95725    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
95726    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
95727    VdbeComment((v, "%s", pIdx->zName));
95728
95729    /* Invoke the stat_init() function. The arguments are:
95730    **
95731    **    (1) the number of columns in the index including the rowid
95732    **        (or for a WITHOUT ROWID table, the number of PK columns),
95733    **    (2) the number of columns in the key without the rowid/pk
95734    **    (3) the number of rows in the index,
95735    **
95736    **
95737    ** The third argument is only used for STAT3 and STAT4
95738    */
95739#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95740    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
95741#endif
95742    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
95743    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
95744    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
95745                     (char*)&statInitFuncdef, P4_FUNCDEF);
95746    sqlite3VdbeChangeP5(v, 2+IsStat34);
95747
95748    /* Implementation of the following:
95749    **
95750    **   Rewind csr
95751    **   if eof(csr) goto end_of_scan;
95752    **   regChng = 0
95753    **   goto next_push_0;
95754    **
95755    */
95756    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
95757    VdbeCoverage(v);
95758    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
95759    addrNextRow = sqlite3VdbeCurrentAddr(v);
95760
95761    if( nColTest>0 ){
95762      int endDistinctTest = sqlite3VdbeMakeLabel(v);
95763      int *aGotoChng;               /* Array of jump instruction addresses */
95764      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
95765      if( aGotoChng==0 ) continue;
95766
95767      /*
95768      **  next_row:
95769      **   regChng = 0
95770      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
95771      **   regChng = 1
95772      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
95773      **   ...
95774      **   regChng = N
95775      **   goto endDistinctTest
95776      */
95777      sqlite3VdbeAddOp0(v, OP_Goto);
95778      addrNextRow = sqlite3VdbeCurrentAddr(v);
95779      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
95780        /* For a single-column UNIQUE index, once we have found a non-NULL
95781        ** row, we know that all the rest will be distinct, so skip
95782        ** subsequent distinctness tests. */
95783        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
95784        VdbeCoverage(v);
95785      }
95786      for(i=0; i<nColTest; i++){
95787        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
95788        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
95789        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
95790        aGotoChng[i] =
95791        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
95792        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
95793        VdbeCoverage(v);
95794      }
95795      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
95796      sqlite3VdbeGoto(v, endDistinctTest);
95797
95798
95799      /*
95800      **  chng_addr_0:
95801      **   regPrev(0) = idx(0)
95802      **  chng_addr_1:
95803      **   regPrev(1) = idx(1)
95804      **  ...
95805      */
95806      sqlite3VdbeJumpHere(v, addrNextRow-1);
95807      for(i=0; i<nColTest; i++){
95808        sqlite3VdbeJumpHere(v, aGotoChng[i]);
95809        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
95810      }
95811      sqlite3VdbeResolveLabel(v, endDistinctTest);
95812      sqlite3DbFree(db, aGotoChng);
95813    }
95814
95815    /*
95816    **  chng_addr_N:
95817    **   regRowid = idx(rowid)            // STAT34 only
95818    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
95819    **   Next csr
95820    **   if !eof(csr) goto next_row;
95821    */
95822#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95823    assert( regRowid==(regStat4+2) );
95824    if( HasRowid(pTab) ){
95825      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
95826    }else{
95827      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
95828      int j, k, regKey;
95829      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
95830      for(j=0; j<pPk->nKeyCol; j++){
95831        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
95832        assert( k>=0 && k<pTab->nCol );
95833        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
95834        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
95835      }
95836      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
95837      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
95838    }
95839#endif
95840    assert( regChng==(regStat4+1) );
95841    sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
95842                     (char*)&statPushFuncdef, P4_FUNCDEF);
95843    sqlite3VdbeChangeP5(v, 2+IsStat34);
95844    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
95845
95846    /* Add the entry to the stat1 table. */
95847    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
95848    assert( "BBB"[0]==SQLITE_AFF_TEXT );
95849    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95850    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95851    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95852    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95853
95854    /* Add the entries to the stat3 or stat4 table. */
95855#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95856    {
95857      int regEq = regStat1;
95858      int regLt = regStat1+1;
95859      int regDLt = regStat1+2;
95860      int regSample = regStat1+3;
95861      int regCol = regStat1+4;
95862      int regSampleRowid = regCol + nCol;
95863      int addrNext;
95864      int addrIsNull;
95865      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
95866
95867      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
95868
95869      addrNext = sqlite3VdbeCurrentAddr(v);
95870      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
95871      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
95872      VdbeCoverage(v);
95873      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
95874      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
95875      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
95876      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
95877      /* We know that the regSampleRowid row exists because it was read by
95878      ** the previous loop.  Thus the not-found jump of seekOp will never
95879      ** be taken */
95880      VdbeCoverageNeverTaken(v);
95881#ifdef SQLITE_ENABLE_STAT3
95882      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
95883#else
95884      for(i=0; i<nCol; i++){
95885        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
95886      }
95887      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
95888#endif
95889      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
95890      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
95891      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
95892      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
95893      sqlite3VdbeJumpHere(v, addrIsNull);
95894    }
95895#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95896
95897    /* End of analysis */
95898    sqlite3VdbeJumpHere(v, addrRewind);
95899  }
95900
95901
95902  /* Create a single sqlite_stat1 entry containing NULL as the index
95903  ** name and the row count as the content.
95904  */
95905  if( pOnlyIdx==0 && needTableCnt ){
95906    VdbeComment((v, "%s", pTab->zName));
95907    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
95908    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
95909    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
95910    assert( "BBB"[0]==SQLITE_AFF_TEXT );
95911    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95912    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95913    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95914    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95915    sqlite3VdbeJumpHere(v, jZeroRows);
95916  }
95917}
95918
95919
95920/*
95921** Generate code that will cause the most recent index analysis to
95922** be loaded into internal hash tables where is can be used.
95923*/
95924static void loadAnalysis(Parse *pParse, int iDb){
95925  Vdbe *v = sqlite3GetVdbe(pParse);
95926  if( v ){
95927    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
95928  }
95929}
95930
95931/*
95932** Generate code that will do an analysis of an entire database
95933*/
95934static void analyzeDatabase(Parse *pParse, int iDb){
95935  sqlite3 *db = pParse->db;
95936  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
95937  HashElem *k;
95938  int iStatCur;
95939  int iMem;
95940  int iTab;
95941
95942  sqlite3BeginWriteOperation(pParse, 0, iDb);
95943  iStatCur = pParse->nTab;
95944  pParse->nTab += 3;
95945  openStatTable(pParse, iDb, iStatCur, 0, 0);
95946  iMem = pParse->nMem+1;
95947  iTab = pParse->nTab;
95948  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95949  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
95950    Table *pTab = (Table*)sqliteHashData(k);
95951    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
95952  }
95953  loadAnalysis(pParse, iDb);
95954}
95955
95956/*
95957** Generate code that will do an analysis of a single table in
95958** a database.  If pOnlyIdx is not NULL then it is a single index
95959** in pTab that should be analyzed.
95960*/
95961static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
95962  int iDb;
95963  int iStatCur;
95964
95965  assert( pTab!=0 );
95966  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95967  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95968  sqlite3BeginWriteOperation(pParse, 0, iDb);
95969  iStatCur = pParse->nTab;
95970  pParse->nTab += 3;
95971  if( pOnlyIdx ){
95972    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
95973  }else{
95974    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
95975  }
95976  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
95977  loadAnalysis(pParse, iDb);
95978}
95979
95980/*
95981** Generate code for the ANALYZE command.  The parser calls this routine
95982** when it recognizes an ANALYZE command.
95983**
95984**        ANALYZE                            -- 1
95985**        ANALYZE  <database>                -- 2
95986**        ANALYZE  ?<database>.?<tablename>  -- 3
95987**
95988** Form 1 causes all indices in all attached databases to be analyzed.
95989** Form 2 analyzes all indices the single database named.
95990** Form 3 analyzes all indices associated with the named table.
95991*/
95992SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
95993  sqlite3 *db = pParse->db;
95994  int iDb;
95995  int i;
95996  char *z, *zDb;
95997  Table *pTab;
95998  Index *pIdx;
95999  Token *pTableName;
96000  Vdbe *v;
96001
96002  /* Read the database schema. If an error occurs, leave an error message
96003  ** and code in pParse and return NULL. */
96004  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96005  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
96006    return;
96007  }
96008
96009  assert( pName2!=0 || pName1==0 );
96010  if( pName1==0 ){
96011    /* Form 1:  Analyze everything */
96012    for(i=0; i<db->nDb; i++){
96013      if( i==1 ) continue;  /* Do not analyze the TEMP database */
96014      analyzeDatabase(pParse, i);
96015    }
96016  }else if( pName2->n==0 ){
96017    /* Form 2:  Analyze the database or table named */
96018    iDb = sqlite3FindDb(db, pName1);
96019    if( iDb>=0 ){
96020      analyzeDatabase(pParse, iDb);
96021    }else{
96022      z = sqlite3NameFromToken(db, pName1);
96023      if( z ){
96024        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
96025          analyzeTable(pParse, pIdx->pTable, pIdx);
96026        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
96027          analyzeTable(pParse, pTab, 0);
96028        }
96029        sqlite3DbFree(db, z);
96030      }
96031    }
96032  }else{
96033    /* Form 3: Analyze the fully qualified table name */
96034    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
96035    if( iDb>=0 ){
96036      zDb = db->aDb[iDb].zName;
96037      z = sqlite3NameFromToken(db, pTableName);
96038      if( z ){
96039        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
96040          analyzeTable(pParse, pIdx->pTable, pIdx);
96041        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
96042          analyzeTable(pParse, pTab, 0);
96043        }
96044        sqlite3DbFree(db, z);
96045      }
96046    }
96047  }
96048  v = sqlite3GetVdbe(pParse);
96049  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
96050}
96051
96052/*
96053** Used to pass information from the analyzer reader through to the
96054** callback routine.
96055*/
96056typedef struct analysisInfo analysisInfo;
96057struct analysisInfo {
96058  sqlite3 *db;
96059  const char *zDatabase;
96060};
96061
96062/*
96063** The first argument points to a nul-terminated string containing a
96064** list of space separated integers. Read the first nOut of these into
96065** the array aOut[].
96066*/
96067static void decodeIntArray(
96068  char *zIntArray,       /* String containing int array to decode */
96069  int nOut,              /* Number of slots in aOut[] */
96070  tRowcnt *aOut,         /* Store integers here */
96071  LogEst *aLog,          /* Or, if aOut==0, here */
96072  Index *pIndex          /* Handle extra flags for this index, if not NULL */
96073){
96074  char *z = zIntArray;
96075  int c;
96076  int i;
96077  tRowcnt v;
96078
96079#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96080  if( z==0 ) z = "";
96081#else
96082  assert( z!=0 );
96083#endif
96084  for(i=0; *z && i<nOut; i++){
96085    v = 0;
96086    while( (c=z[0])>='0' && c<='9' ){
96087      v = v*10 + c - '0';
96088      z++;
96089    }
96090#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96091    if( aOut ) aOut[i] = v;
96092    if( aLog ) aLog[i] = sqlite3LogEst(v);
96093#else
96094    assert( aOut==0 );
96095    UNUSED_PARAMETER(aOut);
96096    assert( aLog!=0 );
96097    aLog[i] = sqlite3LogEst(v);
96098#endif
96099    if( *z==' ' ) z++;
96100  }
96101#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
96102  assert( pIndex!=0 ); {
96103#else
96104  if( pIndex ){
96105#endif
96106    pIndex->bUnordered = 0;
96107    pIndex->noSkipScan = 0;
96108    while( z[0] ){
96109      if( sqlite3_strglob("unordered*", z)==0 ){
96110        pIndex->bUnordered = 1;
96111      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
96112        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
96113      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
96114        pIndex->noSkipScan = 1;
96115      }
96116#ifdef SQLITE_ENABLE_COSTMULT
96117      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
96118        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
96119      }
96120#endif
96121      while( z[0]!=0 && z[0]!=' ' ) z++;
96122      while( z[0]==' ' ) z++;
96123    }
96124  }
96125}
96126
96127/*
96128** This callback is invoked once for each index when reading the
96129** sqlite_stat1 table.
96130**
96131**     argv[0] = name of the table
96132**     argv[1] = name of the index (might be NULL)
96133**     argv[2] = results of analysis - on integer for each column
96134**
96135** Entries for which argv[1]==NULL simply record the number of rows in
96136** the table.
96137*/
96138static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
96139  analysisInfo *pInfo = (analysisInfo*)pData;
96140  Index *pIndex;
96141  Table *pTable;
96142  const char *z;
96143
96144  assert( argc==3 );
96145  UNUSED_PARAMETER2(NotUsed, argc);
96146
96147  if( argv==0 || argv[0]==0 || argv[2]==0 ){
96148    return 0;
96149  }
96150  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
96151  if( pTable==0 ){
96152    return 0;
96153  }
96154  if( argv[1]==0 ){
96155    pIndex = 0;
96156  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
96157    pIndex = sqlite3PrimaryKeyIndex(pTable);
96158  }else{
96159    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
96160  }
96161  z = argv[2];
96162
96163  if( pIndex ){
96164    tRowcnt *aiRowEst = 0;
96165    int nCol = pIndex->nKeyCol+1;
96166#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96167    /* Index.aiRowEst may already be set here if there are duplicate
96168    ** sqlite_stat1 entries for this index. In that case just clobber
96169    ** the old data with the new instead of allocating a new array.  */
96170    if( pIndex->aiRowEst==0 ){
96171      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
96172      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
96173    }
96174    aiRowEst = pIndex->aiRowEst;
96175#endif
96176    pIndex->bUnordered = 0;
96177    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
96178    if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
96179  }else{
96180    Index fakeIdx;
96181    fakeIdx.szIdxRow = pTable->szTabRow;
96182#ifdef SQLITE_ENABLE_COSTMULT
96183    fakeIdx.pTable = pTable;
96184#endif
96185    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
96186    pTable->szTabRow = fakeIdx.szIdxRow;
96187  }
96188
96189  return 0;
96190}
96191
96192/*
96193** If the Index.aSample variable is not NULL, delete the aSample[] array
96194** and its contents.
96195*/
96196SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
96197#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96198  if( pIdx->aSample ){
96199    int j;
96200    for(j=0; j<pIdx->nSample; j++){
96201      IndexSample *p = &pIdx->aSample[j];
96202      sqlite3DbFree(db, p->p);
96203    }
96204    sqlite3DbFree(db, pIdx->aSample);
96205  }
96206  if( db && db->pnBytesFreed==0 ){
96207    pIdx->nSample = 0;
96208    pIdx->aSample = 0;
96209  }
96210#else
96211  UNUSED_PARAMETER(db);
96212  UNUSED_PARAMETER(pIdx);
96213#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96214}
96215
96216#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96217/*
96218** Populate the pIdx->aAvgEq[] array based on the samples currently
96219** stored in pIdx->aSample[].
96220*/
96221static void initAvgEq(Index *pIdx){
96222  if( pIdx ){
96223    IndexSample *aSample = pIdx->aSample;
96224    IndexSample *pFinal = &aSample[pIdx->nSample-1];
96225    int iCol;
96226    int nCol = 1;
96227    if( pIdx->nSampleCol>1 ){
96228      /* If this is stat4 data, then calculate aAvgEq[] values for all
96229      ** sample columns except the last. The last is always set to 1, as
96230      ** once the trailing PK fields are considered all index keys are
96231      ** unique.  */
96232      nCol = pIdx->nSampleCol-1;
96233      pIdx->aAvgEq[nCol] = 1;
96234    }
96235    for(iCol=0; iCol<nCol; iCol++){
96236      int nSample = pIdx->nSample;
96237      int i;                    /* Used to iterate through samples */
96238      tRowcnt sumEq = 0;        /* Sum of the nEq values */
96239      tRowcnt avgEq = 0;
96240      tRowcnt nRow;             /* Number of rows in index */
96241      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
96242      i64 nDist100;             /* Number of distinct values in index */
96243
96244      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
96245        nRow = pFinal->anLt[iCol];
96246        nDist100 = (i64)100 * pFinal->anDLt[iCol];
96247        nSample--;
96248      }else{
96249        nRow = pIdx->aiRowEst[0];
96250        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
96251      }
96252      pIdx->nRowEst0 = nRow;
96253
96254      /* Set nSum to the number of distinct (iCol+1) field prefixes that
96255      ** occur in the stat4 table for this index. Set sumEq to the sum of
96256      ** the nEq values for column iCol for the same set (adding the value
96257      ** only once where there exist duplicate prefixes).  */
96258      for(i=0; i<nSample; i++){
96259        if( i==(pIdx->nSample-1)
96260         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
96261        ){
96262          sumEq += aSample[i].anEq[iCol];
96263          nSum100 += 100;
96264        }
96265      }
96266
96267      if( nDist100>nSum100 ){
96268        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
96269      }
96270      if( avgEq==0 ) avgEq = 1;
96271      pIdx->aAvgEq[iCol] = avgEq;
96272    }
96273  }
96274}
96275
96276/*
96277** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
96278** is supplied instead, find the PRIMARY KEY index for that table.
96279*/
96280static Index *findIndexOrPrimaryKey(
96281  sqlite3 *db,
96282  const char *zName,
96283  const char *zDb
96284){
96285  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
96286  if( pIdx==0 ){
96287    Table *pTab = sqlite3FindTable(db, zName, zDb);
96288    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
96289  }
96290  return pIdx;
96291}
96292
96293/*
96294** Load the content from either the sqlite_stat4 or sqlite_stat3 table
96295** into the relevant Index.aSample[] arrays.
96296**
96297** Arguments zSql1 and zSql2 must point to SQL statements that return
96298** data equivalent to the following (statements are different for stat3,
96299** see the caller of this function for details):
96300**
96301**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
96302**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
96303**
96304** where %Q is replaced with the database name before the SQL is executed.
96305*/
96306static int loadStatTbl(
96307  sqlite3 *db,                  /* Database handle */
96308  int bStat3,                   /* Assume single column records only */
96309  const char *zSql1,            /* SQL statement 1 (see above) */
96310  const char *zSql2,            /* SQL statement 2 (see above) */
96311  const char *zDb               /* Database name (e.g. "main") */
96312){
96313  int rc;                       /* Result codes from subroutines */
96314  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
96315  char *zSql;                   /* Text of the SQL statement */
96316  Index *pPrevIdx = 0;          /* Previous index in the loop */
96317  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
96318
96319  assert( db->lookaside.bDisable );
96320  zSql = sqlite3MPrintf(db, zSql1, zDb);
96321  if( !zSql ){
96322    return SQLITE_NOMEM_BKPT;
96323  }
96324  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96325  sqlite3DbFree(db, zSql);
96326  if( rc ) return rc;
96327
96328  while( sqlite3_step(pStmt)==SQLITE_ROW ){
96329    int nIdxCol = 1;              /* Number of columns in stat4 records */
96330
96331    char *zIndex;   /* Index name */
96332    Index *pIdx;    /* Pointer to the index object */
96333    int nSample;    /* Number of samples */
96334    int nByte;      /* Bytes of space required */
96335    int i;          /* Bytes of space required */
96336    tRowcnt *pSpace;
96337
96338    zIndex = (char *)sqlite3_column_text(pStmt, 0);
96339    if( zIndex==0 ) continue;
96340    nSample = sqlite3_column_int(pStmt, 1);
96341    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
96342    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
96343    /* Index.nSample is non-zero at this point if data has already been
96344    ** loaded from the stat4 table. In this case ignore stat3 data.  */
96345    if( pIdx==0 || pIdx->nSample ) continue;
96346    if( bStat3==0 ){
96347      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
96348      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
96349        nIdxCol = pIdx->nKeyCol;
96350      }else{
96351        nIdxCol = pIdx->nColumn;
96352      }
96353    }
96354    pIdx->nSampleCol = nIdxCol;
96355    nByte = sizeof(IndexSample) * nSample;
96356    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
96357    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
96358
96359    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
96360    if( pIdx->aSample==0 ){
96361      sqlite3_finalize(pStmt);
96362      return SQLITE_NOMEM_BKPT;
96363    }
96364    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
96365    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
96366    for(i=0; i<nSample; i++){
96367      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
96368      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
96369      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
96370    }
96371    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
96372  }
96373  rc = sqlite3_finalize(pStmt);
96374  if( rc ) return rc;
96375
96376  zSql = sqlite3MPrintf(db, zSql2, zDb);
96377  if( !zSql ){
96378    return SQLITE_NOMEM_BKPT;
96379  }
96380  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96381  sqlite3DbFree(db, zSql);
96382  if( rc ) return rc;
96383
96384  while( sqlite3_step(pStmt)==SQLITE_ROW ){
96385    char *zIndex;                 /* Index name */
96386    Index *pIdx;                  /* Pointer to the index object */
96387    int nCol = 1;                 /* Number of columns in index */
96388
96389    zIndex = (char *)sqlite3_column_text(pStmt, 0);
96390    if( zIndex==0 ) continue;
96391    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
96392    if( pIdx==0 ) continue;
96393    /* This next condition is true if data has already been loaded from
96394    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
96395    nCol = pIdx->nSampleCol;
96396    if( bStat3 && nCol>1 ) continue;
96397    if( pIdx!=pPrevIdx ){
96398      initAvgEq(pPrevIdx);
96399      pPrevIdx = pIdx;
96400    }
96401    pSample = &pIdx->aSample[pIdx->nSample];
96402    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
96403    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
96404    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
96405
96406    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
96407    ** This is in case the sample record is corrupted. In that case, the
96408    ** sqlite3VdbeRecordCompare() may read up to two varints past the
96409    ** end of the allocated buffer before it realizes it is dealing with
96410    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
96411    ** a buffer overread.  */
96412    pSample->n = sqlite3_column_bytes(pStmt, 4);
96413    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
96414    if( pSample->p==0 ){
96415      sqlite3_finalize(pStmt);
96416      return SQLITE_NOMEM_BKPT;
96417    }
96418    memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
96419    pIdx->nSample++;
96420  }
96421  rc = sqlite3_finalize(pStmt);
96422  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
96423  return rc;
96424}
96425
96426/*
96427** Load content from the sqlite_stat4 and sqlite_stat3 tables into
96428** the Index.aSample[] arrays of all indices.
96429*/
96430static int loadStat4(sqlite3 *db, const char *zDb){
96431  int rc = SQLITE_OK;             /* Result codes from subroutines */
96432
96433  assert( db->lookaside.bDisable );
96434  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
96435    rc = loadStatTbl(db, 0,
96436      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
96437      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
96438      zDb
96439    );
96440  }
96441
96442  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
96443    rc = loadStatTbl(db, 1,
96444      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
96445      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
96446      zDb
96447    );
96448  }
96449
96450  return rc;
96451}
96452#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96453
96454/*
96455** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
96456** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
96457** arrays. The contents of sqlite_stat3/4 are used to populate the
96458** Index.aSample[] arrays.
96459**
96460** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
96461** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
96462** during compilation and the sqlite_stat3/4 table is present, no data is
96463** read from it.
96464**
96465** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
96466** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
96467** returned. However, in this case, data is read from the sqlite_stat1
96468** table (if it is present) before returning.
96469**
96470** If an OOM error occurs, this function always sets db->mallocFailed.
96471** This means if the caller does not care about other errors, the return
96472** code may be ignored.
96473*/
96474SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
96475  analysisInfo sInfo;
96476  HashElem *i;
96477  char *zSql;
96478  int rc = SQLITE_OK;
96479
96480  assert( iDb>=0 && iDb<db->nDb );
96481  assert( db->aDb[iDb].pBt!=0 );
96482
96483  /* Clear any prior statistics */
96484  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96485  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96486    Index *pIdx = sqliteHashData(i);
96487    pIdx->aiRowLogEst[0] = 0;
96488#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96489    sqlite3DeleteIndexSamples(db, pIdx);
96490    pIdx->aSample = 0;
96491#endif
96492  }
96493
96494  /* Load new statistics out of the sqlite_stat1 table */
96495  sInfo.db = db;
96496  sInfo.zDatabase = db->aDb[iDb].zName;
96497  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
96498    zSql = sqlite3MPrintf(db,
96499        "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
96500    if( zSql==0 ){
96501      rc = SQLITE_NOMEM_BKPT;
96502    }else{
96503      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
96504      sqlite3DbFree(db, zSql);
96505    }
96506  }
96507
96508  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
96509  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96510  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96511    Index *pIdx = sqliteHashData(i);
96512    if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
96513  }
96514
96515  /* Load the statistics from the sqlite_stat4 table. */
96516#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96517  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
96518    db->lookaside.bDisable++;
96519    rc = loadStat4(db, sInfo.zDatabase);
96520    db->lookaside.bDisable--;
96521  }
96522  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96523    Index *pIdx = sqliteHashData(i);
96524    sqlite3_free(pIdx->aiRowEst);
96525    pIdx->aiRowEst = 0;
96526  }
96527#endif
96528
96529  if( rc==SQLITE_NOMEM ){
96530    sqlite3OomFault(db);
96531  }
96532  return rc;
96533}
96534
96535
96536#endif /* SQLITE_OMIT_ANALYZE */
96537
96538/************** End of analyze.c *********************************************/
96539/************** Begin file attach.c ******************************************/
96540/*
96541** 2003 April 6
96542**
96543** The author disclaims copyright to this source code.  In place of
96544** a legal notice, here is a blessing:
96545**
96546**    May you do good and not evil.
96547**    May you find forgiveness for yourself and forgive others.
96548**    May you share freely, never taking more than you give.
96549**
96550*************************************************************************
96551** This file contains code used to implement the ATTACH and DETACH commands.
96552*/
96553/* #include "sqliteInt.h" */
96554
96555#ifndef SQLITE_OMIT_ATTACH
96556/*
96557** Resolve an expression that was part of an ATTACH or DETACH statement. This
96558** is slightly different from resolving a normal SQL expression, because simple
96559** identifiers are treated as strings, not possible column names or aliases.
96560**
96561** i.e. if the parser sees:
96562**
96563**     ATTACH DATABASE abc AS def
96564**
96565** it treats the two expressions as literal strings 'abc' and 'def' instead of
96566** looking for columns of the same name.
96567**
96568** This only applies to the root node of pExpr, so the statement:
96569**
96570**     ATTACH DATABASE abc||def AS 'db2'
96571**
96572** will fail because neither abc or def can be resolved.
96573*/
96574static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
96575{
96576  int rc = SQLITE_OK;
96577  if( pExpr ){
96578    if( pExpr->op!=TK_ID ){
96579      rc = sqlite3ResolveExprNames(pName, pExpr);
96580    }else{
96581      pExpr->op = TK_STRING;
96582    }
96583  }
96584  return rc;
96585}
96586
96587/*
96588** An SQL user-function registered to do the work of an ATTACH statement. The
96589** three arguments to the function come directly from an attach statement:
96590**
96591**     ATTACH DATABASE x AS y KEY z
96592**
96593**     SELECT sqlite_attach(x, y, z)
96594**
96595** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
96596** third argument.
96597*/
96598static void attachFunc(
96599  sqlite3_context *context,
96600  int NotUsed,
96601  sqlite3_value **argv
96602){
96603  int i;
96604  int rc = 0;
96605  sqlite3 *db = sqlite3_context_db_handle(context);
96606  const char *zName;
96607  const char *zFile;
96608  char *zPath = 0;
96609  char *zErr = 0;
96610  unsigned int flags;
96611  Db *aNew;
96612  char *zErrDyn = 0;
96613  sqlite3_vfs *pVfs;
96614
96615  UNUSED_PARAMETER(NotUsed);
96616
96617  zFile = (const char *)sqlite3_value_text(argv[0]);
96618  zName = (const char *)sqlite3_value_text(argv[1]);
96619  if( zFile==0 ) zFile = "";
96620  if( zName==0 ) zName = "";
96621
96622  /* Check for the following errors:
96623  **
96624  **     * Too many attached databases,
96625  **     * Transaction currently open
96626  **     * Specified database name already being used.
96627  */
96628  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
96629    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
96630      db->aLimit[SQLITE_LIMIT_ATTACHED]
96631    );
96632    goto attach_error;
96633  }
96634  if( !db->autoCommit ){
96635    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
96636    goto attach_error;
96637  }
96638  for(i=0; i<db->nDb; i++){
96639    char *z = db->aDb[i].zName;
96640    assert( z && zName );
96641    if( sqlite3StrICmp(z, zName)==0 ){
96642      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
96643      goto attach_error;
96644    }
96645  }
96646
96647  /* Allocate the new entry in the db->aDb[] array and initialize the schema
96648  ** hash tables.
96649  */
96650  if( db->aDb==db->aDbStatic ){
96651    aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
96652    if( aNew==0 ) return;
96653    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
96654  }else{
96655    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
96656    if( aNew==0 ) return;
96657  }
96658  db->aDb = aNew;
96659  aNew = &db->aDb[db->nDb];
96660  memset(aNew, 0, sizeof(*aNew));
96661
96662  /* Open the database file. If the btree is successfully opened, use
96663  ** it to obtain the database schema. At this point the schema may
96664  ** or may not be initialized.
96665  */
96666  flags = db->openFlags;
96667  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
96668  if( rc!=SQLITE_OK ){
96669    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
96670    sqlite3_result_error(context, zErr, -1);
96671    sqlite3_free(zErr);
96672    return;
96673  }
96674  assert( pVfs );
96675  flags |= SQLITE_OPEN_MAIN_DB;
96676  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
96677  sqlite3_free( zPath );
96678  db->nDb++;
96679  if( rc==SQLITE_CONSTRAINT ){
96680    rc = SQLITE_ERROR;
96681    zErrDyn = sqlite3MPrintf(db, "database is already attached");
96682  }else if( rc==SQLITE_OK ){
96683    Pager *pPager;
96684    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
96685    if( !aNew->pSchema ){
96686      rc = SQLITE_NOMEM_BKPT;
96687    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
96688      zErrDyn = sqlite3MPrintf(db,
96689        "attached databases must use the same text encoding as main database");
96690      rc = SQLITE_ERROR;
96691    }
96692    sqlite3BtreeEnter(aNew->pBt);
96693    pPager = sqlite3BtreePager(aNew->pBt);
96694    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
96695    sqlite3BtreeSecureDelete(aNew->pBt,
96696                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
96697#ifndef SQLITE_OMIT_PAGER_PRAGMAS
96698    sqlite3BtreeSetPagerFlags(aNew->pBt,
96699                      PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
96700#endif
96701    sqlite3BtreeLeave(aNew->pBt);
96702  }
96703  aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
96704  aNew->zName = sqlite3DbStrDup(db, zName);
96705  if( rc==SQLITE_OK && aNew->zName==0 ){
96706    rc = SQLITE_NOMEM_BKPT;
96707  }
96708
96709
96710#ifdef SQLITE_HAS_CODEC
96711  if( rc==SQLITE_OK ){
96712    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
96713    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96714    int nKey;
96715    char *zKey;
96716    int t = sqlite3_value_type(argv[2]);
96717    switch( t ){
96718      case SQLITE_INTEGER:
96719      case SQLITE_FLOAT:
96720        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
96721        rc = SQLITE_ERROR;
96722        break;
96723
96724      case SQLITE_TEXT:
96725      case SQLITE_BLOB:
96726        nKey = sqlite3_value_bytes(argv[2]);
96727        zKey = (char *)sqlite3_value_blob(argv[2]);
96728        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96729        break;
96730
96731      case SQLITE_NULL:
96732        /* No key specified.  Use the key from the main database */
96733        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96734        if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
96735          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96736        }
96737        break;
96738    }
96739  }
96740#endif
96741
96742  /* If the file was opened successfully, read the schema for the new database.
96743  ** If this fails, or if opening the file failed, then close the file and
96744  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
96745  ** we found it.
96746  */
96747  if( rc==SQLITE_OK ){
96748    sqlite3BtreeEnterAll(db);
96749    rc = sqlite3Init(db, &zErrDyn);
96750    sqlite3BtreeLeaveAll(db);
96751  }
96752#ifdef SQLITE_USER_AUTHENTICATION
96753  if( rc==SQLITE_OK ){
96754    u8 newAuth = 0;
96755    rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
96756    if( newAuth<db->auth.authLevel ){
96757      rc = SQLITE_AUTH_USER;
96758    }
96759  }
96760#endif
96761  if( rc ){
96762    int iDb = db->nDb - 1;
96763    assert( iDb>=2 );
96764    if( db->aDb[iDb].pBt ){
96765      sqlite3BtreeClose(db->aDb[iDb].pBt);
96766      db->aDb[iDb].pBt = 0;
96767      db->aDb[iDb].pSchema = 0;
96768    }
96769    sqlite3ResetAllSchemasOfConnection(db);
96770    db->nDb = iDb;
96771    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
96772      sqlite3OomFault(db);
96773      sqlite3DbFree(db, zErrDyn);
96774      zErrDyn = sqlite3MPrintf(db, "out of memory");
96775    }else if( zErrDyn==0 ){
96776      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
96777    }
96778    goto attach_error;
96779  }
96780
96781  return;
96782
96783attach_error:
96784  /* Return an error if we get here */
96785  if( zErrDyn ){
96786    sqlite3_result_error(context, zErrDyn, -1);
96787    sqlite3DbFree(db, zErrDyn);
96788  }
96789  if( rc ) sqlite3_result_error_code(context, rc);
96790}
96791
96792/*
96793** An SQL user-function registered to do the work of an DETACH statement. The
96794** three arguments to the function come directly from a detach statement:
96795**
96796**     DETACH DATABASE x
96797**
96798**     SELECT sqlite_detach(x)
96799*/
96800static void detachFunc(
96801  sqlite3_context *context,
96802  int NotUsed,
96803  sqlite3_value **argv
96804){
96805  const char *zName = (const char *)sqlite3_value_text(argv[0]);
96806  sqlite3 *db = sqlite3_context_db_handle(context);
96807  int i;
96808  Db *pDb = 0;
96809  char zErr[128];
96810
96811  UNUSED_PARAMETER(NotUsed);
96812
96813  if( zName==0 ) zName = "";
96814  for(i=0; i<db->nDb; i++){
96815    pDb = &db->aDb[i];
96816    if( pDb->pBt==0 ) continue;
96817    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
96818  }
96819
96820  if( i>=db->nDb ){
96821    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
96822    goto detach_error;
96823  }
96824  if( i<2 ){
96825    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
96826    goto detach_error;
96827  }
96828  if( !db->autoCommit ){
96829    sqlite3_snprintf(sizeof(zErr), zErr,
96830                     "cannot DETACH database within transaction");
96831    goto detach_error;
96832  }
96833  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
96834    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
96835    goto detach_error;
96836  }
96837
96838  sqlite3BtreeClose(pDb->pBt);
96839  pDb->pBt = 0;
96840  pDb->pSchema = 0;
96841  sqlite3CollapseDatabaseArray(db);
96842  return;
96843
96844detach_error:
96845  sqlite3_result_error(context, zErr, -1);
96846}
96847
96848/*
96849** This procedure generates VDBE code for a single invocation of either the
96850** sqlite_detach() or sqlite_attach() SQL user functions.
96851*/
96852static void codeAttach(
96853  Parse *pParse,       /* The parser context */
96854  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
96855  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
96856  Expr *pAuthArg,      /* Expression to pass to authorization callback */
96857  Expr *pFilename,     /* Name of database file */
96858  Expr *pDbname,       /* Name of the database to use internally */
96859  Expr *pKey           /* Database key for encryption extension */
96860){
96861  int rc;
96862  NameContext sName;
96863  Vdbe *v;
96864  sqlite3* db = pParse->db;
96865  int regArgs;
96866
96867  memset(&sName, 0, sizeof(NameContext));
96868  sName.pParse = pParse;
96869
96870  if(
96871      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
96872      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
96873      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
96874  ){
96875    goto attach_end;
96876  }
96877
96878#ifndef SQLITE_OMIT_AUTHORIZATION
96879  if( pAuthArg ){
96880    char *zAuthArg;
96881    if( pAuthArg->op==TK_STRING ){
96882      zAuthArg = pAuthArg->u.zToken;
96883    }else{
96884      zAuthArg = 0;
96885    }
96886    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
96887    if(rc!=SQLITE_OK ){
96888      goto attach_end;
96889    }
96890  }
96891#endif /* SQLITE_OMIT_AUTHORIZATION */
96892
96893
96894  v = sqlite3GetVdbe(pParse);
96895  regArgs = sqlite3GetTempRange(pParse, 4);
96896  sqlite3ExprCode(pParse, pFilename, regArgs);
96897  sqlite3ExprCode(pParse, pDbname, regArgs+1);
96898  sqlite3ExprCode(pParse, pKey, regArgs+2);
96899
96900  assert( v || db->mallocFailed );
96901  if( v ){
96902    sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
96903                      (char *)pFunc, P4_FUNCDEF);
96904    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
96905    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
96906
96907    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
96908    ** statement only). For DETACH, set it to false (expire all existing
96909    ** statements).
96910    */
96911    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
96912  }
96913
96914attach_end:
96915  sqlite3ExprDelete(db, pFilename);
96916  sqlite3ExprDelete(db, pDbname);
96917  sqlite3ExprDelete(db, pKey);
96918}
96919
96920/*
96921** Called by the parser to compile a DETACH statement.
96922**
96923**     DETACH pDbname
96924*/
96925SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
96926  static const FuncDef detach_func = {
96927    1,                /* nArg */
96928    SQLITE_UTF8,      /* funcFlags */
96929    0,                /* pUserData */
96930    0,                /* pNext */
96931    detachFunc,       /* xSFunc */
96932    0,                /* xFinalize */
96933    "sqlite_detach",  /* zName */
96934    {0}
96935  };
96936  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
96937}
96938
96939/*
96940** Called by the parser to compile an ATTACH statement.
96941**
96942**     ATTACH p AS pDbname KEY pKey
96943*/
96944SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
96945  static const FuncDef attach_func = {
96946    3,                /* nArg */
96947    SQLITE_UTF8,      /* funcFlags */
96948    0,                /* pUserData */
96949    0,                /* pNext */
96950    attachFunc,       /* xSFunc */
96951    0,                /* xFinalize */
96952    "sqlite_attach",  /* zName */
96953    {0}
96954  };
96955  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
96956}
96957#endif /* SQLITE_OMIT_ATTACH */
96958
96959/*
96960** Initialize a DbFixer structure.  This routine must be called prior
96961** to passing the structure to one of the sqliteFixAAAA() routines below.
96962*/
96963SQLITE_PRIVATE void sqlite3FixInit(
96964  DbFixer *pFix,      /* The fixer to be initialized */
96965  Parse *pParse,      /* Error messages will be written here */
96966  int iDb,            /* This is the database that must be used */
96967  const char *zType,  /* "view", "trigger", or "index" */
96968  const Token *pName  /* Name of the view, trigger, or index */
96969){
96970  sqlite3 *db;
96971
96972  db = pParse->db;
96973  assert( db->nDb>iDb );
96974  pFix->pParse = pParse;
96975  pFix->zDb = db->aDb[iDb].zName;
96976  pFix->pSchema = db->aDb[iDb].pSchema;
96977  pFix->zType = zType;
96978  pFix->pName = pName;
96979  pFix->bVarOnly = (iDb==1);
96980}
96981
96982/*
96983** The following set of routines walk through the parse tree and assign
96984** a specific database to all table references where the database name
96985** was left unspecified in the original SQL statement.  The pFix structure
96986** must have been initialized by a prior call to sqlite3FixInit().
96987**
96988** These routines are used to make sure that an index, trigger, or
96989** view in one database does not refer to objects in a different database.
96990** (Exception: indices, triggers, and views in the TEMP database are
96991** allowed to refer to anything.)  If a reference is explicitly made
96992** to an object in a different database, an error message is added to
96993** pParse->zErrMsg and these routines return non-zero.  If everything
96994** checks out, these routines return 0.
96995*/
96996SQLITE_PRIVATE int sqlite3FixSrcList(
96997  DbFixer *pFix,       /* Context of the fixation */
96998  SrcList *pList       /* The Source list to check and modify */
96999){
97000  int i;
97001  const char *zDb;
97002  struct SrcList_item *pItem;
97003
97004  if( NEVER(pList==0) ) return 0;
97005  zDb = pFix->zDb;
97006  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
97007    if( pFix->bVarOnly==0 ){
97008      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
97009        sqlite3ErrorMsg(pFix->pParse,
97010            "%s %T cannot reference objects in database %s",
97011            pFix->zType, pFix->pName, pItem->zDatabase);
97012        return 1;
97013      }
97014      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
97015      pItem->zDatabase = 0;
97016      pItem->pSchema = pFix->pSchema;
97017    }
97018#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97019    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
97020    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
97021#endif
97022  }
97023  return 0;
97024}
97025#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97026SQLITE_PRIVATE int sqlite3FixSelect(
97027  DbFixer *pFix,       /* Context of the fixation */
97028  Select *pSelect      /* The SELECT statement to be fixed to one database */
97029){
97030  while( pSelect ){
97031    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
97032      return 1;
97033    }
97034    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
97035      return 1;
97036    }
97037    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
97038      return 1;
97039    }
97040    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
97041      return 1;
97042    }
97043    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
97044      return 1;
97045    }
97046    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
97047      return 1;
97048    }
97049    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
97050      return 1;
97051    }
97052    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
97053      return 1;
97054    }
97055    pSelect = pSelect->pPrior;
97056  }
97057  return 0;
97058}
97059SQLITE_PRIVATE int sqlite3FixExpr(
97060  DbFixer *pFix,     /* Context of the fixation */
97061  Expr *pExpr        /* The expression to be fixed to one database */
97062){
97063  while( pExpr ){
97064    if( pExpr->op==TK_VARIABLE ){
97065      if( pFix->pParse->db->init.busy ){
97066        pExpr->op = TK_NULL;
97067      }else{
97068        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
97069        return 1;
97070      }
97071    }
97072    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
97073    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97074      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
97075    }else{
97076      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
97077    }
97078    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
97079      return 1;
97080    }
97081    pExpr = pExpr->pLeft;
97082  }
97083  return 0;
97084}
97085SQLITE_PRIVATE int sqlite3FixExprList(
97086  DbFixer *pFix,     /* Context of the fixation */
97087  ExprList *pList    /* The expression to be fixed to one database */
97088){
97089  int i;
97090  struct ExprList_item *pItem;
97091  if( pList==0 ) return 0;
97092  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
97093    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
97094      return 1;
97095    }
97096  }
97097  return 0;
97098}
97099#endif
97100
97101#ifndef SQLITE_OMIT_TRIGGER
97102SQLITE_PRIVATE int sqlite3FixTriggerStep(
97103  DbFixer *pFix,     /* Context of the fixation */
97104  TriggerStep *pStep /* The trigger step be fixed to one database */
97105){
97106  while( pStep ){
97107    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
97108      return 1;
97109    }
97110    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
97111      return 1;
97112    }
97113    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
97114      return 1;
97115    }
97116    pStep = pStep->pNext;
97117  }
97118  return 0;
97119}
97120#endif
97121
97122/************** End of attach.c **********************************************/
97123/************** Begin file auth.c ********************************************/
97124/*
97125** 2003 January 11
97126**
97127** The author disclaims copyright to this source code.  In place of
97128** a legal notice, here is a blessing:
97129**
97130**    May you do good and not evil.
97131**    May you find forgiveness for yourself and forgive others.
97132**    May you share freely, never taking more than you give.
97133**
97134*************************************************************************
97135** This file contains code used to implement the sqlite3_set_authorizer()
97136** API.  This facility is an optional feature of the library.  Embedded
97137** systems that do not need this facility may omit it by recompiling
97138** the library with -DSQLITE_OMIT_AUTHORIZATION=1
97139*/
97140/* #include "sqliteInt.h" */
97141
97142/*
97143** All of the code in this file may be omitted by defining a single
97144** macro.
97145*/
97146#ifndef SQLITE_OMIT_AUTHORIZATION
97147
97148/*
97149** Set or clear the access authorization function.
97150**
97151** The access authorization function is be called during the compilation
97152** phase to verify that the user has read and/or write access permission on
97153** various fields of the database.  The first argument to the auth function
97154** is a copy of the 3rd argument to this routine.  The second argument
97155** to the auth function is one of these constants:
97156**
97157**       SQLITE_CREATE_INDEX
97158**       SQLITE_CREATE_TABLE
97159**       SQLITE_CREATE_TEMP_INDEX
97160**       SQLITE_CREATE_TEMP_TABLE
97161**       SQLITE_CREATE_TEMP_TRIGGER
97162**       SQLITE_CREATE_TEMP_VIEW
97163**       SQLITE_CREATE_TRIGGER
97164**       SQLITE_CREATE_VIEW
97165**       SQLITE_DELETE
97166**       SQLITE_DROP_INDEX
97167**       SQLITE_DROP_TABLE
97168**       SQLITE_DROP_TEMP_INDEX
97169**       SQLITE_DROP_TEMP_TABLE
97170**       SQLITE_DROP_TEMP_TRIGGER
97171**       SQLITE_DROP_TEMP_VIEW
97172**       SQLITE_DROP_TRIGGER
97173**       SQLITE_DROP_VIEW
97174**       SQLITE_INSERT
97175**       SQLITE_PRAGMA
97176**       SQLITE_READ
97177**       SQLITE_SELECT
97178**       SQLITE_TRANSACTION
97179**       SQLITE_UPDATE
97180**
97181** The third and fourth arguments to the auth function are the name of
97182** the table and the column that are being accessed.  The auth function
97183** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
97184** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
97185** means that the SQL statement will never-run - the sqlite3_exec() call
97186** will return with an error.  SQLITE_IGNORE means that the SQL statement
97187** should run but attempts to read the specified column will return NULL
97188** and attempts to write the column will be ignored.
97189**
97190** Setting the auth function to NULL disables this hook.  The default
97191** setting of the auth function is NULL.
97192*/
97193SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
97194  sqlite3 *db,
97195  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
97196  void *pArg
97197){
97198#ifdef SQLITE_ENABLE_API_ARMOR
97199  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
97200#endif
97201  sqlite3_mutex_enter(db->mutex);
97202  db->xAuth = (sqlite3_xauth)xAuth;
97203  db->pAuthArg = pArg;
97204  sqlite3ExpirePreparedStatements(db);
97205  sqlite3_mutex_leave(db->mutex);
97206  return SQLITE_OK;
97207}
97208
97209/*
97210** Write an error message into pParse->zErrMsg that explains that the
97211** user-supplied authorization function returned an illegal value.
97212*/
97213static void sqliteAuthBadReturnCode(Parse *pParse){
97214  sqlite3ErrorMsg(pParse, "authorizer malfunction");
97215  pParse->rc = SQLITE_ERROR;
97216}
97217
97218/*
97219** Invoke the authorization callback for permission to read column zCol from
97220** table zTab in database zDb. This function assumes that an authorization
97221** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
97222**
97223** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
97224** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
97225** is treated as SQLITE_DENY. In this case an error is left in pParse.
97226*/
97227SQLITE_PRIVATE int sqlite3AuthReadCol(
97228  Parse *pParse,                  /* The parser context */
97229  const char *zTab,               /* Table name */
97230  const char *zCol,               /* Column name */
97231  int iDb                         /* Index of containing database. */
97232){
97233  sqlite3 *db = pParse->db;       /* Database handle */
97234  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
97235  int rc;                         /* Auth callback return code */
97236
97237  if( db->init.busy ) return SQLITE_OK;
97238  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
97239#ifdef SQLITE_USER_AUTHENTICATION
97240                 ,db->auth.zAuthUser
97241#endif
97242                );
97243  if( rc==SQLITE_DENY ){
97244    if( db->nDb>2 || iDb!=0 ){
97245      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
97246    }else{
97247      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
97248    }
97249    pParse->rc = SQLITE_AUTH;
97250  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
97251    sqliteAuthBadReturnCode(pParse);
97252  }
97253  return rc;
97254}
97255
97256/*
97257** The pExpr should be a TK_COLUMN expression.  The table referred to
97258** is in pTabList or else it is the NEW or OLD table of a trigger.
97259** Check to see if it is OK to read this particular column.
97260**
97261** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
97262** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
97263** then generate an error.
97264*/
97265SQLITE_PRIVATE void sqlite3AuthRead(
97266  Parse *pParse,        /* The parser context */
97267  Expr *pExpr,          /* The expression to check authorization on */
97268  Schema *pSchema,      /* The schema of the expression */
97269  SrcList *pTabList     /* All table that pExpr might refer to */
97270){
97271  sqlite3 *db = pParse->db;
97272  Table *pTab = 0;      /* The table being read */
97273  const char *zCol;     /* Name of the column of the table */
97274  int iSrc;             /* Index in pTabList->a[] of table being read */
97275  int iDb;              /* The index of the database the expression refers to */
97276  int iCol;             /* Index of column in table */
97277
97278  if( db->xAuth==0 ) return;
97279  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
97280  if( iDb<0 ){
97281    /* An attempt to read a column out of a subquery or other
97282    ** temporary table. */
97283    return;
97284  }
97285
97286  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
97287  if( pExpr->op==TK_TRIGGER ){
97288    pTab = pParse->pTriggerTab;
97289  }else{
97290    assert( pTabList );
97291    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
97292      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
97293        pTab = pTabList->a[iSrc].pTab;
97294        break;
97295      }
97296    }
97297  }
97298  iCol = pExpr->iColumn;
97299  if( NEVER(pTab==0) ) return;
97300
97301  if( iCol>=0 ){
97302    assert( iCol<pTab->nCol );
97303    zCol = pTab->aCol[iCol].zName;
97304  }else if( pTab->iPKey>=0 ){
97305    assert( pTab->iPKey<pTab->nCol );
97306    zCol = pTab->aCol[pTab->iPKey].zName;
97307  }else{
97308    zCol = "ROWID";
97309  }
97310  assert( iDb>=0 && iDb<db->nDb );
97311  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
97312    pExpr->op = TK_NULL;
97313  }
97314}
97315
97316/*
97317** Do an authorization check using the code and arguments given.  Return
97318** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
97319** is returned, then the error count and error message in pParse are
97320** modified appropriately.
97321*/
97322SQLITE_PRIVATE int sqlite3AuthCheck(
97323  Parse *pParse,
97324  int code,
97325  const char *zArg1,
97326  const char *zArg2,
97327  const char *zArg3
97328){
97329  sqlite3 *db = pParse->db;
97330  int rc;
97331
97332  /* Don't do any authorization checks if the database is initialising
97333  ** or if the parser is being invoked from within sqlite3_declare_vtab.
97334  */
97335  if( db->init.busy || IN_DECLARE_VTAB ){
97336    return SQLITE_OK;
97337  }
97338
97339  if( db->xAuth==0 ){
97340    return SQLITE_OK;
97341  }
97342  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
97343#ifdef SQLITE_USER_AUTHENTICATION
97344                 ,db->auth.zAuthUser
97345#endif
97346                );
97347  if( rc==SQLITE_DENY ){
97348    sqlite3ErrorMsg(pParse, "not authorized");
97349    pParse->rc = SQLITE_AUTH;
97350  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
97351    rc = SQLITE_DENY;
97352    sqliteAuthBadReturnCode(pParse);
97353  }
97354  return rc;
97355}
97356
97357/*
97358** Push an authorization context.  After this routine is called, the
97359** zArg3 argument to authorization callbacks will be zContext until
97360** popped.  Or if pParse==0, this routine is a no-op.
97361*/
97362SQLITE_PRIVATE void sqlite3AuthContextPush(
97363  Parse *pParse,
97364  AuthContext *pContext,
97365  const char *zContext
97366){
97367  assert( pParse );
97368  pContext->pParse = pParse;
97369  pContext->zAuthContext = pParse->zAuthContext;
97370  pParse->zAuthContext = zContext;
97371}
97372
97373/*
97374** Pop an authorization context that was previously pushed
97375** by sqlite3AuthContextPush
97376*/
97377SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
97378  if( pContext->pParse ){
97379    pContext->pParse->zAuthContext = pContext->zAuthContext;
97380    pContext->pParse = 0;
97381  }
97382}
97383
97384#endif /* SQLITE_OMIT_AUTHORIZATION */
97385
97386/************** End of auth.c ************************************************/
97387/************** Begin file build.c *******************************************/
97388/*
97389** 2001 September 15
97390**
97391** The author disclaims copyright to this source code.  In place of
97392** a legal notice, here is a blessing:
97393**
97394**    May you do good and not evil.
97395**    May you find forgiveness for yourself and forgive others.
97396**    May you share freely, never taking more than you give.
97397**
97398*************************************************************************
97399** This file contains C code routines that are called by the SQLite parser
97400** when syntax rules are reduced.  The routines in this file handle the
97401** following kinds of SQL syntax:
97402**
97403**     CREATE TABLE
97404**     DROP TABLE
97405**     CREATE INDEX
97406**     DROP INDEX
97407**     creating ID lists
97408**     BEGIN TRANSACTION
97409**     COMMIT
97410**     ROLLBACK
97411*/
97412/* #include "sqliteInt.h" */
97413
97414#ifndef SQLITE_OMIT_SHARED_CACHE
97415/*
97416** The TableLock structure is only used by the sqlite3TableLock() and
97417** codeTableLocks() functions.
97418*/
97419struct TableLock {
97420  int iDb;             /* The database containing the table to be locked */
97421  int iTab;            /* The root page of the table to be locked */
97422  u8 isWriteLock;      /* True for write lock.  False for a read lock */
97423  const char *zName;   /* Name of the table */
97424};
97425
97426/*
97427** Record the fact that we want to lock a table at run-time.
97428**
97429** The table to be locked has root page iTab and is found in database iDb.
97430** A read or a write lock can be taken depending on isWritelock.
97431**
97432** This routine just records the fact that the lock is desired.  The
97433** code to make the lock occur is generated by a later call to
97434** codeTableLocks() which occurs during sqlite3FinishCoding().
97435*/
97436SQLITE_PRIVATE void sqlite3TableLock(
97437  Parse *pParse,     /* Parsing context */
97438  int iDb,           /* Index of the database containing the table to lock */
97439  int iTab,          /* Root page number of the table to be locked */
97440  u8 isWriteLock,    /* True for a write lock */
97441  const char *zName  /* Name of the table to be locked */
97442){
97443  Parse *pToplevel = sqlite3ParseToplevel(pParse);
97444  int i;
97445  int nBytes;
97446  TableLock *p;
97447  assert( iDb>=0 );
97448
97449  for(i=0; i<pToplevel->nTableLock; i++){
97450    p = &pToplevel->aTableLock[i];
97451    if( p->iDb==iDb && p->iTab==iTab ){
97452      p->isWriteLock = (p->isWriteLock || isWriteLock);
97453      return;
97454    }
97455  }
97456
97457  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
97458  pToplevel->aTableLock =
97459      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
97460  if( pToplevel->aTableLock ){
97461    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
97462    p->iDb = iDb;
97463    p->iTab = iTab;
97464    p->isWriteLock = isWriteLock;
97465    p->zName = zName;
97466  }else{
97467    pToplevel->nTableLock = 0;
97468    sqlite3OomFault(pToplevel->db);
97469  }
97470}
97471
97472/*
97473** Code an OP_TableLock instruction for each table locked by the
97474** statement (configured by calls to sqlite3TableLock()).
97475*/
97476static void codeTableLocks(Parse *pParse){
97477  int i;
97478  Vdbe *pVdbe;
97479
97480  pVdbe = sqlite3GetVdbe(pParse);
97481  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
97482
97483  for(i=0; i<pParse->nTableLock; i++){
97484    TableLock *p = &pParse->aTableLock[i];
97485    int p1 = p->iDb;
97486    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
97487                      p->zName, P4_STATIC);
97488  }
97489}
97490#else
97491  #define codeTableLocks(x)
97492#endif
97493
97494/*
97495** Return TRUE if the given yDbMask object is empty - if it contains no
97496** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
97497** macros when SQLITE_MAX_ATTACHED is greater than 30.
97498*/
97499#if SQLITE_MAX_ATTACHED>30
97500SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
97501  int i;
97502  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
97503  return 1;
97504}
97505#endif
97506
97507/*
97508** This routine is called after a single SQL statement has been
97509** parsed and a VDBE program to execute that statement has been
97510** prepared.  This routine puts the finishing touches on the
97511** VDBE program and resets the pParse structure for the next
97512** parse.
97513**
97514** Note that if an error occurred, it might be the case that
97515** no VDBE code was generated.
97516*/
97517SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
97518  sqlite3 *db;
97519  Vdbe *v;
97520
97521  assert( pParse->pToplevel==0 );
97522  db = pParse->db;
97523  if( pParse->nested ) return;
97524  if( db->mallocFailed || pParse->nErr ){
97525    if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
97526    return;
97527  }
97528
97529  /* Begin by generating some termination code at the end of the
97530  ** vdbe program
97531  */
97532  v = sqlite3GetVdbe(pParse);
97533  assert( !pParse->isMultiWrite
97534       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
97535  if( v ){
97536    while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
97537    sqlite3VdbeAddOp0(v, OP_Halt);
97538
97539#if SQLITE_USER_AUTHENTICATION
97540    if( pParse->nTableLock>0 && db->init.busy==0 ){
97541      sqlite3UserAuthInit(db);
97542      if( db->auth.authLevel<UAUTH_User ){
97543        pParse->rc = SQLITE_AUTH_USER;
97544        sqlite3ErrorMsg(pParse, "user not authenticated");
97545        return;
97546      }
97547    }
97548#endif
97549
97550    /* The cookie mask contains one bit for each database file open.
97551    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
97552    ** set for each database that is used.  Generate code to start a
97553    ** transaction on each used database and to verify the schema cookie
97554    ** on each used database.
97555    */
97556    if( db->mallocFailed==0
97557     && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
97558    ){
97559      int iDb, i;
97560      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
97561      sqlite3VdbeJumpHere(v, 0);
97562      for(iDb=0; iDb<db->nDb; iDb++){
97563        if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
97564        sqlite3VdbeUsesBtree(v, iDb);
97565        sqlite3VdbeAddOp4Int(v,
97566          OP_Transaction,                    /* Opcode */
97567          iDb,                               /* P1 */
97568          DbMaskTest(pParse->writeMask,iDb), /* P2 */
97569          pParse->cookieValue[iDb],          /* P3 */
97570          db->aDb[iDb].pSchema->iGeneration  /* P4 */
97571        );
97572        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
97573        VdbeComment((v,
97574              "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
97575      }
97576#ifndef SQLITE_OMIT_VIRTUALTABLE
97577      for(i=0; i<pParse->nVtabLock; i++){
97578        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
97579        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
97580      }
97581      pParse->nVtabLock = 0;
97582#endif
97583
97584      /* Once all the cookies have been verified and transactions opened,
97585      ** obtain the required table-locks. This is a no-op unless the
97586      ** shared-cache feature is enabled.
97587      */
97588      codeTableLocks(pParse);
97589
97590      /* Initialize any AUTOINCREMENT data structures required.
97591      */
97592      sqlite3AutoincrementBegin(pParse);
97593
97594      /* Code constant expressions that where factored out of inner loops */
97595      if( pParse->pConstExpr ){
97596        ExprList *pEL = pParse->pConstExpr;
97597        pParse->okConstFactor = 0;
97598        for(i=0; i<pEL->nExpr; i++){
97599          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
97600        }
97601      }
97602
97603      /* Finally, jump back to the beginning of the executable code. */
97604      sqlite3VdbeGoto(v, 1);
97605    }
97606  }
97607
97608
97609  /* Get the VDBE program ready for execution
97610  */
97611  if( v && pParse->nErr==0 && !db->mallocFailed ){
97612    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
97613    /* A minimum of one cursor is required if autoincrement is used
97614    *  See ticket [a696379c1f08866] */
97615    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
97616    sqlite3VdbeMakeReady(v, pParse);
97617    pParse->rc = SQLITE_DONE;
97618  }else{
97619    pParse->rc = SQLITE_ERROR;
97620  }
97621
97622  /* We are done with this Parse object. There is no need to de-initialize it */
97623#if 0
97624  pParse->colNamesSet = 0;
97625  pParse->nTab = 0;
97626  pParse->nMem = 0;
97627  pParse->nSet = 0;
97628  pParse->nVar = 0;
97629  DbMaskZero(pParse->cookieMask);
97630#endif
97631}
97632
97633/*
97634** Run the parser and code generator recursively in order to generate
97635** code for the SQL statement given onto the end of the pParse context
97636** currently under construction.  When the parser is run recursively
97637** this way, the final OP_Halt is not appended and other initialization
97638** and finalization steps are omitted because those are handling by the
97639** outermost parser.
97640**
97641** Not everything is nestable.  This facility is designed to permit
97642** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
97643** care if you decide to try to use this routine for some other purposes.
97644*/
97645SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
97646  va_list ap;
97647  char *zSql;
97648  char *zErrMsg = 0;
97649  sqlite3 *db = pParse->db;
97650# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
97651  char saveBuf[SAVE_SZ];
97652
97653  if( pParse->nErr ) return;
97654  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
97655  va_start(ap, zFormat);
97656  zSql = sqlite3VMPrintf(db, zFormat, ap);
97657  va_end(ap);
97658  if( zSql==0 ){
97659    return;   /* A malloc must have failed */
97660  }
97661  pParse->nested++;
97662  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
97663  memset(&pParse->nVar, 0, SAVE_SZ);
97664  sqlite3RunParser(pParse, zSql, &zErrMsg);
97665  sqlite3DbFree(db, zErrMsg);
97666  sqlite3DbFree(db, zSql);
97667  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
97668  pParse->nested--;
97669}
97670
97671#if SQLITE_USER_AUTHENTICATION
97672/*
97673** Return TRUE if zTable is the name of the system table that stores the
97674** list of users and their access credentials.
97675*/
97676SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
97677  return sqlite3_stricmp(zTable, "sqlite_user")==0;
97678}
97679#endif
97680
97681/*
97682** Locate the in-memory structure that describes a particular database
97683** table given the name of that table and (optionally) the name of the
97684** database containing the table.  Return NULL if not found.
97685**
97686** If zDatabase is 0, all databases are searched for the table and the
97687** first matching table is returned.  (No checking for duplicate table
97688** names is done.)  The search order is TEMP first, then MAIN, then any
97689** auxiliary databases added using the ATTACH command.
97690**
97691** See also sqlite3LocateTable().
97692*/
97693SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
97694  Table *p = 0;
97695  int i;
97696
97697  /* All mutexes are required for schema access.  Make sure we hold them. */
97698  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97699#if SQLITE_USER_AUTHENTICATION
97700  /* Only the admin user is allowed to know that the sqlite_user table
97701  ** exists */
97702  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
97703    return 0;
97704  }
97705#endif
97706  for(i=OMIT_TEMPDB; i<db->nDb; i++){
97707    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
97708    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
97709    assert( sqlite3SchemaMutexHeld(db, j, 0) );
97710    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
97711    if( p ) break;
97712  }
97713  return p;
97714}
97715
97716/*
97717** Locate the in-memory structure that describes a particular database
97718** table given the name of that table and (optionally) the name of the
97719** database containing the table.  Return NULL if not found.  Also leave an
97720** error message in pParse->zErrMsg.
97721**
97722** The difference between this routine and sqlite3FindTable() is that this
97723** routine leaves an error message in pParse->zErrMsg where
97724** sqlite3FindTable() does not.
97725*/
97726SQLITE_PRIVATE Table *sqlite3LocateTable(
97727  Parse *pParse,         /* context in which to report errors */
97728  u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
97729  const char *zName,     /* Name of the table we are looking for */
97730  const char *zDbase     /* Name of the database.  Might be NULL */
97731){
97732  Table *p;
97733
97734  /* Read the database schema. If an error occurs, leave an error message
97735  ** and code in pParse and return NULL. */
97736  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97737    return 0;
97738  }
97739
97740  p = sqlite3FindTable(pParse->db, zName, zDbase);
97741  if( p==0 ){
97742    const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
97743#ifndef SQLITE_OMIT_VIRTUALTABLE
97744    if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
97745      /* If zName is the not the name of a table in the schema created using
97746      ** CREATE, then check to see if it is the name of an virtual table that
97747      ** can be an eponymous virtual table. */
97748      Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
97749      if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
97750        return pMod->pEpoTab;
97751      }
97752    }
97753#endif
97754    if( (flags & LOCATE_NOERR)==0 ){
97755      if( zDbase ){
97756        sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
97757      }else{
97758        sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
97759      }
97760      pParse->checkSchema = 1;
97761    }
97762  }
97763
97764  return p;
97765}
97766
97767/*
97768** Locate the table identified by *p.
97769**
97770** This is a wrapper around sqlite3LocateTable(). The difference between
97771** sqlite3LocateTable() and this function is that this function restricts
97772** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
97773** non-NULL if it is part of a view or trigger program definition. See
97774** sqlite3FixSrcList() for details.
97775*/
97776SQLITE_PRIVATE Table *sqlite3LocateTableItem(
97777  Parse *pParse,
97778  u32 flags,
97779  struct SrcList_item *p
97780){
97781  const char *zDb;
97782  assert( p->pSchema==0 || p->zDatabase==0 );
97783  if( p->pSchema ){
97784    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
97785    zDb = pParse->db->aDb[iDb].zName;
97786  }else{
97787    zDb = p->zDatabase;
97788  }
97789  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
97790}
97791
97792/*
97793** Locate the in-memory structure that describes
97794** a particular index given the name of that index
97795** and the name of the database that contains the index.
97796** Return NULL if not found.
97797**
97798** If zDatabase is 0, all databases are searched for the
97799** table and the first matching index is returned.  (No checking
97800** for duplicate index names is done.)  The search order is
97801** TEMP first, then MAIN, then any auxiliary databases added
97802** using the ATTACH command.
97803*/
97804SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
97805  Index *p = 0;
97806  int i;
97807  /* All mutexes are required for schema access.  Make sure we hold them. */
97808  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97809  for(i=OMIT_TEMPDB; i<db->nDb; i++){
97810    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
97811    Schema *pSchema = db->aDb[j].pSchema;
97812    assert( pSchema );
97813    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
97814    assert( sqlite3SchemaMutexHeld(db, j, 0) );
97815    p = sqlite3HashFind(&pSchema->idxHash, zName);
97816    if( p ) break;
97817  }
97818  return p;
97819}
97820
97821/*
97822** Reclaim the memory used by an index
97823*/
97824static void freeIndex(sqlite3 *db, Index *p){
97825#ifndef SQLITE_OMIT_ANALYZE
97826  sqlite3DeleteIndexSamples(db, p);
97827#endif
97828  sqlite3ExprDelete(db, p->pPartIdxWhere);
97829  sqlite3ExprListDelete(db, p->aColExpr);
97830  sqlite3DbFree(db, p->zColAff);
97831  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
97832#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97833  sqlite3_free(p->aiRowEst);
97834#endif
97835  sqlite3DbFree(db, p);
97836}
97837
97838/*
97839** For the index called zIdxName which is found in the database iDb,
97840** unlike that index from its Table then remove the index from
97841** the index hash table and free all memory structures associated
97842** with the index.
97843*/
97844SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
97845  Index *pIndex;
97846  Hash *pHash;
97847
97848  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97849  pHash = &db->aDb[iDb].pSchema->idxHash;
97850  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
97851  if( ALWAYS(pIndex) ){
97852    if( pIndex->pTable->pIndex==pIndex ){
97853      pIndex->pTable->pIndex = pIndex->pNext;
97854    }else{
97855      Index *p;
97856      /* Justification of ALWAYS();  The index must be on the list of
97857      ** indices. */
97858      p = pIndex->pTable->pIndex;
97859      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
97860      if( ALWAYS(p && p->pNext==pIndex) ){
97861        p->pNext = pIndex->pNext;
97862      }
97863    }
97864    freeIndex(db, pIndex);
97865  }
97866  db->flags |= SQLITE_InternChanges;
97867}
97868
97869/*
97870** Look through the list of open database files in db->aDb[] and if
97871** any have been closed, remove them from the list.  Reallocate the
97872** db->aDb[] structure to a smaller size, if possible.
97873**
97874** Entry 0 (the "main" database) and entry 1 (the "temp" database)
97875** are never candidates for being collapsed.
97876*/
97877SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
97878  int i, j;
97879  for(i=j=2; i<db->nDb; i++){
97880    struct Db *pDb = &db->aDb[i];
97881    if( pDb->pBt==0 ){
97882      sqlite3DbFree(db, pDb->zName);
97883      pDb->zName = 0;
97884      continue;
97885    }
97886    if( j<i ){
97887      db->aDb[j] = db->aDb[i];
97888    }
97889    j++;
97890  }
97891  db->nDb = j;
97892  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
97893    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
97894    sqlite3DbFree(db, db->aDb);
97895    db->aDb = db->aDbStatic;
97896  }
97897}
97898
97899/*
97900** Reset the schema for the database at index iDb.  Also reset the
97901** TEMP schema.
97902*/
97903SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
97904  Db *pDb;
97905  assert( iDb<db->nDb );
97906
97907  /* Case 1:  Reset the single schema identified by iDb */
97908  pDb = &db->aDb[iDb];
97909  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97910  assert( pDb->pSchema!=0 );
97911  sqlite3SchemaClear(pDb->pSchema);
97912
97913  /* If any database other than TEMP is reset, then also reset TEMP
97914  ** since TEMP might be holding triggers that reference tables in the
97915  ** other database.
97916  */
97917  if( iDb!=1 ){
97918    pDb = &db->aDb[1];
97919    assert( pDb->pSchema!=0 );
97920    sqlite3SchemaClear(pDb->pSchema);
97921  }
97922  return;
97923}
97924
97925/*
97926** Erase all schema information from all attached databases (including
97927** "main" and "temp") for a single database connection.
97928*/
97929SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
97930  int i;
97931  sqlite3BtreeEnterAll(db);
97932  for(i=0; i<db->nDb; i++){
97933    Db *pDb = &db->aDb[i];
97934    if( pDb->pSchema ){
97935      sqlite3SchemaClear(pDb->pSchema);
97936    }
97937  }
97938  db->flags &= ~SQLITE_InternChanges;
97939  sqlite3VtabUnlockList(db);
97940  sqlite3BtreeLeaveAll(db);
97941  sqlite3CollapseDatabaseArray(db);
97942}
97943
97944/*
97945** This routine is called when a commit occurs.
97946*/
97947SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
97948  db->flags &= ~SQLITE_InternChanges;
97949}
97950
97951/*
97952** Delete memory allocated for the column names of a table or view (the
97953** Table.aCol[] array).
97954*/
97955SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
97956  int i;
97957  Column *pCol;
97958  assert( pTable!=0 );
97959  if( (pCol = pTable->aCol)!=0 ){
97960    for(i=0; i<pTable->nCol; i++, pCol++){
97961      sqlite3DbFree(db, pCol->zName);
97962      sqlite3ExprDelete(db, pCol->pDflt);
97963      sqlite3DbFree(db, pCol->zColl);
97964    }
97965    sqlite3DbFree(db, pTable->aCol);
97966  }
97967}
97968
97969/*
97970** Remove the memory data structures associated with the given
97971** Table.  No changes are made to disk by this routine.
97972**
97973** This routine just deletes the data structure.  It does not unlink
97974** the table data structure from the hash table.  But it does destroy
97975** memory structures of the indices and foreign keys associated with
97976** the table.
97977**
97978** The db parameter is optional.  It is needed if the Table object
97979** contains lookaside memory.  (Table objects in the schema do not use
97980** lookaside memory, but some ephemeral Table objects do.)  Or the
97981** db parameter can be used with db->pnBytesFreed to measure the memory
97982** used by the Table object.
97983*/
97984static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
97985  Index *pIndex, *pNext;
97986  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
97987
97988  /* Record the number of outstanding lookaside allocations in schema Tables
97989  ** prior to doing any free() operations.  Since schema Tables do not use
97990  ** lookaside, this number should not change. */
97991  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
97992                         db->lookaside.nOut : 0 );
97993
97994  /* Delete all indices associated with this table. */
97995  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
97996    pNext = pIndex->pNext;
97997    assert( pIndex->pSchema==pTable->pSchema
97998         || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
97999    if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
98000      char *zName = pIndex->zName;
98001      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
98002         &pIndex->pSchema->idxHash, zName, 0
98003      );
98004      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
98005      assert( pOld==pIndex || pOld==0 );
98006    }
98007    freeIndex(db, pIndex);
98008  }
98009
98010  /* Delete any foreign keys attached to this table. */
98011  sqlite3FkDelete(db, pTable);
98012
98013  /* Delete the Table structure itself.
98014  */
98015  sqlite3DeleteColumnNames(db, pTable);
98016  sqlite3DbFree(db, pTable->zName);
98017  sqlite3DbFree(db, pTable->zColAff);
98018  sqlite3SelectDelete(db, pTable->pSelect);
98019  sqlite3ExprListDelete(db, pTable->pCheck);
98020#ifndef SQLITE_OMIT_VIRTUALTABLE
98021  sqlite3VtabClear(db, pTable);
98022#endif
98023  sqlite3DbFree(db, pTable);
98024
98025  /* Verify that no lookaside memory was used by schema tables */
98026  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
98027}
98028SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
98029  /* Do not delete the table until the reference count reaches zero. */
98030  if( !pTable ) return;
98031  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
98032  deleteTable(db, pTable);
98033}
98034
98035
98036/*
98037** Unlink the given table from the hash tables and the delete the
98038** table structure with all its indices and foreign keys.
98039*/
98040SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
98041  Table *p;
98042  Db *pDb;
98043
98044  assert( db!=0 );
98045  assert( iDb>=0 && iDb<db->nDb );
98046  assert( zTabName );
98047  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98048  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
98049  pDb = &db->aDb[iDb];
98050  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
98051  sqlite3DeleteTable(db, p);
98052  db->flags |= SQLITE_InternChanges;
98053}
98054
98055/*
98056** Given a token, return a string that consists of the text of that
98057** token.  Space to hold the returned string
98058** is obtained from sqliteMalloc() and must be freed by the calling
98059** function.
98060**
98061** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
98062** surround the body of the token are removed.
98063**
98064** Tokens are often just pointers into the original SQL text and so
98065** are not \000 terminated and are not persistent.  The returned string
98066** is \000 terminated and is persistent.
98067*/
98068SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
98069  char *zName;
98070  if( pName ){
98071    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
98072    sqlite3Dequote(zName);
98073  }else{
98074    zName = 0;
98075  }
98076  return zName;
98077}
98078
98079/*
98080** Open the sqlite_master table stored in database number iDb for
98081** writing. The table is opened using cursor 0.
98082*/
98083SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
98084  Vdbe *v = sqlite3GetVdbe(p);
98085  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
98086  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
98087  if( p->nTab==0 ){
98088    p->nTab = 1;
98089  }
98090}
98091
98092/*
98093** Parameter zName points to a nul-terminated buffer containing the name
98094** of a database ("main", "temp" or the name of an attached db). This
98095** function returns the index of the named database in db->aDb[], or
98096** -1 if the named db cannot be found.
98097*/
98098SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
98099  int i = -1;         /* Database number */
98100  if( zName ){
98101    Db *pDb;
98102    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
98103      if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
98104    }
98105  }
98106  return i;
98107}
98108
98109/*
98110** The token *pName contains the name of a database (either "main" or
98111** "temp" or the name of an attached db). This routine returns the
98112** index of the named database in db->aDb[], or -1 if the named db
98113** does not exist.
98114*/
98115SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
98116  int i;                               /* Database number */
98117  char *zName;                         /* Name we are searching for */
98118  zName = sqlite3NameFromToken(db, pName);
98119  i = sqlite3FindDbName(db, zName);
98120  sqlite3DbFree(db, zName);
98121  return i;
98122}
98123
98124/* The table or view or trigger name is passed to this routine via tokens
98125** pName1 and pName2. If the table name was fully qualified, for example:
98126**
98127** CREATE TABLE xxx.yyy (...);
98128**
98129** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
98130** the table name is not fully qualified, i.e.:
98131**
98132** CREATE TABLE yyy(...);
98133**
98134** Then pName1 is set to "yyy" and pName2 is "".
98135**
98136** This routine sets the *ppUnqual pointer to point at the token (pName1 or
98137** pName2) that stores the unqualified table name.  The index of the
98138** database "xxx" is returned.
98139*/
98140SQLITE_PRIVATE int sqlite3TwoPartName(
98141  Parse *pParse,      /* Parsing and code generating context */
98142  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
98143  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
98144  Token **pUnqual     /* Write the unqualified object name here */
98145){
98146  int iDb;                    /* Database holding the object */
98147  sqlite3 *db = pParse->db;
98148
98149  assert( pName2!=0 );
98150  if( pName2->n>0 ){
98151    if( db->init.busy ) {
98152      sqlite3ErrorMsg(pParse, "corrupt database");
98153      return -1;
98154    }
98155    *pUnqual = pName2;
98156    iDb = sqlite3FindDb(db, pName1);
98157    if( iDb<0 ){
98158      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
98159      return -1;
98160    }
98161  }else{
98162    assert( db->init.iDb==0 || db->init.busy );
98163    iDb = db->init.iDb;
98164    *pUnqual = pName1;
98165  }
98166  return iDb;
98167}
98168
98169/*
98170** This routine is used to check if the UTF-8 string zName is a legal
98171** unqualified name for a new schema object (table, index, view or
98172** trigger). All names are legal except those that begin with the string
98173** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
98174** is reserved for internal use.
98175*/
98176SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
98177  if( !pParse->db->init.busy && pParse->nested==0
98178          && (pParse->db->flags & SQLITE_WriteSchema)==0
98179          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
98180    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
98181    return SQLITE_ERROR;
98182  }
98183  return SQLITE_OK;
98184}
98185
98186/*
98187** Return the PRIMARY KEY index of a table
98188*/
98189SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
98190  Index *p;
98191  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
98192  return p;
98193}
98194
98195/*
98196** Return the column of index pIdx that corresponds to table
98197** column iCol.  Return -1 if not found.
98198*/
98199SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
98200  int i;
98201  for(i=0; i<pIdx->nColumn; i++){
98202    if( iCol==pIdx->aiColumn[i] ) return i;
98203  }
98204  return -1;
98205}
98206
98207/*
98208** Begin constructing a new table representation in memory.  This is
98209** the first of several action routines that get called in response
98210** to a CREATE TABLE statement.  In particular, this routine is called
98211** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
98212** flag is true if the table should be stored in the auxiliary database
98213** file instead of in the main database file.  This is normally the case
98214** when the "TEMP" or "TEMPORARY" keyword occurs in between
98215** CREATE and TABLE.
98216**
98217** The new table record is initialized and put in pParse->pNewTable.
98218** As more of the CREATE TABLE statement is parsed, additional action
98219** routines will be called to add more information to this record.
98220** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
98221** is called to complete the construction of the new table record.
98222*/
98223SQLITE_PRIVATE void sqlite3StartTable(
98224  Parse *pParse,   /* Parser context */
98225  Token *pName1,   /* First part of the name of the table or view */
98226  Token *pName2,   /* Second part of the name of the table or view */
98227  int isTemp,      /* True if this is a TEMP table */
98228  int isView,      /* True if this is a VIEW */
98229  int isVirtual,   /* True if this is a VIRTUAL table */
98230  int noErr        /* Do nothing if table already exists */
98231){
98232  Table *pTable;
98233  char *zName = 0; /* The name of the new table */
98234  sqlite3 *db = pParse->db;
98235  Vdbe *v;
98236  int iDb;         /* Database number to create the table in */
98237  Token *pName;    /* Unqualified name of the table to create */
98238
98239  if( db->init.busy && db->init.newTnum==1 ){
98240    /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
98241    iDb = db->init.iDb;
98242    zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
98243    pName = pName1;
98244  }else{
98245    /* The common case */
98246    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
98247    if( iDb<0 ) return;
98248    if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
98249      /* If creating a temp table, the name may not be qualified. Unless
98250      ** the database name is "temp" anyway.  */
98251      sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
98252      return;
98253    }
98254    if( !OMIT_TEMPDB && isTemp ) iDb = 1;
98255    zName = sqlite3NameFromToken(db, pName);
98256  }
98257  pParse->sNameToken = *pName;
98258  if( zName==0 ) return;
98259  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
98260    goto begin_table_error;
98261  }
98262  if( db->init.iDb==1 ) isTemp = 1;
98263#ifndef SQLITE_OMIT_AUTHORIZATION
98264  assert( isTemp==0 || isTemp==1 );
98265  assert( isView==0 || isView==1 );
98266  {
98267    static const u8 aCode[] = {
98268       SQLITE_CREATE_TABLE,
98269       SQLITE_CREATE_TEMP_TABLE,
98270       SQLITE_CREATE_VIEW,
98271       SQLITE_CREATE_TEMP_VIEW
98272    };
98273    char *zDb = db->aDb[iDb].zName;
98274    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
98275      goto begin_table_error;
98276    }
98277    if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
98278                                       zName, 0, zDb) ){
98279      goto begin_table_error;
98280    }
98281  }
98282#endif
98283
98284  /* Make sure the new table name does not collide with an existing
98285  ** index or table name in the same database.  Issue an error message if
98286  ** it does. The exception is if the statement being parsed was passed
98287  ** to an sqlite3_declare_vtab() call. In that case only the column names
98288  ** and types will be used, so there is no need to test for namespace
98289  ** collisions.
98290  */
98291  if( !IN_DECLARE_VTAB ){
98292    char *zDb = db->aDb[iDb].zName;
98293    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98294      goto begin_table_error;
98295    }
98296    pTable = sqlite3FindTable(db, zName, zDb);
98297    if( pTable ){
98298      if( !noErr ){
98299        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
98300      }else{
98301        assert( !db->init.busy || CORRUPT_DB );
98302        sqlite3CodeVerifySchema(pParse, iDb);
98303      }
98304      goto begin_table_error;
98305    }
98306    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
98307      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
98308      goto begin_table_error;
98309    }
98310  }
98311
98312  pTable = sqlite3DbMallocZero(db, sizeof(Table));
98313  if( pTable==0 ){
98314    assert( db->mallocFailed );
98315    pParse->rc = SQLITE_NOMEM_BKPT;
98316    pParse->nErr++;
98317    goto begin_table_error;
98318  }
98319  pTable->zName = zName;
98320  pTable->iPKey = -1;
98321  pTable->pSchema = db->aDb[iDb].pSchema;
98322  pTable->nRef = 1;
98323  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
98324  assert( pParse->pNewTable==0 );
98325  pParse->pNewTable = pTable;
98326
98327  /* If this is the magic sqlite_sequence table used by autoincrement,
98328  ** then record a pointer to this table in the main database structure
98329  ** so that INSERT can find the table easily.
98330  */
98331#ifndef SQLITE_OMIT_AUTOINCREMENT
98332  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
98333    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98334    pTable->pSchema->pSeqTab = pTable;
98335  }
98336#endif
98337
98338  /* Begin generating the code that will insert the table record into
98339  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
98340  ** and allocate the record number for the table entry now.  Before any
98341  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
98342  ** indices to be created and the table record must come before the
98343  ** indices.  Hence, the record number for the table must be allocated
98344  ** now.
98345  */
98346  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
98347    int addr1;
98348    int fileFormat;
98349    int reg1, reg2, reg3;
98350    /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
98351    static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
98352    sqlite3BeginWriteOperation(pParse, 1, iDb);
98353
98354#ifndef SQLITE_OMIT_VIRTUALTABLE
98355    if( isVirtual ){
98356      sqlite3VdbeAddOp0(v, OP_VBegin);
98357    }
98358#endif
98359
98360    /* If the file format and encoding in the database have not been set,
98361    ** set them now.
98362    */
98363    reg1 = pParse->regRowid = ++pParse->nMem;
98364    reg2 = pParse->regRoot = ++pParse->nMem;
98365    reg3 = ++pParse->nMem;
98366    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
98367    sqlite3VdbeUsesBtree(v, iDb);
98368    addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
98369    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
98370                  1 : SQLITE_MAX_FILE_FORMAT;
98371    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
98372    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
98373    sqlite3VdbeJumpHere(v, addr1);
98374
98375    /* This just creates a place-holder record in the sqlite_master table.
98376    ** The record created does not contain anything yet.  It will be replaced
98377    ** by the real entry in code generated at sqlite3EndTable().
98378    **
98379    ** The rowid for the new entry is left in register pParse->regRowid.
98380    ** The root page number of the new table is left in reg pParse->regRoot.
98381    ** The rowid and root page number values are needed by the code that
98382    ** sqlite3EndTable will generate.
98383    */
98384#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
98385    if( isView || isVirtual ){
98386      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
98387    }else
98388#endif
98389    {
98390      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
98391    }
98392    sqlite3OpenMasterTable(pParse, iDb);
98393    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
98394    sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
98395    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
98396    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98397    sqlite3VdbeAddOp0(v, OP_Close);
98398  }
98399
98400  /* Normal (non-error) return. */
98401  return;
98402
98403  /* If an error occurs, we jump here */
98404begin_table_error:
98405  sqlite3DbFree(db, zName);
98406  return;
98407}
98408
98409/* Set properties of a table column based on the (magical)
98410** name of the column.
98411*/
98412#if SQLITE_ENABLE_HIDDEN_COLUMNS
98413SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
98414  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
98415    pCol->colFlags |= COLFLAG_HIDDEN;
98416  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
98417    pTab->tabFlags |= TF_OOOHidden;
98418  }
98419}
98420#endif
98421
98422
98423/*
98424** Add a new column to the table currently being constructed.
98425**
98426** The parser calls this routine once for each column declaration
98427** in a CREATE TABLE statement.  sqlite3StartTable() gets called
98428** first to get things going.  Then this routine is called for each
98429** column.
98430*/
98431SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
98432  Table *p;
98433  int i;
98434  char *z;
98435  char *zType;
98436  Column *pCol;
98437  sqlite3 *db = pParse->db;
98438  if( (p = pParse->pNewTable)==0 ) return;
98439#if SQLITE_MAX_COLUMN
98440  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
98441    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
98442    return;
98443  }
98444#endif
98445  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
98446  if( z==0 ) return;
98447  memcpy(z, pName->z, pName->n);
98448  z[pName->n] = 0;
98449  sqlite3Dequote(z);
98450  for(i=0; i<p->nCol; i++){
98451    if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
98452      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
98453      sqlite3DbFree(db, z);
98454      return;
98455    }
98456  }
98457  if( (p->nCol & 0x7)==0 ){
98458    Column *aNew;
98459    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
98460    if( aNew==0 ){
98461      sqlite3DbFree(db, z);
98462      return;
98463    }
98464    p->aCol = aNew;
98465  }
98466  pCol = &p->aCol[p->nCol];
98467  memset(pCol, 0, sizeof(p->aCol[0]));
98468  pCol->zName = z;
98469  sqlite3ColumnPropertiesFromName(p, pCol);
98470
98471  if( pType->n==0 ){
98472    /* If there is no type specified, columns have the default affinity
98473    ** 'BLOB'. */
98474    pCol->affinity = SQLITE_AFF_BLOB;
98475    pCol->szEst = 1;
98476  }else{
98477    zType = z + sqlite3Strlen30(z) + 1;
98478    memcpy(zType, pType->z, pType->n);
98479    zType[pType->n] = 0;
98480    sqlite3Dequote(zType);
98481    pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
98482    pCol->colFlags |= COLFLAG_HASTYPE;
98483  }
98484  p->nCol++;
98485  pParse->constraintName.n = 0;
98486}
98487
98488/*
98489** This routine is called by the parser while in the middle of
98490** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
98491** been seen on a column.  This routine sets the notNull flag on
98492** the column currently under construction.
98493*/
98494SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
98495  Table *p;
98496  p = pParse->pNewTable;
98497  if( p==0 || NEVER(p->nCol<1) ) return;
98498  p->aCol[p->nCol-1].notNull = (u8)onError;
98499}
98500
98501/*
98502** Scan the column type name zType (length nType) and return the
98503** associated affinity type.
98504**
98505** This routine does a case-independent search of zType for the
98506** substrings in the following table. If one of the substrings is
98507** found, the corresponding affinity is returned. If zType contains
98508** more than one of the substrings, entries toward the top of
98509** the table take priority. For example, if zType is 'BLOBINT',
98510** SQLITE_AFF_INTEGER is returned.
98511**
98512** Substring     | Affinity
98513** --------------------------------
98514** 'INT'         | SQLITE_AFF_INTEGER
98515** 'CHAR'        | SQLITE_AFF_TEXT
98516** 'CLOB'        | SQLITE_AFF_TEXT
98517** 'TEXT'        | SQLITE_AFF_TEXT
98518** 'BLOB'        | SQLITE_AFF_BLOB
98519** 'REAL'        | SQLITE_AFF_REAL
98520** 'FLOA'        | SQLITE_AFF_REAL
98521** 'DOUB'        | SQLITE_AFF_REAL
98522**
98523** If none of the substrings in the above table are found,
98524** SQLITE_AFF_NUMERIC is returned.
98525*/
98526SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
98527  u32 h = 0;
98528  char aff = SQLITE_AFF_NUMERIC;
98529  const char *zChar = 0;
98530
98531  assert( zIn!=0 );
98532  while( zIn[0] ){
98533    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
98534    zIn++;
98535    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
98536      aff = SQLITE_AFF_TEXT;
98537      zChar = zIn;
98538    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
98539      aff = SQLITE_AFF_TEXT;
98540    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
98541      aff = SQLITE_AFF_TEXT;
98542    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
98543        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
98544      aff = SQLITE_AFF_BLOB;
98545      if( zIn[0]=='(' ) zChar = zIn;
98546#ifndef SQLITE_OMIT_FLOATING_POINT
98547    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
98548        && aff==SQLITE_AFF_NUMERIC ){
98549      aff = SQLITE_AFF_REAL;
98550    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
98551        && aff==SQLITE_AFF_NUMERIC ){
98552      aff = SQLITE_AFF_REAL;
98553    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
98554        && aff==SQLITE_AFF_NUMERIC ){
98555      aff = SQLITE_AFF_REAL;
98556#endif
98557    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
98558      aff = SQLITE_AFF_INTEGER;
98559      break;
98560    }
98561  }
98562
98563  /* If pszEst is not NULL, store an estimate of the field size.  The
98564  ** estimate is scaled so that the size of an integer is 1.  */
98565  if( pszEst ){
98566    *pszEst = 1;   /* default size is approx 4 bytes */
98567    if( aff<SQLITE_AFF_NUMERIC ){
98568      if( zChar ){
98569        while( zChar[0] ){
98570          if( sqlite3Isdigit(zChar[0]) ){
98571            int v = 0;
98572            sqlite3GetInt32(zChar, &v);
98573            v = v/4 + 1;
98574            if( v>255 ) v = 255;
98575            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
98576            break;
98577          }
98578          zChar++;
98579        }
98580      }else{
98581        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
98582      }
98583    }
98584  }
98585  return aff;
98586}
98587
98588/*
98589** The expression is the default value for the most recently added column
98590** of the table currently under construction.
98591**
98592** Default value expressions must be constant.  Raise an exception if this
98593** is not the case.
98594**
98595** This routine is called by the parser while in the middle of
98596** parsing a CREATE TABLE statement.
98597*/
98598SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
98599  Table *p;
98600  Column *pCol;
98601  sqlite3 *db = pParse->db;
98602  p = pParse->pNewTable;
98603  if( p!=0 ){
98604    pCol = &(p->aCol[p->nCol-1]);
98605    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
98606      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
98607          pCol->zName);
98608    }else{
98609      /* A copy of pExpr is used instead of the original, as pExpr contains
98610      ** tokens that point to volatile memory. The 'span' of the expression
98611      ** is required by pragma table_info.
98612      */
98613      Expr x;
98614      sqlite3ExprDelete(db, pCol->pDflt);
98615      memset(&x, 0, sizeof(x));
98616      x.op = TK_SPAN;
98617      x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
98618                                    (int)(pSpan->zEnd - pSpan->zStart));
98619      x.pLeft = pSpan->pExpr;
98620      x.flags = EP_Skip;
98621      pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
98622      sqlite3DbFree(db, x.u.zToken);
98623    }
98624  }
98625  sqlite3ExprDelete(db, pSpan->pExpr);
98626}
98627
98628/*
98629** Backwards Compatibility Hack:
98630**
98631** Historical versions of SQLite accepted strings as column names in
98632** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
98633**
98634**     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
98635**     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
98636**
98637** This is goofy.  But to preserve backwards compatibility we continue to
98638** accept it.  This routine does the necessary conversion.  It converts
98639** the expression given in its argument from a TK_STRING into a TK_ID
98640** if the expression is just a TK_STRING with an optional COLLATE clause.
98641** If the epxression is anything other than TK_STRING, the expression is
98642** unchanged.
98643*/
98644static void sqlite3StringToId(Expr *p){
98645  if( p->op==TK_STRING ){
98646    p->op = TK_ID;
98647  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
98648    p->pLeft->op = TK_ID;
98649  }
98650}
98651
98652/*
98653** Designate the PRIMARY KEY for the table.  pList is a list of names
98654** of columns that form the primary key.  If pList is NULL, then the
98655** most recently added column of the table is the primary key.
98656**
98657** A table can have at most one primary key.  If the table already has
98658** a primary key (and this is the second primary key) then create an
98659** error.
98660**
98661** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
98662** then we will try to use that column as the rowid.  Set the Table.iPKey
98663** field of the table under construction to be the index of the
98664** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
98665** no INTEGER PRIMARY KEY.
98666**
98667** If the key is not an INTEGER PRIMARY KEY, then create a unique
98668** index for the key.  No index is created for INTEGER PRIMARY KEYs.
98669*/
98670SQLITE_PRIVATE void sqlite3AddPrimaryKey(
98671  Parse *pParse,    /* Parsing context */
98672  ExprList *pList,  /* List of field names to be indexed */
98673  int onError,      /* What to do with a uniqueness conflict */
98674  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
98675  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
98676){
98677  Table *pTab = pParse->pNewTable;
98678  Column *pCol = 0;
98679  int iCol = -1, i;
98680  int nTerm;
98681  if( pTab==0 ) goto primary_key_exit;
98682  if( pTab->tabFlags & TF_HasPrimaryKey ){
98683    sqlite3ErrorMsg(pParse,
98684      "table \"%s\" has more than one primary key", pTab->zName);
98685    goto primary_key_exit;
98686  }
98687  pTab->tabFlags |= TF_HasPrimaryKey;
98688  if( pList==0 ){
98689    iCol = pTab->nCol - 1;
98690    pCol = &pTab->aCol[iCol];
98691    pCol->colFlags |= COLFLAG_PRIMKEY;
98692    nTerm = 1;
98693  }else{
98694    nTerm = pList->nExpr;
98695    for(i=0; i<nTerm; i++){
98696      Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
98697      assert( pCExpr!=0 );
98698      sqlite3StringToId(pCExpr);
98699      if( pCExpr->op==TK_ID ){
98700        const char *zCName = pCExpr->u.zToken;
98701        for(iCol=0; iCol<pTab->nCol; iCol++){
98702          if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
98703            pCol = &pTab->aCol[iCol];
98704            pCol->colFlags |= COLFLAG_PRIMKEY;
98705            break;
98706          }
98707        }
98708      }
98709    }
98710  }
98711  if( nTerm==1
98712   && pCol
98713   && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
98714   && sortOrder!=SQLITE_SO_DESC
98715  ){
98716    pTab->iPKey = iCol;
98717    pTab->keyConf = (u8)onError;
98718    assert( autoInc==0 || autoInc==1 );
98719    pTab->tabFlags |= autoInc*TF_Autoincrement;
98720    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
98721  }else if( autoInc ){
98722#ifndef SQLITE_OMIT_AUTOINCREMENT
98723    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
98724       "INTEGER PRIMARY KEY");
98725#endif
98726  }else{
98727    sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
98728                           0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
98729    pList = 0;
98730  }
98731
98732primary_key_exit:
98733  sqlite3ExprListDelete(pParse->db, pList);
98734  return;
98735}
98736
98737/*
98738** Add a new CHECK constraint to the table currently under construction.
98739*/
98740SQLITE_PRIVATE void sqlite3AddCheckConstraint(
98741  Parse *pParse,    /* Parsing context */
98742  Expr *pCheckExpr  /* The check expression */
98743){
98744#ifndef SQLITE_OMIT_CHECK
98745  Table *pTab = pParse->pNewTable;
98746  sqlite3 *db = pParse->db;
98747  if( pTab && !IN_DECLARE_VTAB
98748   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
98749  ){
98750    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
98751    if( pParse->constraintName.n ){
98752      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
98753    }
98754  }else
98755#endif
98756  {
98757    sqlite3ExprDelete(pParse->db, pCheckExpr);
98758  }
98759}
98760
98761/*
98762** Set the collation function of the most recently parsed table column
98763** to the CollSeq given.
98764*/
98765SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
98766  Table *p;
98767  int i;
98768  char *zColl;              /* Dequoted name of collation sequence */
98769  sqlite3 *db;
98770
98771  if( (p = pParse->pNewTable)==0 ) return;
98772  i = p->nCol-1;
98773  db = pParse->db;
98774  zColl = sqlite3NameFromToken(db, pToken);
98775  if( !zColl ) return;
98776
98777  if( sqlite3LocateCollSeq(pParse, zColl) ){
98778    Index *pIdx;
98779    sqlite3DbFree(db, p->aCol[i].zColl);
98780    p->aCol[i].zColl = zColl;
98781
98782    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
98783    ** then an index may have been created on this column before the
98784    ** collation type was added. Correct this if it is the case.
98785    */
98786    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
98787      assert( pIdx->nKeyCol==1 );
98788      if( pIdx->aiColumn[0]==i ){
98789        pIdx->azColl[0] = p->aCol[i].zColl;
98790      }
98791    }
98792  }else{
98793    sqlite3DbFree(db, zColl);
98794  }
98795}
98796
98797/*
98798** This function returns the collation sequence for database native text
98799** encoding identified by the string zName, length nName.
98800**
98801** If the requested collation sequence is not available, or not available
98802** in the database native encoding, the collation factory is invoked to
98803** request it. If the collation factory does not supply such a sequence,
98804** and the sequence is available in another text encoding, then that is
98805** returned instead.
98806**
98807** If no versions of the requested collations sequence are available, or
98808** another error occurs, NULL is returned and an error message written into
98809** pParse.
98810**
98811** This routine is a wrapper around sqlite3FindCollSeq().  This routine
98812** invokes the collation factory if the named collation cannot be found
98813** and generates an error message.
98814**
98815** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
98816*/
98817SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
98818  sqlite3 *db = pParse->db;
98819  u8 enc = ENC(db);
98820  u8 initbusy = db->init.busy;
98821  CollSeq *pColl;
98822
98823  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
98824  if( !initbusy && (!pColl || !pColl->xCmp) ){
98825    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
98826  }
98827
98828  return pColl;
98829}
98830
98831
98832/*
98833** Generate code that will increment the schema cookie.
98834**
98835** The schema cookie is used to determine when the schema for the
98836** database changes.  After each schema change, the cookie value
98837** changes.  When a process first reads the schema it records the
98838** cookie.  Thereafter, whenever it goes to access the database,
98839** it checks the cookie to make sure the schema has not changed
98840** since it was last read.
98841**
98842** This plan is not completely bullet-proof.  It is possible for
98843** the schema to change multiple times and for the cookie to be
98844** set back to prior value.  But schema changes are infrequent
98845** and the probability of hitting the same cookie value is only
98846** 1 chance in 2^32.  So we're safe enough.
98847*/
98848SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
98849  sqlite3 *db = pParse->db;
98850  Vdbe *v = pParse->pVdbe;
98851  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98852  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
98853                    db->aDb[iDb].pSchema->schema_cookie+1);
98854}
98855
98856/*
98857** Measure the number of characters needed to output the given
98858** identifier.  The number returned includes any quotes used
98859** but does not include the null terminator.
98860**
98861** The estimate is conservative.  It might be larger that what is
98862** really needed.
98863*/
98864static int identLength(const char *z){
98865  int n;
98866  for(n=0; *z; n++, z++){
98867    if( *z=='"' ){ n++; }
98868  }
98869  return n + 2;
98870}
98871
98872/*
98873** The first parameter is a pointer to an output buffer. The second
98874** parameter is a pointer to an integer that contains the offset at
98875** which to write into the output buffer. This function copies the
98876** nul-terminated string pointed to by the third parameter, zSignedIdent,
98877** to the specified offset in the buffer and updates *pIdx to refer
98878** to the first byte after the last byte written before returning.
98879**
98880** If the string zSignedIdent consists entirely of alpha-numeric
98881** characters, does not begin with a digit and is not an SQL keyword,
98882** then it is copied to the output buffer exactly as it is. Otherwise,
98883** it is quoted using double-quotes.
98884*/
98885static void identPut(char *z, int *pIdx, char *zSignedIdent){
98886  unsigned char *zIdent = (unsigned char*)zSignedIdent;
98887  int i, j, needQuote;
98888  i = *pIdx;
98889
98890  for(j=0; zIdent[j]; j++){
98891    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
98892  }
98893  needQuote = sqlite3Isdigit(zIdent[0])
98894            || sqlite3KeywordCode(zIdent, j)!=TK_ID
98895            || zIdent[j]!=0
98896            || j==0;
98897
98898  if( needQuote ) z[i++] = '"';
98899  for(j=0; zIdent[j]; j++){
98900    z[i++] = zIdent[j];
98901    if( zIdent[j]=='"' ) z[i++] = '"';
98902  }
98903  if( needQuote ) z[i++] = '"';
98904  z[i] = 0;
98905  *pIdx = i;
98906}
98907
98908/*
98909** Generate a CREATE TABLE statement appropriate for the given
98910** table.  Memory to hold the text of the statement is obtained
98911** from sqliteMalloc() and must be freed by the calling function.
98912*/
98913static char *createTableStmt(sqlite3 *db, Table *p){
98914  int i, k, n;
98915  char *zStmt;
98916  char *zSep, *zSep2, *zEnd;
98917  Column *pCol;
98918  n = 0;
98919  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
98920    n += identLength(pCol->zName) + 5;
98921  }
98922  n += identLength(p->zName);
98923  if( n<50 ){
98924    zSep = "";
98925    zSep2 = ",";
98926    zEnd = ")";
98927  }else{
98928    zSep = "\n  ";
98929    zSep2 = ",\n  ";
98930    zEnd = "\n)";
98931  }
98932  n += 35 + 6*p->nCol;
98933  zStmt = sqlite3DbMallocRaw(0, n);
98934  if( zStmt==0 ){
98935    sqlite3OomFault(db);
98936    return 0;
98937  }
98938  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
98939  k = sqlite3Strlen30(zStmt);
98940  identPut(zStmt, &k, p->zName);
98941  zStmt[k++] = '(';
98942  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
98943    static const char * const azType[] = {
98944        /* SQLITE_AFF_BLOB    */ "",
98945        /* SQLITE_AFF_TEXT    */ " TEXT",
98946        /* SQLITE_AFF_NUMERIC */ " NUM",
98947        /* SQLITE_AFF_INTEGER */ " INT",
98948        /* SQLITE_AFF_REAL    */ " REAL"
98949    };
98950    int len;
98951    const char *zType;
98952
98953    sqlite3_snprintf(n-k, &zStmt[k], zSep);
98954    k += sqlite3Strlen30(&zStmt[k]);
98955    zSep = zSep2;
98956    identPut(zStmt, &k, pCol->zName);
98957    assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
98958    assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
98959    testcase( pCol->affinity==SQLITE_AFF_BLOB );
98960    testcase( pCol->affinity==SQLITE_AFF_TEXT );
98961    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
98962    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
98963    testcase( pCol->affinity==SQLITE_AFF_REAL );
98964
98965    zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
98966    len = sqlite3Strlen30(zType);
98967    assert( pCol->affinity==SQLITE_AFF_BLOB
98968            || pCol->affinity==sqlite3AffinityType(zType, 0) );
98969    memcpy(&zStmt[k], zType, len);
98970    k += len;
98971    assert( k<=n );
98972  }
98973  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
98974  return zStmt;
98975}
98976
98977/*
98978** Resize an Index object to hold N columns total.  Return SQLITE_OK
98979** on success and SQLITE_NOMEM on an OOM error.
98980*/
98981static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
98982  char *zExtra;
98983  int nByte;
98984  if( pIdx->nColumn>=N ) return SQLITE_OK;
98985  assert( pIdx->isResized==0 );
98986  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
98987  zExtra = sqlite3DbMallocZero(db, nByte);
98988  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
98989  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
98990  pIdx->azColl = (const char**)zExtra;
98991  zExtra += sizeof(char*)*N;
98992  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
98993  pIdx->aiColumn = (i16*)zExtra;
98994  zExtra += sizeof(i16)*N;
98995  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
98996  pIdx->aSortOrder = (u8*)zExtra;
98997  pIdx->nColumn = N;
98998  pIdx->isResized = 1;
98999  return SQLITE_OK;
99000}
99001
99002/*
99003** Estimate the total row width for a table.
99004*/
99005static void estimateTableWidth(Table *pTab){
99006  unsigned wTable = 0;
99007  const Column *pTabCol;
99008  int i;
99009  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
99010    wTable += pTabCol->szEst;
99011  }
99012  if( pTab->iPKey<0 ) wTable++;
99013  pTab->szTabRow = sqlite3LogEst(wTable*4);
99014}
99015
99016/*
99017** Estimate the average size of a row for an index.
99018*/
99019static void estimateIndexWidth(Index *pIdx){
99020  unsigned wIndex = 0;
99021  int i;
99022  const Column *aCol = pIdx->pTable->aCol;
99023  for(i=0; i<pIdx->nColumn; i++){
99024    i16 x = pIdx->aiColumn[i];
99025    assert( x<pIdx->pTable->nCol );
99026    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
99027  }
99028  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
99029}
99030
99031/* Return true if value x is found any of the first nCol entries of aiCol[]
99032*/
99033static int hasColumn(const i16 *aiCol, int nCol, int x){
99034  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
99035  return 0;
99036}
99037
99038/*
99039** This routine runs at the end of parsing a CREATE TABLE statement that
99040** has a WITHOUT ROWID clause.  The job of this routine is to convert both
99041** internal schema data structures and the generated VDBE code so that they
99042** are appropriate for a WITHOUT ROWID table instead of a rowid table.
99043** Changes include:
99044**
99045**     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
99046**     (2)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
99047**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
99048**          data storage is a covering index btree.
99049**     (3)  Bypass the creation of the sqlite_master table entry
99050**          for the PRIMARY KEY as the primary key index is now
99051**          identified by the sqlite_master table entry of the table itself.
99052**     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
99053**          schema to the rootpage from the main table.
99054**     (5)  Add all table columns to the PRIMARY KEY Index object
99055**          so that the PRIMARY KEY is a covering index.  The surplus
99056**          columns are part of KeyInfo.nXField and are not used for
99057**          sorting or lookup or uniqueness checks.
99058**     (6)  Replace the rowid tail on all automatically generated UNIQUE
99059**          indices with the PRIMARY KEY columns.
99060**
99061** For virtual tables, only (1) is performed.
99062*/
99063static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
99064  Index *pIdx;
99065  Index *pPk;
99066  int nPk;
99067  int i, j;
99068  sqlite3 *db = pParse->db;
99069  Vdbe *v = pParse->pVdbe;
99070
99071  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
99072  */
99073  if( !db->init.imposterTable ){
99074    for(i=0; i<pTab->nCol; i++){
99075      if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
99076        pTab->aCol[i].notNull = OE_Abort;
99077      }
99078    }
99079  }
99080
99081  /* The remaining transformations only apply to b-tree tables, not to
99082  ** virtual tables */
99083  if( IN_DECLARE_VTAB ) return;
99084
99085  /* Convert the OP_CreateTable opcode that would normally create the
99086  ** root-page for the table into an OP_CreateIndex opcode.  The index
99087  ** created will become the PRIMARY KEY index.
99088  */
99089  if( pParse->addrCrTab ){
99090    assert( v );
99091    sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
99092  }
99093
99094  /* Locate the PRIMARY KEY index.  Or, if this table was originally
99095  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
99096  */
99097  if( pTab->iPKey>=0 ){
99098    ExprList *pList;
99099    Token ipkToken;
99100    sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
99101    pList = sqlite3ExprListAppend(pParse, 0,
99102                  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
99103    if( pList==0 ) return;
99104    pList->a[0].sortOrder = pParse->iPkSortOrder;
99105    assert( pParse->pNewTable==pTab );
99106    sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
99107                       SQLITE_IDXTYPE_PRIMARYKEY);
99108    if( db->mallocFailed ) return;
99109    pPk = sqlite3PrimaryKeyIndex(pTab);
99110    pTab->iPKey = -1;
99111  }else{
99112    pPk = sqlite3PrimaryKeyIndex(pTab);
99113
99114    /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
99115    ** table entry. This is only required if currently generating VDBE
99116    ** code for a CREATE TABLE (not when parsing one as part of reading
99117    ** a database schema).  */
99118    if( v ){
99119      assert( db->init.busy==0 );
99120      sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
99121    }
99122
99123    /*
99124    ** Remove all redundant columns from the PRIMARY KEY.  For example, change
99125    ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
99126    ** code assumes the PRIMARY KEY contains no repeated columns.
99127    */
99128    for(i=j=1; i<pPk->nKeyCol; i++){
99129      if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
99130        pPk->nColumn--;
99131      }else{
99132        pPk->aiColumn[j++] = pPk->aiColumn[i];
99133      }
99134    }
99135    pPk->nKeyCol = j;
99136  }
99137  assert( pPk!=0 );
99138  pPk->isCovering = 1;
99139  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
99140  nPk = pPk->nKeyCol;
99141
99142  /* The root page of the PRIMARY KEY is the table root page */
99143  pPk->tnum = pTab->tnum;
99144
99145  /* Update the in-memory representation of all UNIQUE indices by converting
99146  ** the final rowid column into one or more columns of the PRIMARY KEY.
99147  */
99148  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99149    int n;
99150    if( IsPrimaryKeyIndex(pIdx) ) continue;
99151    for(i=n=0; i<nPk; i++){
99152      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
99153    }
99154    if( n==0 ){
99155      /* This index is a superset of the primary key */
99156      pIdx->nColumn = pIdx->nKeyCol;
99157      continue;
99158    }
99159    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
99160    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
99161      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
99162        pIdx->aiColumn[j] = pPk->aiColumn[i];
99163        pIdx->azColl[j] = pPk->azColl[i];
99164        j++;
99165      }
99166    }
99167    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
99168    assert( pIdx->nColumn>=j );
99169  }
99170
99171  /* Add all table columns to the PRIMARY KEY index
99172  */
99173  if( nPk<pTab->nCol ){
99174    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
99175    for(i=0, j=nPk; i<pTab->nCol; i++){
99176      if( !hasColumn(pPk->aiColumn, j, i) ){
99177        assert( j<pPk->nColumn );
99178        pPk->aiColumn[j] = i;
99179        pPk->azColl[j] = sqlite3StrBINARY;
99180        j++;
99181      }
99182    }
99183    assert( pPk->nColumn==j );
99184    assert( pTab->nCol==j );
99185  }else{
99186    pPk->nColumn = pTab->nCol;
99187  }
99188}
99189
99190/*
99191** This routine is called to report the final ")" that terminates
99192** a CREATE TABLE statement.
99193**
99194** The table structure that other action routines have been building
99195** is added to the internal hash tables, assuming no errors have
99196** occurred.
99197**
99198** An entry for the table is made in the master table on disk, unless
99199** this is a temporary table or db->init.busy==1.  When db->init.busy==1
99200** it means we are reading the sqlite_master table because we just
99201** connected to the database or because the sqlite_master table has
99202** recently changed, so the entry for this table already exists in
99203** the sqlite_master table.  We do not want to create it again.
99204**
99205** If the pSelect argument is not NULL, it means that this routine
99206** was called to create a table generated from a
99207** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
99208** the new table will match the result set of the SELECT.
99209*/
99210SQLITE_PRIVATE void sqlite3EndTable(
99211  Parse *pParse,          /* Parse context */
99212  Token *pCons,           /* The ',' token after the last column defn. */
99213  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
99214  u8 tabOpts,             /* Extra table options. Usually 0. */
99215  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
99216){
99217  Table *p;                 /* The new table */
99218  sqlite3 *db = pParse->db; /* The database connection */
99219  int iDb;                  /* Database in which the table lives */
99220  Index *pIdx;              /* An implied index of the table */
99221
99222  if( pEnd==0 && pSelect==0 ){
99223    return;
99224  }
99225  assert( !db->mallocFailed );
99226  p = pParse->pNewTable;
99227  if( p==0 ) return;
99228
99229  assert( !db->init.busy || !pSelect );
99230
99231  /* If the db->init.busy is 1 it means we are reading the SQL off the
99232  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
99233  ** So do not write to the disk again.  Extract the root page number
99234  ** for the table from the db->init.newTnum field.  (The page number
99235  ** should have been put there by the sqliteOpenCb routine.)
99236  **
99237  ** If the root page number is 1, that means this is the sqlite_master
99238  ** table itself.  So mark it read-only.
99239  */
99240  if( db->init.busy ){
99241    p->tnum = db->init.newTnum;
99242    if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
99243  }
99244
99245  /* Special processing for WITHOUT ROWID Tables */
99246  if( tabOpts & TF_WithoutRowid ){
99247    if( (p->tabFlags & TF_Autoincrement) ){
99248      sqlite3ErrorMsg(pParse,
99249          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
99250      return;
99251    }
99252    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
99253      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
99254    }else{
99255      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
99256      convertToWithoutRowidTable(pParse, p);
99257    }
99258  }
99259
99260  iDb = sqlite3SchemaToIndex(db, p->pSchema);
99261
99262#ifndef SQLITE_OMIT_CHECK
99263  /* Resolve names in all CHECK constraint expressions.
99264  */
99265  if( p->pCheck ){
99266    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
99267  }
99268#endif /* !defined(SQLITE_OMIT_CHECK) */
99269
99270  /* Estimate the average row size for the table and for all implied indices */
99271  estimateTableWidth(p);
99272  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
99273    estimateIndexWidth(pIdx);
99274  }
99275
99276  /* If not initializing, then create a record for the new table
99277  ** in the SQLITE_MASTER table of the database.
99278  **
99279  ** If this is a TEMPORARY table, write the entry into the auxiliary
99280  ** file instead of into the main database file.
99281  */
99282  if( !db->init.busy ){
99283    int n;
99284    Vdbe *v;
99285    char *zType;    /* "view" or "table" */
99286    char *zType2;   /* "VIEW" or "TABLE" */
99287    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
99288
99289    v = sqlite3GetVdbe(pParse);
99290    if( NEVER(v==0) ) return;
99291
99292    sqlite3VdbeAddOp1(v, OP_Close, 0);
99293
99294    /*
99295    ** Initialize zType for the new view or table.
99296    */
99297    if( p->pSelect==0 ){
99298      /* A regular table */
99299      zType = "table";
99300      zType2 = "TABLE";
99301#ifndef SQLITE_OMIT_VIEW
99302    }else{
99303      /* A view */
99304      zType = "view";
99305      zType2 = "VIEW";
99306#endif
99307    }
99308
99309    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
99310    ** statement to populate the new table. The root-page number for the
99311    ** new table is in register pParse->regRoot.
99312    **
99313    ** Once the SELECT has been coded by sqlite3Select(), it is in a
99314    ** suitable state to query for the column names and types to be used
99315    ** by the new table.
99316    **
99317    ** A shared-cache write-lock is not required to write to the new table,
99318    ** as a schema-lock must have already been obtained to create it. Since
99319    ** a schema-lock excludes all other database users, the write-lock would
99320    ** be redundant.
99321    */
99322    if( pSelect ){
99323      SelectDest dest;    /* Where the SELECT should store results */
99324      int regYield;       /* Register holding co-routine entry-point */
99325      int addrTop;        /* Top of the co-routine */
99326      int regRec;         /* A record to be insert into the new table */
99327      int regRowid;       /* Rowid of the next row to insert */
99328      int addrInsLoop;    /* Top of the loop for inserting rows */
99329      Table *pSelTab;     /* A table that describes the SELECT results */
99330
99331      regYield = ++pParse->nMem;
99332      regRec = ++pParse->nMem;
99333      regRowid = ++pParse->nMem;
99334      assert(pParse->nTab==1);
99335      sqlite3MayAbort(pParse);
99336      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
99337      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
99338      pParse->nTab = 2;
99339      addrTop = sqlite3VdbeCurrentAddr(v) + 1;
99340      sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
99341      sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
99342      sqlite3Select(pParse, pSelect, &dest);
99343      sqlite3VdbeEndCoroutine(v, regYield);
99344      sqlite3VdbeJumpHere(v, addrTop - 1);
99345      if( pParse->nErr ) return;
99346      pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
99347      if( pSelTab==0 ) return;
99348      assert( p->aCol==0 );
99349      p->nCol = pSelTab->nCol;
99350      p->aCol = pSelTab->aCol;
99351      pSelTab->nCol = 0;
99352      pSelTab->aCol = 0;
99353      sqlite3DeleteTable(db, pSelTab);
99354      addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
99355      VdbeCoverage(v);
99356      sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
99357      sqlite3TableAffinity(v, p, 0);
99358      sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
99359      sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
99360      sqlite3VdbeGoto(v, addrInsLoop);
99361      sqlite3VdbeJumpHere(v, addrInsLoop);
99362      sqlite3VdbeAddOp1(v, OP_Close, 1);
99363    }
99364
99365    /* Compute the complete text of the CREATE statement */
99366    if( pSelect ){
99367      zStmt = createTableStmt(db, p);
99368    }else{
99369      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
99370      n = (int)(pEnd2->z - pParse->sNameToken.z);
99371      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
99372      zStmt = sqlite3MPrintf(db,
99373          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
99374      );
99375    }
99376
99377    /* A slot for the record has already been allocated in the
99378    ** SQLITE_MASTER table.  We just need to update that slot with all
99379    ** the information we've collected.
99380    */
99381    sqlite3NestedParse(pParse,
99382      "UPDATE %Q.%s "
99383         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
99384       "WHERE rowid=#%d",
99385      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
99386      zType,
99387      p->zName,
99388      p->zName,
99389      pParse->regRoot,
99390      zStmt,
99391      pParse->regRowid
99392    );
99393    sqlite3DbFree(db, zStmt);
99394    sqlite3ChangeCookie(pParse, iDb);
99395
99396#ifndef SQLITE_OMIT_AUTOINCREMENT
99397    /* Check to see if we need to create an sqlite_sequence table for
99398    ** keeping track of autoincrement keys.
99399    */
99400    if( p->tabFlags & TF_Autoincrement ){
99401      Db *pDb = &db->aDb[iDb];
99402      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99403      if( pDb->pSchema->pSeqTab==0 ){
99404        sqlite3NestedParse(pParse,
99405          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
99406          pDb->zName
99407        );
99408      }
99409    }
99410#endif
99411
99412    /* Reparse everything to update our internal data structures */
99413    sqlite3VdbeAddParseSchemaOp(v, iDb,
99414           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
99415  }
99416
99417
99418  /* Add the table to the in-memory representation of the database.
99419  */
99420  if( db->init.busy ){
99421    Table *pOld;
99422    Schema *pSchema = p->pSchema;
99423    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99424    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
99425    if( pOld ){
99426      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
99427      sqlite3OomFault(db);
99428      return;
99429    }
99430    pParse->pNewTable = 0;
99431    db->flags |= SQLITE_InternChanges;
99432
99433#ifndef SQLITE_OMIT_ALTERTABLE
99434    if( !p->pSelect ){
99435      const char *zName = (const char *)pParse->sNameToken.z;
99436      int nName;
99437      assert( !pSelect && pCons && pEnd );
99438      if( pCons->z==0 ){
99439        pCons = pEnd;
99440      }
99441      nName = (int)((const char *)pCons->z - zName);
99442      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
99443    }
99444#endif
99445  }
99446}
99447
99448#ifndef SQLITE_OMIT_VIEW
99449/*
99450** The parser calls this routine in order to create a new VIEW
99451*/
99452SQLITE_PRIVATE void sqlite3CreateView(
99453  Parse *pParse,     /* The parsing context */
99454  Token *pBegin,     /* The CREATE token that begins the statement */
99455  Token *pName1,     /* The token that holds the name of the view */
99456  Token *pName2,     /* The token that holds the name of the view */
99457  ExprList *pCNames, /* Optional list of view column names */
99458  Select *pSelect,   /* A SELECT statement that will become the new view */
99459  int isTemp,        /* TRUE for a TEMPORARY view */
99460  int noErr          /* Suppress error messages if VIEW already exists */
99461){
99462  Table *p;
99463  int n;
99464  const char *z;
99465  Token sEnd;
99466  DbFixer sFix;
99467  Token *pName = 0;
99468  int iDb;
99469  sqlite3 *db = pParse->db;
99470
99471  if( pParse->nVar>0 ){
99472    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
99473    goto create_view_fail;
99474  }
99475  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
99476  p = pParse->pNewTable;
99477  if( p==0 || pParse->nErr ) goto create_view_fail;
99478  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99479  iDb = sqlite3SchemaToIndex(db, p->pSchema);
99480  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
99481  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
99482
99483  /* Make a copy of the entire SELECT statement that defines the view.
99484  ** This will force all the Expr.token.z values to be dynamically
99485  ** allocated rather than point to the input string - which means that
99486  ** they will persist after the current sqlite3_exec() call returns.
99487  */
99488  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99489  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
99490  if( db->mallocFailed ) goto create_view_fail;
99491
99492  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
99493  ** the end.
99494  */
99495  sEnd = pParse->sLastToken;
99496  assert( sEnd.z[0]!=0 );
99497  if( sEnd.z[0]!=';' ){
99498    sEnd.z += sEnd.n;
99499  }
99500  sEnd.n = 0;
99501  n = (int)(sEnd.z - pBegin->z);
99502  assert( n>0 );
99503  z = pBegin->z;
99504  while( sqlite3Isspace(z[n-1]) ){ n--; }
99505  sEnd.z = &z[n-1];
99506  sEnd.n = 1;
99507
99508  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
99509  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
99510
99511create_view_fail:
99512  sqlite3SelectDelete(db, pSelect);
99513  sqlite3ExprListDelete(db, pCNames);
99514  return;
99515}
99516#endif /* SQLITE_OMIT_VIEW */
99517
99518#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
99519/*
99520** The Table structure pTable is really a VIEW.  Fill in the names of
99521** the columns of the view in the pTable structure.  Return the number
99522** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
99523*/
99524SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
99525  Table *pSelTab;   /* A fake table from which we get the result set */
99526  Select *pSel;     /* Copy of the SELECT that implements the view */
99527  int nErr = 0;     /* Number of errors encountered */
99528  int n;            /* Temporarily holds the number of cursors assigned */
99529  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
99530  sqlite3_xauth xAuth;       /* Saved xAuth pointer */
99531
99532  assert( pTable );
99533
99534#ifndef SQLITE_OMIT_VIRTUALTABLE
99535  if( sqlite3VtabCallConnect(pParse, pTable) ){
99536    return SQLITE_ERROR;
99537  }
99538  if( IsVirtual(pTable) ) return 0;
99539#endif
99540
99541#ifndef SQLITE_OMIT_VIEW
99542  /* A positive nCol means the columns names for this view are
99543  ** already known.
99544  */
99545  if( pTable->nCol>0 ) return 0;
99546
99547  /* A negative nCol is a special marker meaning that we are currently
99548  ** trying to compute the column names.  If we enter this routine with
99549  ** a negative nCol, it means two or more views form a loop, like this:
99550  **
99551  **     CREATE VIEW one AS SELECT * FROM two;
99552  **     CREATE VIEW two AS SELECT * FROM one;
99553  **
99554  ** Actually, the error above is now caught prior to reaching this point.
99555  ** But the following test is still important as it does come up
99556  ** in the following:
99557  **
99558  **     CREATE TABLE main.ex1(a);
99559  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
99560  **     SELECT * FROM temp.ex1;
99561  */
99562  if( pTable->nCol<0 ){
99563    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
99564    return 1;
99565  }
99566  assert( pTable->nCol>=0 );
99567
99568  /* If we get this far, it means we need to compute the table names.
99569  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
99570  ** "*" elements in the results set of the view and will assign cursors
99571  ** to the elements of the FROM clause.  But we do not want these changes
99572  ** to be permanent.  So the computation is done on a copy of the SELECT
99573  ** statement that defines the view.
99574  */
99575  assert( pTable->pSelect );
99576  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
99577  if( pSel ){
99578    n = pParse->nTab;
99579    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
99580    pTable->nCol = -1;
99581    db->lookaside.bDisable++;
99582#ifndef SQLITE_OMIT_AUTHORIZATION
99583    xAuth = db->xAuth;
99584    db->xAuth = 0;
99585    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
99586    db->xAuth = xAuth;
99587#else
99588    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
99589#endif
99590    pParse->nTab = n;
99591    if( pTable->pCheck ){
99592      /* CREATE VIEW name(arglist) AS ...
99593      ** The names of the columns in the table are taken from
99594      ** arglist which is stored in pTable->pCheck.  The pCheck field
99595      ** normally holds CHECK constraints on an ordinary table, but for
99596      ** a VIEW it holds the list of column names.
99597      */
99598      sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
99599                                 &pTable->nCol, &pTable->aCol);
99600      if( db->mallocFailed==0
99601       && pParse->nErr==0
99602       && pTable->nCol==pSel->pEList->nExpr
99603      ){
99604        sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
99605      }
99606    }else if( pSelTab ){
99607      /* CREATE VIEW name AS...  without an argument list.  Construct
99608      ** the column names from the SELECT statement that defines the view.
99609      */
99610      assert( pTable->aCol==0 );
99611      pTable->nCol = pSelTab->nCol;
99612      pTable->aCol = pSelTab->aCol;
99613      pSelTab->nCol = 0;
99614      pSelTab->aCol = 0;
99615      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
99616    }else{
99617      pTable->nCol = 0;
99618      nErr++;
99619    }
99620    sqlite3DeleteTable(db, pSelTab);
99621    sqlite3SelectDelete(db, pSel);
99622    db->lookaside.bDisable--;
99623  } else {
99624    nErr++;
99625  }
99626  pTable->pSchema->schemaFlags |= DB_UnresetViews;
99627#endif /* SQLITE_OMIT_VIEW */
99628  return nErr;
99629}
99630#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
99631
99632#ifndef SQLITE_OMIT_VIEW
99633/*
99634** Clear the column names from every VIEW in database idx.
99635*/
99636static void sqliteViewResetAll(sqlite3 *db, int idx){
99637  HashElem *i;
99638  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
99639  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
99640  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
99641    Table *pTab = sqliteHashData(i);
99642    if( pTab->pSelect ){
99643      sqlite3DeleteColumnNames(db, pTab);
99644      pTab->aCol = 0;
99645      pTab->nCol = 0;
99646    }
99647  }
99648  DbClearProperty(db, idx, DB_UnresetViews);
99649}
99650#else
99651# define sqliteViewResetAll(A,B)
99652#endif /* SQLITE_OMIT_VIEW */
99653
99654/*
99655** This function is called by the VDBE to adjust the internal schema
99656** used by SQLite when the btree layer moves a table root page. The
99657** root-page of a table or index in database iDb has changed from iFrom
99658** to iTo.
99659**
99660** Ticket #1728:  The symbol table might still contain information
99661** on tables and/or indices that are the process of being deleted.
99662** If you are unlucky, one of those deleted indices or tables might
99663** have the same rootpage number as the real table or index that is
99664** being moved.  So we cannot stop searching after the first match
99665** because the first match might be for one of the deleted indices
99666** or tables and not the table/index that is actually being moved.
99667** We must continue looping until all tables and indices with
99668** rootpage==iFrom have been converted to have a rootpage of iTo
99669** in order to be certain that we got the right one.
99670*/
99671#ifndef SQLITE_OMIT_AUTOVACUUM
99672SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
99673  HashElem *pElem;
99674  Hash *pHash;
99675  Db *pDb;
99676
99677  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99678  pDb = &db->aDb[iDb];
99679  pHash = &pDb->pSchema->tblHash;
99680  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99681    Table *pTab = sqliteHashData(pElem);
99682    if( pTab->tnum==iFrom ){
99683      pTab->tnum = iTo;
99684    }
99685  }
99686  pHash = &pDb->pSchema->idxHash;
99687  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99688    Index *pIdx = sqliteHashData(pElem);
99689    if( pIdx->tnum==iFrom ){
99690      pIdx->tnum = iTo;
99691    }
99692  }
99693}
99694#endif
99695
99696/*
99697** Write code to erase the table with root-page iTable from database iDb.
99698** Also write code to modify the sqlite_master table and internal schema
99699** if a root-page of another table is moved by the btree-layer whilst
99700** erasing iTable (this can happen with an auto-vacuum database).
99701*/
99702static void destroyRootPage(Parse *pParse, int iTable, int iDb){
99703  Vdbe *v = sqlite3GetVdbe(pParse);
99704  int r1 = sqlite3GetTempReg(pParse);
99705  assert( iTable>1 );
99706  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
99707  sqlite3MayAbort(pParse);
99708#ifndef SQLITE_OMIT_AUTOVACUUM
99709  /* OP_Destroy stores an in integer r1. If this integer
99710  ** is non-zero, then it is the root page number of a table moved to
99711  ** location iTable. The following code modifies the sqlite_master table to
99712  ** reflect this.
99713  **
99714  ** The "#NNN" in the SQL is a special constant that means whatever value
99715  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
99716  ** token for additional information.
99717  */
99718  sqlite3NestedParse(pParse,
99719     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
99720     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
99721#endif
99722  sqlite3ReleaseTempReg(pParse, r1);
99723}
99724
99725/*
99726** Write VDBE code to erase table pTab and all associated indices on disk.
99727** Code to update the sqlite_master tables and internal schema definitions
99728** in case a root-page belonging to another table is moved by the btree layer
99729** is also added (this can happen with an auto-vacuum database).
99730*/
99731static void destroyTable(Parse *pParse, Table *pTab){
99732#ifdef SQLITE_OMIT_AUTOVACUUM
99733  Index *pIdx;
99734  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99735  destroyRootPage(pParse, pTab->tnum, iDb);
99736  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99737    destroyRootPage(pParse, pIdx->tnum, iDb);
99738  }
99739#else
99740  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
99741  ** is not defined), then it is important to call OP_Destroy on the
99742  ** table and index root-pages in order, starting with the numerically
99743  ** largest root-page number. This guarantees that none of the root-pages
99744  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
99745  ** following were coded:
99746  **
99747  ** OP_Destroy 4 0
99748  ** ...
99749  ** OP_Destroy 5 0
99750  **
99751  ** and root page 5 happened to be the largest root-page number in the
99752  ** database, then root page 5 would be moved to page 4 by the
99753  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
99754  ** a free-list page.
99755  */
99756  int iTab = pTab->tnum;
99757  int iDestroyed = 0;
99758
99759  while( 1 ){
99760    Index *pIdx;
99761    int iLargest = 0;
99762
99763    if( iDestroyed==0 || iTab<iDestroyed ){
99764      iLargest = iTab;
99765    }
99766    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99767      int iIdx = pIdx->tnum;
99768      assert( pIdx->pSchema==pTab->pSchema );
99769      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
99770        iLargest = iIdx;
99771      }
99772    }
99773    if( iLargest==0 ){
99774      return;
99775    }else{
99776      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99777      assert( iDb>=0 && iDb<pParse->db->nDb );
99778      destroyRootPage(pParse, iLargest, iDb);
99779      iDestroyed = iLargest;
99780    }
99781  }
99782#endif
99783}
99784
99785/*
99786** Remove entries from the sqlite_statN tables (for N in (1,2,3))
99787** after a DROP INDEX or DROP TABLE command.
99788*/
99789static void sqlite3ClearStatTables(
99790  Parse *pParse,         /* The parsing context */
99791  int iDb,               /* The database number */
99792  const char *zType,     /* "idx" or "tbl" */
99793  const char *zName      /* Name of index or table */
99794){
99795  int i;
99796  const char *zDbName = pParse->db->aDb[iDb].zName;
99797  for(i=1; i<=4; i++){
99798    char zTab[24];
99799    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
99800    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
99801      sqlite3NestedParse(pParse,
99802        "DELETE FROM %Q.%s WHERE %s=%Q",
99803        zDbName, zTab, zType, zName
99804      );
99805    }
99806  }
99807}
99808
99809/*
99810** Generate code to drop a table.
99811*/
99812SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
99813  Vdbe *v;
99814  sqlite3 *db = pParse->db;
99815  Trigger *pTrigger;
99816  Db *pDb = &db->aDb[iDb];
99817
99818  v = sqlite3GetVdbe(pParse);
99819  assert( v!=0 );
99820  sqlite3BeginWriteOperation(pParse, 1, iDb);
99821
99822#ifndef SQLITE_OMIT_VIRTUALTABLE
99823  if( IsVirtual(pTab) ){
99824    sqlite3VdbeAddOp0(v, OP_VBegin);
99825  }
99826#endif
99827
99828  /* Drop all triggers associated with the table being dropped. Code
99829  ** is generated to remove entries from sqlite_master and/or
99830  ** sqlite_temp_master if required.
99831  */
99832  pTrigger = sqlite3TriggerList(pParse, pTab);
99833  while( pTrigger ){
99834    assert( pTrigger->pSchema==pTab->pSchema ||
99835        pTrigger->pSchema==db->aDb[1].pSchema );
99836    sqlite3DropTriggerPtr(pParse, pTrigger);
99837    pTrigger = pTrigger->pNext;
99838  }
99839
99840#ifndef SQLITE_OMIT_AUTOINCREMENT
99841  /* Remove any entries of the sqlite_sequence table associated with
99842  ** the table being dropped. This is done before the table is dropped
99843  ** at the btree level, in case the sqlite_sequence table needs to
99844  ** move as a result of the drop (can happen in auto-vacuum mode).
99845  */
99846  if( pTab->tabFlags & TF_Autoincrement ){
99847    sqlite3NestedParse(pParse,
99848      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
99849      pDb->zName, pTab->zName
99850    );
99851  }
99852#endif
99853
99854  /* Drop all SQLITE_MASTER table and index entries that refer to the
99855  ** table. The program name loops through the master table and deletes
99856  ** every row that refers to a table of the same name as the one being
99857  ** dropped. Triggers are handled separately because a trigger can be
99858  ** created in the temp database that refers to a table in another
99859  ** database.
99860  */
99861  sqlite3NestedParse(pParse,
99862      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
99863      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
99864  if( !isView && !IsVirtual(pTab) ){
99865    destroyTable(pParse, pTab);
99866  }
99867
99868  /* Remove the table entry from SQLite's internal schema and modify
99869  ** the schema cookie.
99870  */
99871  if( IsVirtual(pTab) ){
99872    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
99873  }
99874  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
99875  sqlite3ChangeCookie(pParse, iDb);
99876  sqliteViewResetAll(db, iDb);
99877}
99878
99879/*
99880** This routine is called to do the work of a DROP TABLE statement.
99881** pName is the name of the table to be dropped.
99882*/
99883SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
99884  Table *pTab;
99885  Vdbe *v;
99886  sqlite3 *db = pParse->db;
99887  int iDb;
99888
99889  if( db->mallocFailed ){
99890    goto exit_drop_table;
99891  }
99892  assert( pParse->nErr==0 );
99893  assert( pName->nSrc==1 );
99894  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
99895  if( noErr ) db->suppressErr++;
99896  assert( isView==0 || isView==LOCATE_VIEW );
99897  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
99898  if( noErr ) db->suppressErr--;
99899
99900  if( pTab==0 ){
99901    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
99902    goto exit_drop_table;
99903  }
99904  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99905  assert( iDb>=0 && iDb<db->nDb );
99906
99907  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
99908  ** it is initialized.
99909  */
99910  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
99911    goto exit_drop_table;
99912  }
99913#ifndef SQLITE_OMIT_AUTHORIZATION
99914  {
99915    int code;
99916    const char *zTab = SCHEMA_TABLE(iDb);
99917    const char *zDb = db->aDb[iDb].zName;
99918    const char *zArg2 = 0;
99919    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
99920      goto exit_drop_table;
99921    }
99922    if( isView ){
99923      if( !OMIT_TEMPDB && iDb==1 ){
99924        code = SQLITE_DROP_TEMP_VIEW;
99925      }else{
99926        code = SQLITE_DROP_VIEW;
99927      }
99928#ifndef SQLITE_OMIT_VIRTUALTABLE
99929    }else if( IsVirtual(pTab) ){
99930      code = SQLITE_DROP_VTABLE;
99931      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
99932#endif
99933    }else{
99934      if( !OMIT_TEMPDB && iDb==1 ){
99935        code = SQLITE_DROP_TEMP_TABLE;
99936      }else{
99937        code = SQLITE_DROP_TABLE;
99938      }
99939    }
99940    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
99941      goto exit_drop_table;
99942    }
99943    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
99944      goto exit_drop_table;
99945    }
99946  }
99947#endif
99948  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
99949    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
99950    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
99951    goto exit_drop_table;
99952  }
99953
99954#ifndef SQLITE_OMIT_VIEW
99955  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
99956  ** on a table.
99957  */
99958  if( isView && pTab->pSelect==0 ){
99959    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
99960    goto exit_drop_table;
99961  }
99962  if( !isView && pTab->pSelect ){
99963    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
99964    goto exit_drop_table;
99965  }
99966#endif
99967
99968  /* Generate code to remove the table from the master table
99969  ** on disk.
99970  */
99971  v = sqlite3GetVdbe(pParse);
99972  if( v ){
99973    sqlite3BeginWriteOperation(pParse, 1, iDb);
99974    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
99975    sqlite3FkDropTable(pParse, pName, pTab);
99976    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
99977  }
99978
99979exit_drop_table:
99980  sqlite3SrcListDelete(db, pName);
99981}
99982
99983/*
99984** This routine is called to create a new foreign key on the table
99985** currently under construction.  pFromCol determines which columns
99986** in the current table point to the foreign key.  If pFromCol==0 then
99987** connect the key to the last column inserted.  pTo is the name of
99988** the table referred to (a.k.a the "parent" table).  pToCol is a list
99989** of tables in the parent pTo table.  flags contains all
99990** information about the conflict resolution algorithms specified
99991** in the ON DELETE, ON UPDATE and ON INSERT clauses.
99992**
99993** An FKey structure is created and added to the table currently
99994** under construction in the pParse->pNewTable field.
99995**
99996** The foreign key is set for IMMEDIATE processing.  A subsequent call
99997** to sqlite3DeferForeignKey() might change this to DEFERRED.
99998*/
99999SQLITE_PRIVATE void sqlite3CreateForeignKey(
100000  Parse *pParse,       /* Parsing context */
100001  ExprList *pFromCol,  /* Columns in this table that point to other table */
100002  Token *pTo,          /* Name of the other table */
100003  ExprList *pToCol,    /* Columns in the other table */
100004  int flags            /* Conflict resolution algorithms. */
100005){
100006  sqlite3 *db = pParse->db;
100007#ifndef SQLITE_OMIT_FOREIGN_KEY
100008  FKey *pFKey = 0;
100009  FKey *pNextTo;
100010  Table *p = pParse->pNewTable;
100011  int nByte;
100012  int i;
100013  int nCol;
100014  char *z;
100015
100016  assert( pTo!=0 );
100017  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
100018  if( pFromCol==0 ){
100019    int iCol = p->nCol-1;
100020    if( NEVER(iCol<0) ) goto fk_end;
100021    if( pToCol && pToCol->nExpr!=1 ){
100022      sqlite3ErrorMsg(pParse, "foreign key on %s"
100023         " should reference only one column of table %T",
100024         p->aCol[iCol].zName, pTo);
100025      goto fk_end;
100026    }
100027    nCol = 1;
100028  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
100029    sqlite3ErrorMsg(pParse,
100030        "number of columns in foreign key does not match the number of "
100031        "columns in the referenced table");
100032    goto fk_end;
100033  }else{
100034    nCol = pFromCol->nExpr;
100035  }
100036  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
100037  if( pToCol ){
100038    for(i=0; i<pToCol->nExpr; i++){
100039      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
100040    }
100041  }
100042  pFKey = sqlite3DbMallocZero(db, nByte );
100043  if( pFKey==0 ){
100044    goto fk_end;
100045  }
100046  pFKey->pFrom = p;
100047  pFKey->pNextFrom = p->pFKey;
100048  z = (char*)&pFKey->aCol[nCol];
100049  pFKey->zTo = z;
100050  memcpy(z, pTo->z, pTo->n);
100051  z[pTo->n] = 0;
100052  sqlite3Dequote(z);
100053  z += pTo->n+1;
100054  pFKey->nCol = nCol;
100055  if( pFromCol==0 ){
100056    pFKey->aCol[0].iFrom = p->nCol-1;
100057  }else{
100058    for(i=0; i<nCol; i++){
100059      int j;
100060      for(j=0; j<p->nCol; j++){
100061        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
100062          pFKey->aCol[i].iFrom = j;
100063          break;
100064        }
100065      }
100066      if( j>=p->nCol ){
100067        sqlite3ErrorMsg(pParse,
100068          "unknown column \"%s\" in foreign key definition",
100069          pFromCol->a[i].zName);
100070        goto fk_end;
100071      }
100072    }
100073  }
100074  if( pToCol ){
100075    for(i=0; i<nCol; i++){
100076      int n = sqlite3Strlen30(pToCol->a[i].zName);
100077      pFKey->aCol[i].zCol = z;
100078      memcpy(z, pToCol->a[i].zName, n);
100079      z[n] = 0;
100080      z += n+1;
100081    }
100082  }
100083  pFKey->isDeferred = 0;
100084  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
100085  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
100086
100087  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
100088  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
100089      pFKey->zTo, (void *)pFKey
100090  );
100091  if( pNextTo==pFKey ){
100092    sqlite3OomFault(db);
100093    goto fk_end;
100094  }
100095  if( pNextTo ){
100096    assert( pNextTo->pPrevTo==0 );
100097    pFKey->pNextTo = pNextTo;
100098    pNextTo->pPrevTo = pFKey;
100099  }
100100
100101  /* Link the foreign key to the table as the last step.
100102  */
100103  p->pFKey = pFKey;
100104  pFKey = 0;
100105
100106fk_end:
100107  sqlite3DbFree(db, pFKey);
100108#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
100109  sqlite3ExprListDelete(db, pFromCol);
100110  sqlite3ExprListDelete(db, pToCol);
100111}
100112
100113/*
100114** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
100115** clause is seen as part of a foreign key definition.  The isDeferred
100116** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
100117** The behavior of the most recently created foreign key is adjusted
100118** accordingly.
100119*/
100120SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
100121#ifndef SQLITE_OMIT_FOREIGN_KEY
100122  Table *pTab;
100123  FKey *pFKey;
100124  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
100125  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
100126  pFKey->isDeferred = (u8)isDeferred;
100127#endif
100128}
100129
100130/*
100131** Generate code that will erase and refill index *pIdx.  This is
100132** used to initialize a newly created index or to recompute the
100133** content of an index in response to a REINDEX command.
100134**
100135** if memRootPage is not negative, it means that the index is newly
100136** created.  The register specified by memRootPage contains the
100137** root page number of the index.  If memRootPage is negative, then
100138** the index already exists and must be cleared before being refilled and
100139** the root page number of the index is taken from pIndex->tnum.
100140*/
100141static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
100142  Table *pTab = pIndex->pTable;  /* The table that is indexed */
100143  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
100144  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
100145  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
100146  int addr1;                     /* Address of top of loop */
100147  int addr2;                     /* Address to jump to for next iteration */
100148  int tnum;                      /* Root page of index */
100149  int iPartIdxLabel;             /* Jump to this label to skip a row */
100150  Vdbe *v;                       /* Generate code into this virtual machine */
100151  KeyInfo *pKey;                 /* KeyInfo for index */
100152  int regRecord;                 /* Register holding assembled index record */
100153  sqlite3 *db = pParse->db;      /* The database connection */
100154  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100155
100156#ifndef SQLITE_OMIT_AUTHORIZATION
100157  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
100158      db->aDb[iDb].zName ) ){
100159    return;
100160  }
100161#endif
100162
100163  /* Require a write-lock on the table to perform this operation */
100164  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
100165
100166  v = sqlite3GetVdbe(pParse);
100167  if( v==0 ) return;
100168  if( memRootPage>=0 ){
100169    tnum = memRootPage;
100170  }else{
100171    tnum = pIndex->tnum;
100172  }
100173  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
100174  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
100175
100176  /* Open the sorter cursor if we are to use one. */
100177  iSorter = pParse->nTab++;
100178  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
100179                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
100180
100181  /* Open the table. Loop through all rows of the table, inserting index
100182  ** records into the sorter. */
100183  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
100184  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
100185  regRecord = sqlite3GetTempReg(pParse);
100186
100187  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
100188  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
100189  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
100190  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
100191  sqlite3VdbeJumpHere(v, addr1);
100192  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
100193  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
100194                    (char *)pKey, P4_KEYINFO);
100195  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
100196
100197  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
100198  if( IsUniqueIndex(pIndex) ){
100199    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
100200    sqlite3VdbeGoto(v, j2);
100201    addr2 = sqlite3VdbeCurrentAddr(v);
100202    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
100203                         pIndex->nKeyCol); VdbeCoverage(v);
100204    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
100205  }else{
100206    addr2 = sqlite3VdbeCurrentAddr(v);
100207  }
100208  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
100209  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
100210  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
100211  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
100212  sqlite3ReleaseTempReg(pParse, regRecord);
100213  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
100214  sqlite3VdbeJumpHere(v, addr1);
100215
100216  sqlite3VdbeAddOp1(v, OP_Close, iTab);
100217  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
100218  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
100219}
100220
100221/*
100222** Allocate heap space to hold an Index object with nCol columns.
100223**
100224** Increase the allocation size to provide an extra nExtra bytes
100225** of 8-byte aligned space after the Index object and return a
100226** pointer to this extra space in *ppExtra.
100227*/
100228SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
100229  sqlite3 *db,         /* Database connection */
100230  i16 nCol,            /* Total number of columns in the index */
100231  int nExtra,          /* Number of bytes of extra space to alloc */
100232  char **ppExtra       /* Pointer to the "extra" space */
100233){
100234  Index *p;            /* Allocated index object */
100235  int nByte;           /* Bytes of space for Index object + arrays */
100236
100237  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
100238          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
100239          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
100240                 sizeof(i16)*nCol +            /* Index.aiColumn   */
100241                 sizeof(u8)*nCol);             /* Index.aSortOrder */
100242  p = sqlite3DbMallocZero(db, nByte + nExtra);
100243  if( p ){
100244    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
100245    p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
100246    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
100247    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
100248    p->aSortOrder = (u8*)pExtra;
100249    p->nColumn = nCol;
100250    p->nKeyCol = nCol - 1;
100251    *ppExtra = ((char*)p) + nByte;
100252  }
100253  return p;
100254}
100255
100256/*
100257** Create a new index for an SQL table.  pName1.pName2 is the name of the index
100258** and pTblList is the name of the table that is to be indexed.  Both will
100259** be NULL for a primary key or an index that is created to satisfy a
100260** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
100261** as the table to be indexed.  pParse->pNewTable is a table that is
100262** currently being constructed by a CREATE TABLE statement.
100263**
100264** pList is a list of columns to be indexed.  pList will be NULL if this
100265** is a primary key or unique-constraint on the most recent column added
100266** to the table currently under construction.
100267*/
100268SQLITE_PRIVATE void sqlite3CreateIndex(
100269  Parse *pParse,     /* All information about this parse */
100270  Token *pName1,     /* First part of index name. May be NULL */
100271  Token *pName2,     /* Second part of index name. May be NULL */
100272  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
100273  ExprList *pList,   /* A list of columns to be indexed */
100274  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
100275  Token *pStart,     /* The CREATE token that begins this statement */
100276  Expr *pPIWhere,    /* WHERE clause for partial indices */
100277  int sortOrder,     /* Sort order of primary key when pList==NULL */
100278  int ifNotExist,    /* Omit error if index already exists */
100279  u8 idxType         /* The index type */
100280){
100281  Table *pTab = 0;     /* Table to be indexed */
100282  Index *pIndex = 0;   /* The index to be created */
100283  char *zName = 0;     /* Name of the index */
100284  int nName;           /* Number of characters in zName */
100285  int i, j;
100286  DbFixer sFix;        /* For assigning database names to pTable */
100287  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
100288  sqlite3 *db = pParse->db;
100289  Db *pDb;             /* The specific table containing the indexed database */
100290  int iDb;             /* Index of the database that is being written */
100291  Token *pName = 0;    /* Unqualified name of the index to create */
100292  struct ExprList_item *pListItem; /* For looping over pList */
100293  int nExtra = 0;                  /* Space allocated for zExtra[] */
100294  int nExtraCol;                   /* Number of extra columns needed */
100295  char *zExtra = 0;                /* Extra space after the Index object */
100296  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
100297
100298  if( db->mallocFailed || pParse->nErr>0 ){
100299    goto exit_create_index;
100300  }
100301  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
100302    goto exit_create_index;
100303  }
100304  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100305    goto exit_create_index;
100306  }
100307
100308  /*
100309  ** Find the table that is to be indexed.  Return early if not found.
100310  */
100311  if( pTblName!=0 ){
100312
100313    /* Use the two-part index name to determine the database
100314    ** to search for the table. 'Fix' the table name to this db
100315    ** before looking up the table.
100316    */
100317    assert( pName1 && pName2 );
100318    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100319    if( iDb<0 ) goto exit_create_index;
100320    assert( pName && pName->z );
100321
100322#ifndef SQLITE_OMIT_TEMPDB
100323    /* If the index name was unqualified, check if the table
100324    ** is a temp table. If so, set the database to 1. Do not do this
100325    ** if initialising a database schema.
100326    */
100327    if( !db->init.busy ){
100328      pTab = sqlite3SrcListLookup(pParse, pTblName);
100329      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
100330        iDb = 1;
100331      }
100332    }
100333#endif
100334
100335    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
100336    if( sqlite3FixSrcList(&sFix, pTblName) ){
100337      /* Because the parser constructs pTblName from a single identifier,
100338      ** sqlite3FixSrcList can never fail. */
100339      assert(0);
100340    }
100341    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
100342    assert( db->mallocFailed==0 || pTab==0 );
100343    if( pTab==0 ) goto exit_create_index;
100344    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
100345      sqlite3ErrorMsg(pParse,
100346           "cannot create a TEMP index on non-TEMP table \"%s\"",
100347           pTab->zName);
100348      goto exit_create_index;
100349    }
100350    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
100351  }else{
100352    assert( pName==0 );
100353    assert( pStart==0 );
100354    pTab = pParse->pNewTable;
100355    if( !pTab ) goto exit_create_index;
100356    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100357  }
100358  pDb = &db->aDb[iDb];
100359
100360  assert( pTab!=0 );
100361  assert( pParse->nErr==0 );
100362  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
100363       && db->init.busy==0
100364#if SQLITE_USER_AUTHENTICATION
100365       && sqlite3UserAuthTable(pTab->zName)==0
100366#endif
100367       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
100368    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
100369    goto exit_create_index;
100370  }
100371#ifndef SQLITE_OMIT_VIEW
100372  if( pTab->pSelect ){
100373    sqlite3ErrorMsg(pParse, "views may not be indexed");
100374    goto exit_create_index;
100375  }
100376#endif
100377#ifndef SQLITE_OMIT_VIRTUALTABLE
100378  if( IsVirtual(pTab) ){
100379    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
100380    goto exit_create_index;
100381  }
100382#endif
100383
100384  /*
100385  ** Find the name of the index.  Make sure there is not already another
100386  ** index or table with the same name.
100387  **
100388  ** Exception:  If we are reading the names of permanent indices from the
100389  ** sqlite_master table (because some other process changed the schema) and
100390  ** one of the index names collides with the name of a temporary table or
100391  ** index, then we will continue to process this index.
100392  **
100393  ** If pName==0 it means that we are
100394  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
100395  ** own name.
100396  */
100397  if( pName ){
100398    zName = sqlite3NameFromToken(db, pName);
100399    if( zName==0 ) goto exit_create_index;
100400    assert( pName->z!=0 );
100401    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
100402      goto exit_create_index;
100403    }
100404    if( !db->init.busy ){
100405      if( sqlite3FindTable(db, zName, 0)!=0 ){
100406        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
100407        goto exit_create_index;
100408      }
100409    }
100410    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
100411      if( !ifNotExist ){
100412        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
100413      }else{
100414        assert( !db->init.busy );
100415        sqlite3CodeVerifySchema(pParse, iDb);
100416      }
100417      goto exit_create_index;
100418    }
100419  }else{
100420    int n;
100421    Index *pLoop;
100422    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
100423    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
100424    if( zName==0 ){
100425      goto exit_create_index;
100426    }
100427
100428    /* Automatic index names generated from within sqlite3_declare_vtab()
100429    ** must have names that are distinct from normal automatic index names.
100430    ** The following statement converts "sqlite3_autoindex..." into
100431    ** "sqlite3_butoindex..." in order to make the names distinct.
100432    ** The "vtab_err.test" test demonstrates the need of this statement. */
100433    if( IN_DECLARE_VTAB ) zName[7]++;
100434  }
100435
100436  /* Check for authorization to create an index.
100437  */
100438#ifndef SQLITE_OMIT_AUTHORIZATION
100439  {
100440    const char *zDb = pDb->zName;
100441    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
100442      goto exit_create_index;
100443    }
100444    i = SQLITE_CREATE_INDEX;
100445    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
100446    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
100447      goto exit_create_index;
100448    }
100449  }
100450#endif
100451
100452  /* If pList==0, it means this routine was called to make a primary
100453  ** key out of the last column added to the table under construction.
100454  ** So create a fake list to simulate this.
100455  */
100456  if( pList==0 ){
100457    Token prevCol;
100458    sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
100459    pList = sqlite3ExprListAppend(pParse, 0,
100460              sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
100461    if( pList==0 ) goto exit_create_index;
100462    assert( pList->nExpr==1 );
100463    sqlite3ExprListSetSortOrder(pList, sortOrder);
100464  }else{
100465    sqlite3ExprListCheckLength(pParse, pList, "index");
100466  }
100467
100468  /* Figure out how many bytes of space are required to store explicitly
100469  ** specified collation sequence names.
100470  */
100471  for(i=0; i<pList->nExpr; i++){
100472    Expr *pExpr = pList->a[i].pExpr;
100473    assert( pExpr!=0 );
100474    if( pExpr->op==TK_COLLATE ){
100475      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
100476    }
100477  }
100478
100479  /*
100480  ** Allocate the index structure.
100481  */
100482  nName = sqlite3Strlen30(zName);
100483  nExtraCol = pPk ? pPk->nKeyCol : 1;
100484  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
100485                                      nName + nExtra + 1, &zExtra);
100486  if( db->mallocFailed ){
100487    goto exit_create_index;
100488  }
100489  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
100490  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
100491  pIndex->zName = zExtra;
100492  zExtra += nName + 1;
100493  memcpy(pIndex->zName, zName, nName+1);
100494  pIndex->pTable = pTab;
100495  pIndex->onError = (u8)onError;
100496  pIndex->uniqNotNull = onError!=OE_None;
100497  pIndex->idxType = idxType;
100498  pIndex->pSchema = db->aDb[iDb].pSchema;
100499  pIndex->nKeyCol = pList->nExpr;
100500  if( pPIWhere ){
100501    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
100502    pIndex->pPartIdxWhere = pPIWhere;
100503    pPIWhere = 0;
100504  }
100505  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100506
100507  /* Check to see if we should honor DESC requests on index columns
100508  */
100509  if( pDb->pSchema->file_format>=4 ){
100510    sortOrderMask = -1;   /* Honor DESC */
100511  }else{
100512    sortOrderMask = 0;    /* Ignore DESC */
100513  }
100514
100515  /* Analyze the list of expressions that form the terms of the index and
100516  ** report any errors.  In the common case where the expression is exactly
100517  ** a table column, store that column in aiColumn[].  For general expressions,
100518  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
100519  **
100520  ** TODO: Issue a warning if two or more columns of the index are identical.
100521  ** TODO: Issue a warning if the table primary key is used as part of the
100522  ** index key.
100523  */
100524  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
100525    Expr *pCExpr;                  /* The i-th index expression */
100526    int requestedSortOrder;        /* ASC or DESC on the i-th expression */
100527    const char *zColl;             /* Collation sequence name */
100528
100529    sqlite3StringToId(pListItem->pExpr);
100530    sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
100531    if( pParse->nErr ) goto exit_create_index;
100532    pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
100533    if( pCExpr->op!=TK_COLUMN ){
100534      if( pTab==pParse->pNewTable ){
100535        sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
100536                                "UNIQUE constraints");
100537        goto exit_create_index;
100538      }
100539      if( pIndex->aColExpr==0 ){
100540        ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
100541        pIndex->aColExpr = pCopy;
100542        if( !db->mallocFailed ){
100543          assert( pCopy!=0 );
100544          pListItem = &pCopy->a[i];
100545        }
100546      }
100547      j = XN_EXPR;
100548      pIndex->aiColumn[i] = XN_EXPR;
100549      pIndex->uniqNotNull = 0;
100550    }else{
100551      j = pCExpr->iColumn;
100552      assert( j<=0x7fff );
100553      if( j<0 ){
100554        j = pTab->iPKey;
100555      }else if( pTab->aCol[j].notNull==0 ){
100556        pIndex->uniqNotNull = 0;
100557      }
100558      pIndex->aiColumn[i] = (i16)j;
100559    }
100560    zColl = 0;
100561    if( pListItem->pExpr->op==TK_COLLATE ){
100562      int nColl;
100563      zColl = pListItem->pExpr->u.zToken;
100564      nColl = sqlite3Strlen30(zColl) + 1;
100565      assert( nExtra>=nColl );
100566      memcpy(zExtra, zColl, nColl);
100567      zColl = zExtra;
100568      zExtra += nColl;
100569      nExtra -= nColl;
100570    }else if( j>=0 ){
100571      zColl = pTab->aCol[j].zColl;
100572    }
100573    if( !zColl ) zColl = sqlite3StrBINARY;
100574    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
100575      goto exit_create_index;
100576    }
100577    pIndex->azColl[i] = zColl;
100578    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
100579    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
100580  }
100581
100582  /* Append the table key to the end of the index.  For WITHOUT ROWID
100583  ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
100584  ** normal tables (when pPk==0) this will be the rowid.
100585  */
100586  if( pPk ){
100587    for(j=0; j<pPk->nKeyCol; j++){
100588      int x = pPk->aiColumn[j];
100589      assert( x>=0 );
100590      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
100591        pIndex->nColumn--;
100592      }else{
100593        pIndex->aiColumn[i] = x;
100594        pIndex->azColl[i] = pPk->azColl[j];
100595        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
100596        i++;
100597      }
100598    }
100599    assert( i==pIndex->nColumn );
100600  }else{
100601    pIndex->aiColumn[i] = XN_ROWID;
100602    pIndex->azColl[i] = sqlite3StrBINARY;
100603  }
100604  sqlite3DefaultRowEst(pIndex);
100605  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
100606
100607  /* If this index contains every column of its table, then mark
100608  ** it as a covering index */
100609  assert( HasRowid(pTab)
100610      || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
100611  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
100612    pIndex->isCovering = 1;
100613    for(j=0; j<pTab->nCol; j++){
100614      if( j==pTab->iPKey ) continue;
100615      if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
100616      pIndex->isCovering = 0;
100617      break;
100618    }
100619  }
100620
100621  if( pTab==pParse->pNewTable ){
100622    /* This routine has been called to create an automatic index as a
100623    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
100624    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
100625    ** i.e. one of:
100626    **
100627    ** CREATE TABLE t(x PRIMARY KEY, y);
100628    ** CREATE TABLE t(x, y, UNIQUE(x, y));
100629    **
100630    ** Either way, check to see if the table already has such an index. If
100631    ** so, don't bother creating this one. This only applies to
100632    ** automatically created indices. Users can do as they wish with
100633    ** explicit indices.
100634    **
100635    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
100636    ** (and thus suppressing the second one) even if they have different
100637    ** sort orders.
100638    **
100639    ** If there are different collating sequences or if the columns of
100640    ** the constraint occur in different orders, then the constraints are
100641    ** considered distinct and both result in separate indices.
100642    */
100643    Index *pIdx;
100644    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100645      int k;
100646      assert( IsUniqueIndex(pIdx) );
100647      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
100648      assert( IsUniqueIndex(pIndex) );
100649
100650      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
100651      for(k=0; k<pIdx->nKeyCol; k++){
100652        const char *z1;
100653        const char *z2;
100654        assert( pIdx->aiColumn[k]>=0 );
100655        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
100656        z1 = pIdx->azColl[k];
100657        z2 = pIndex->azColl[k];
100658        if( sqlite3StrICmp(z1, z2) ) break;
100659      }
100660      if( k==pIdx->nKeyCol ){
100661        if( pIdx->onError!=pIndex->onError ){
100662          /* This constraint creates the same index as a previous
100663          ** constraint specified somewhere in the CREATE TABLE statement.
100664          ** However the ON CONFLICT clauses are different. If both this
100665          ** constraint and the previous equivalent constraint have explicit
100666          ** ON CONFLICT clauses this is an error. Otherwise, use the
100667          ** explicitly specified behavior for the index.
100668          */
100669          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
100670            sqlite3ErrorMsg(pParse,
100671                "conflicting ON CONFLICT clauses specified", 0);
100672          }
100673          if( pIdx->onError==OE_Default ){
100674            pIdx->onError = pIndex->onError;
100675          }
100676        }
100677        if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
100678        goto exit_create_index;
100679      }
100680    }
100681  }
100682
100683  /* Link the new Index structure to its table and to the other
100684  ** in-memory database structures.
100685  */
100686  assert( pParse->nErr==0 );
100687  if( db->init.busy ){
100688    Index *p;
100689    assert( !IN_DECLARE_VTAB );
100690    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
100691    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
100692                          pIndex->zName, pIndex);
100693    if( p ){
100694      assert( p==pIndex );  /* Malloc must have failed */
100695      sqlite3OomFault(db);
100696      goto exit_create_index;
100697    }
100698    db->flags |= SQLITE_InternChanges;
100699    if( pTblName!=0 ){
100700      pIndex->tnum = db->init.newTnum;
100701    }
100702  }
100703
100704  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
100705  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
100706  ** emit code to allocate the index rootpage on disk and make an entry for
100707  ** the index in the sqlite_master table and populate the index with
100708  ** content.  But, do not do this if we are simply reading the sqlite_master
100709  ** table to parse the schema, or if this index is the PRIMARY KEY index
100710  ** of a WITHOUT ROWID table.
100711  **
100712  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
100713  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
100714  ** has just been created, it contains no data and the index initialization
100715  ** step can be skipped.
100716  */
100717  else if( HasRowid(pTab) || pTblName!=0 ){
100718    Vdbe *v;
100719    char *zStmt;
100720    int iMem = ++pParse->nMem;
100721
100722    v = sqlite3GetVdbe(pParse);
100723    if( v==0 ) goto exit_create_index;
100724
100725    sqlite3BeginWriteOperation(pParse, 1, iDb);
100726
100727    /* Create the rootpage for the index using CreateIndex. But before
100728    ** doing so, code a Noop instruction and store its address in
100729    ** Index.tnum. This is required in case this index is actually a
100730    ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
100731    ** that case the convertToWithoutRowidTable() routine will replace
100732    ** the Noop with a Goto to jump over the VDBE code generated below. */
100733    pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
100734    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
100735
100736    /* Gather the complete text of the CREATE INDEX statement into
100737    ** the zStmt variable
100738    */
100739    if( pStart ){
100740      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
100741      if( pName->z[n-1]==';' ) n--;
100742      /* A named index with an explicit CREATE INDEX statement */
100743      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
100744        onError==OE_None ? "" : " UNIQUE", n, pName->z);
100745    }else{
100746      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
100747      /* zStmt = sqlite3MPrintf(""); */
100748      zStmt = 0;
100749    }
100750
100751    /* Add an entry in sqlite_master for this index
100752    */
100753    sqlite3NestedParse(pParse,
100754        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
100755        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
100756        pIndex->zName,
100757        pTab->zName,
100758        iMem,
100759        zStmt
100760    );
100761    sqlite3DbFree(db, zStmt);
100762
100763    /* Fill the index with data and reparse the schema. Code an OP_Expire
100764    ** to invalidate all pre-compiled statements.
100765    */
100766    if( pTblName ){
100767      sqlite3RefillIndex(pParse, pIndex, iMem);
100768      sqlite3ChangeCookie(pParse, iDb);
100769      sqlite3VdbeAddParseSchemaOp(v, iDb,
100770         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
100771      sqlite3VdbeAddOp0(v, OP_Expire);
100772    }
100773
100774    sqlite3VdbeJumpHere(v, pIndex->tnum);
100775  }
100776
100777  /* When adding an index to the list of indices for a table, make
100778  ** sure all indices labeled OE_Replace come after all those labeled
100779  ** OE_Ignore.  This is necessary for the correct constraint check
100780  ** processing (in sqlite3GenerateConstraintChecks()) as part of
100781  ** UPDATE and INSERT statements.
100782  */
100783  if( db->init.busy || pTblName==0 ){
100784    if( onError!=OE_Replace || pTab->pIndex==0
100785         || pTab->pIndex->onError==OE_Replace){
100786      pIndex->pNext = pTab->pIndex;
100787      pTab->pIndex = pIndex;
100788    }else{
100789      Index *pOther = pTab->pIndex;
100790      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
100791        pOther = pOther->pNext;
100792      }
100793      pIndex->pNext = pOther->pNext;
100794      pOther->pNext = pIndex;
100795    }
100796    pIndex = 0;
100797  }
100798
100799  /* Clean up before exiting */
100800exit_create_index:
100801  if( pIndex ) freeIndex(db, pIndex);
100802  sqlite3ExprDelete(db, pPIWhere);
100803  sqlite3ExprListDelete(db, pList);
100804  sqlite3SrcListDelete(db, pTblName);
100805  sqlite3DbFree(db, zName);
100806}
100807
100808/*
100809** Fill the Index.aiRowEst[] array with default information - information
100810** to be used when we have not run the ANALYZE command.
100811**
100812** aiRowEst[0] is supposed to contain the number of elements in the index.
100813** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
100814** number of rows in the table that match any particular value of the
100815** first column of the index.  aiRowEst[2] is an estimate of the number
100816** of rows that match any particular combination of the first 2 columns
100817** of the index.  And so forth.  It must always be the case that
100818*
100819**           aiRowEst[N]<=aiRowEst[N-1]
100820**           aiRowEst[N]>=1
100821**
100822** Apart from that, we have little to go on besides intuition as to
100823** how aiRowEst[] should be initialized.  The numbers generated here
100824** are based on typical values found in actual indices.
100825*/
100826SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
100827  /*                10,  9,  8,  7,  6 */
100828  LogEst aVal[] = { 33, 32, 30, 28, 26 };
100829  LogEst *a = pIdx->aiRowLogEst;
100830  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
100831  int i;
100832
100833  /* Set the first entry (number of rows in the index) to the estimated
100834  ** number of rows in the table, or half the number of rows in the table
100835  ** for a partial index.   But do not let the estimate drop below 10. */
100836  a[0] = pIdx->pTable->nRowLogEst;
100837  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
100838  if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
100839
100840  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
100841  ** 6 and each subsequent value (if any) is 5.  */
100842  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
100843  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
100844    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
100845  }
100846
100847  assert( 0==sqlite3LogEst(1) );
100848  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
100849}
100850
100851/*
100852** This routine will drop an existing named index.  This routine
100853** implements the DROP INDEX statement.
100854*/
100855SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
100856  Index *pIndex;
100857  Vdbe *v;
100858  sqlite3 *db = pParse->db;
100859  int iDb;
100860
100861  assert( pParse->nErr==0 );   /* Never called with prior errors */
100862  if( db->mallocFailed ){
100863    goto exit_drop_index;
100864  }
100865  assert( pName->nSrc==1 );
100866  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100867    goto exit_drop_index;
100868  }
100869  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
100870  if( pIndex==0 ){
100871    if( !ifExists ){
100872      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
100873    }else{
100874      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
100875    }
100876    pParse->checkSchema = 1;
100877    goto exit_drop_index;
100878  }
100879  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
100880    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
100881      "or PRIMARY KEY constraint cannot be dropped", 0);
100882    goto exit_drop_index;
100883  }
100884  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100885#ifndef SQLITE_OMIT_AUTHORIZATION
100886  {
100887    int code = SQLITE_DROP_INDEX;
100888    Table *pTab = pIndex->pTable;
100889    const char *zDb = db->aDb[iDb].zName;
100890    const char *zTab = SCHEMA_TABLE(iDb);
100891    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100892      goto exit_drop_index;
100893    }
100894    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
100895    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
100896      goto exit_drop_index;
100897    }
100898  }
100899#endif
100900
100901  /* Generate code to remove the index and from the master table */
100902  v = sqlite3GetVdbe(pParse);
100903  if( v ){
100904    sqlite3BeginWriteOperation(pParse, 1, iDb);
100905    sqlite3NestedParse(pParse,
100906       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
100907       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
100908    );
100909    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
100910    sqlite3ChangeCookie(pParse, iDb);
100911    destroyRootPage(pParse, pIndex->tnum, iDb);
100912    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
100913  }
100914
100915exit_drop_index:
100916  sqlite3SrcListDelete(db, pName);
100917}
100918
100919/*
100920** pArray is a pointer to an array of objects. Each object in the
100921** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
100922** to extend the array so that there is space for a new object at the end.
100923**
100924** When this function is called, *pnEntry contains the current size of
100925** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
100926** in total).
100927**
100928** If the realloc() is successful (i.e. if no OOM condition occurs), the
100929** space allocated for the new object is zeroed, *pnEntry updated to
100930** reflect the new size of the array and a pointer to the new allocation
100931** returned. *pIdx is set to the index of the new array entry in this case.
100932**
100933** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
100934** unchanged and a copy of pArray returned.
100935*/
100936SQLITE_PRIVATE void *sqlite3ArrayAllocate(
100937  sqlite3 *db,      /* Connection to notify of malloc failures */
100938  void *pArray,     /* Array of objects.  Might be reallocated */
100939  int szEntry,      /* Size of each object in the array */
100940  int *pnEntry,     /* Number of objects currently in use */
100941  int *pIdx         /* Write the index of a new slot here */
100942){
100943  char *z;
100944  int n = *pnEntry;
100945  if( (n & (n-1))==0 ){
100946    int sz = (n==0) ? 1 : 2*n;
100947    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
100948    if( pNew==0 ){
100949      *pIdx = -1;
100950      return pArray;
100951    }
100952    pArray = pNew;
100953  }
100954  z = (char*)pArray;
100955  memset(&z[n * szEntry], 0, szEntry);
100956  *pIdx = n;
100957  ++*pnEntry;
100958  return pArray;
100959}
100960
100961/*
100962** Append a new element to the given IdList.  Create a new IdList if
100963** need be.
100964**
100965** A new IdList is returned, or NULL if malloc() fails.
100966*/
100967SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
100968  int i;
100969  if( pList==0 ){
100970    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
100971    if( pList==0 ) return 0;
100972  }
100973  pList->a = sqlite3ArrayAllocate(
100974      db,
100975      pList->a,
100976      sizeof(pList->a[0]),
100977      &pList->nId,
100978      &i
100979  );
100980  if( i<0 ){
100981    sqlite3IdListDelete(db, pList);
100982    return 0;
100983  }
100984  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
100985  return pList;
100986}
100987
100988/*
100989** Delete an IdList.
100990*/
100991SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
100992  int i;
100993  if( pList==0 ) return;
100994  for(i=0; i<pList->nId; i++){
100995    sqlite3DbFree(db, pList->a[i].zName);
100996  }
100997  sqlite3DbFree(db, pList->a);
100998  sqlite3DbFree(db, pList);
100999}
101000
101001/*
101002** Return the index in pList of the identifier named zId.  Return -1
101003** if not found.
101004*/
101005SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
101006  int i;
101007  if( pList==0 ) return -1;
101008  for(i=0; i<pList->nId; i++){
101009    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
101010  }
101011  return -1;
101012}
101013
101014/*
101015** Expand the space allocated for the given SrcList object by
101016** creating nExtra new slots beginning at iStart.  iStart is zero based.
101017** New slots are zeroed.
101018**
101019** For example, suppose a SrcList initially contains two entries: A,B.
101020** To append 3 new entries onto the end, do this:
101021**
101022**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
101023**
101024** After the call above it would contain:  A, B, nil, nil, nil.
101025** If the iStart argument had been 1 instead of 2, then the result
101026** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
101027** the iStart value would be 0.  The result then would
101028** be: nil, nil, nil, A, B.
101029**
101030** If a memory allocation fails the SrcList is unchanged.  The
101031** db->mallocFailed flag will be set to true.
101032*/
101033SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
101034  sqlite3 *db,       /* Database connection to notify of OOM errors */
101035  SrcList *pSrc,     /* The SrcList to be enlarged */
101036  int nExtra,        /* Number of new slots to add to pSrc->a[] */
101037  int iStart         /* Index in pSrc->a[] of first new slot */
101038){
101039  int i;
101040
101041  /* Sanity checking on calling parameters */
101042  assert( iStart>=0 );
101043  assert( nExtra>=1 );
101044  assert( pSrc!=0 );
101045  assert( iStart<=pSrc->nSrc );
101046
101047  /* Allocate additional space if needed */
101048  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
101049    SrcList *pNew;
101050    int nAlloc = pSrc->nSrc+nExtra;
101051    int nGot;
101052    pNew = sqlite3DbRealloc(db, pSrc,
101053               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
101054    if( pNew==0 ){
101055      assert( db->mallocFailed );
101056      return pSrc;
101057    }
101058    pSrc = pNew;
101059    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
101060    pSrc->nAlloc = nGot;
101061  }
101062
101063  /* Move existing slots that come after the newly inserted slots
101064  ** out of the way */
101065  for(i=pSrc->nSrc-1; i>=iStart; i--){
101066    pSrc->a[i+nExtra] = pSrc->a[i];
101067  }
101068  pSrc->nSrc += nExtra;
101069
101070  /* Zero the newly allocated slots */
101071  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
101072  for(i=iStart; i<iStart+nExtra; i++){
101073    pSrc->a[i].iCursor = -1;
101074  }
101075
101076  /* Return a pointer to the enlarged SrcList */
101077  return pSrc;
101078}
101079
101080
101081/*
101082** Append a new table name to the given SrcList.  Create a new SrcList if
101083** need be.  A new entry is created in the SrcList even if pTable is NULL.
101084**
101085** A SrcList is returned, or NULL if there is an OOM error.  The returned
101086** SrcList might be the same as the SrcList that was input or it might be
101087** a new one.  If an OOM error does occurs, then the prior value of pList
101088** that is input to this routine is automatically freed.
101089**
101090** If pDatabase is not null, it means that the table has an optional
101091** database name prefix.  Like this:  "database.table".  The pDatabase
101092** points to the table name and the pTable points to the database name.
101093** The SrcList.a[].zName field is filled with the table name which might
101094** come from pTable (if pDatabase is NULL) or from pDatabase.
101095** SrcList.a[].zDatabase is filled with the database name from pTable,
101096** or with NULL if no database is specified.
101097**
101098** In other words, if call like this:
101099**
101100**         sqlite3SrcListAppend(D,A,B,0);
101101**
101102** Then B is a table name and the database name is unspecified.  If called
101103** like this:
101104**
101105**         sqlite3SrcListAppend(D,A,B,C);
101106**
101107** Then C is the table name and B is the database name.  If C is defined
101108** then so is B.  In other words, we never have a case where:
101109**
101110**         sqlite3SrcListAppend(D,A,0,C);
101111**
101112** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
101113** before being added to the SrcList.
101114*/
101115SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
101116  sqlite3 *db,        /* Connection to notify of malloc failures */
101117  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
101118  Token *pTable,      /* Table to append */
101119  Token *pDatabase    /* Database of the table */
101120){
101121  struct SrcList_item *pItem;
101122  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
101123  assert( db!=0 );
101124  if( pList==0 ){
101125    pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
101126    if( pList==0 ) return 0;
101127    pList->nAlloc = 1;
101128    pList->nSrc = 0;
101129  }
101130  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
101131  if( db->mallocFailed ){
101132    sqlite3SrcListDelete(db, pList);
101133    return 0;
101134  }
101135  pItem = &pList->a[pList->nSrc-1];
101136  if( pDatabase && pDatabase->z==0 ){
101137    pDatabase = 0;
101138  }
101139  if( pDatabase ){
101140    Token *pTemp = pDatabase;
101141    pDatabase = pTable;
101142    pTable = pTemp;
101143  }
101144  pItem->zName = sqlite3NameFromToken(db, pTable);
101145  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
101146  return pList;
101147}
101148
101149/*
101150** Assign VdbeCursor index numbers to all tables in a SrcList
101151*/
101152SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
101153  int i;
101154  struct SrcList_item *pItem;
101155  assert(pList || pParse->db->mallocFailed );
101156  if( pList ){
101157    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
101158      if( pItem->iCursor>=0 ) break;
101159      pItem->iCursor = pParse->nTab++;
101160      if( pItem->pSelect ){
101161        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
101162      }
101163    }
101164  }
101165}
101166
101167/*
101168** Delete an entire SrcList including all its substructure.
101169*/
101170SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
101171  int i;
101172  struct SrcList_item *pItem;
101173  if( pList==0 ) return;
101174  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
101175    sqlite3DbFree(db, pItem->zDatabase);
101176    sqlite3DbFree(db, pItem->zName);
101177    sqlite3DbFree(db, pItem->zAlias);
101178    if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
101179    if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
101180    sqlite3DeleteTable(db, pItem->pTab);
101181    sqlite3SelectDelete(db, pItem->pSelect);
101182    sqlite3ExprDelete(db, pItem->pOn);
101183    sqlite3IdListDelete(db, pItem->pUsing);
101184  }
101185  sqlite3DbFree(db, pList);
101186}
101187
101188/*
101189** This routine is called by the parser to add a new term to the
101190** end of a growing FROM clause.  The "p" parameter is the part of
101191** the FROM clause that has already been constructed.  "p" is NULL
101192** if this is the first term of the FROM clause.  pTable and pDatabase
101193** are the name of the table and database named in the FROM clause term.
101194** pDatabase is NULL if the database name qualifier is missing - the
101195** usual case.  If the term has an alias, then pAlias points to the
101196** alias token.  If the term is a subquery, then pSubquery is the
101197** SELECT statement that the subquery encodes.  The pTable and
101198** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
101199** parameters are the content of the ON and USING clauses.
101200**
101201** Return a new SrcList which encodes is the FROM with the new
101202** term added.
101203*/
101204SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
101205  Parse *pParse,          /* Parsing context */
101206  SrcList *p,             /* The left part of the FROM clause already seen */
101207  Token *pTable,          /* Name of the table to add to the FROM clause */
101208  Token *pDatabase,       /* Name of the database containing pTable */
101209  Token *pAlias,          /* The right-hand side of the AS subexpression */
101210  Select *pSubquery,      /* A subquery used in place of a table name */
101211  Expr *pOn,              /* The ON clause of a join */
101212  IdList *pUsing          /* The USING clause of a join */
101213){
101214  struct SrcList_item *pItem;
101215  sqlite3 *db = pParse->db;
101216  if( !p && (pOn || pUsing) ){
101217    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
101218      (pOn ? "ON" : "USING")
101219    );
101220    goto append_from_error;
101221  }
101222  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
101223  if( p==0 || NEVER(p->nSrc==0) ){
101224    goto append_from_error;
101225  }
101226  pItem = &p->a[p->nSrc-1];
101227  assert( pAlias!=0 );
101228  if( pAlias->n ){
101229    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
101230  }
101231  pItem->pSelect = pSubquery;
101232  pItem->pOn = pOn;
101233  pItem->pUsing = pUsing;
101234  return p;
101235
101236 append_from_error:
101237  assert( p==0 );
101238  sqlite3ExprDelete(db, pOn);
101239  sqlite3IdListDelete(db, pUsing);
101240  sqlite3SelectDelete(db, pSubquery);
101241  return 0;
101242}
101243
101244/*
101245** Add an INDEXED BY or NOT INDEXED clause to the most recently added
101246** element of the source-list passed as the second argument.
101247*/
101248SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
101249  assert( pIndexedBy!=0 );
101250  if( p && ALWAYS(p->nSrc>0) ){
101251    struct SrcList_item *pItem = &p->a[p->nSrc-1];
101252    assert( pItem->fg.notIndexed==0 );
101253    assert( pItem->fg.isIndexedBy==0 );
101254    assert( pItem->fg.isTabFunc==0 );
101255    if( pIndexedBy->n==1 && !pIndexedBy->z ){
101256      /* A "NOT INDEXED" clause was supplied. See parse.y
101257      ** construct "indexed_opt" for details. */
101258      pItem->fg.notIndexed = 1;
101259    }else{
101260      pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
101261      pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
101262    }
101263  }
101264}
101265
101266/*
101267** Add the list of function arguments to the SrcList entry for a
101268** table-valued-function.
101269*/
101270SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
101271  if( p ){
101272    struct SrcList_item *pItem = &p->a[p->nSrc-1];
101273    assert( pItem->fg.notIndexed==0 );
101274    assert( pItem->fg.isIndexedBy==0 );
101275    assert( pItem->fg.isTabFunc==0 );
101276    pItem->u1.pFuncArg = pList;
101277    pItem->fg.isTabFunc = 1;
101278  }else{
101279    sqlite3ExprListDelete(pParse->db, pList);
101280  }
101281}
101282
101283/*
101284** When building up a FROM clause in the parser, the join operator
101285** is initially attached to the left operand.  But the code generator
101286** expects the join operator to be on the right operand.  This routine
101287** Shifts all join operators from left to right for an entire FROM
101288** clause.
101289**
101290** Example: Suppose the join is like this:
101291**
101292**           A natural cross join B
101293**
101294** The operator is "natural cross join".  The A and B operands are stored
101295** in p->a[0] and p->a[1], respectively.  The parser initially stores the
101296** operator with A.  This routine shifts that operator over to B.
101297*/
101298SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
101299  if( p ){
101300    int i;
101301    for(i=p->nSrc-1; i>0; i--){
101302      p->a[i].fg.jointype = p->a[i-1].fg.jointype;
101303    }
101304    p->a[0].fg.jointype = 0;
101305  }
101306}
101307
101308/*
101309** Generate VDBE code for a BEGIN statement.
101310*/
101311SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
101312  sqlite3 *db;
101313  Vdbe *v;
101314  int i;
101315
101316  assert( pParse!=0 );
101317  db = pParse->db;
101318  assert( db!=0 );
101319  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
101320    return;
101321  }
101322  v = sqlite3GetVdbe(pParse);
101323  if( !v ) return;
101324  if( type!=TK_DEFERRED ){
101325    for(i=0; i<db->nDb; i++){
101326      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
101327      sqlite3VdbeUsesBtree(v, i);
101328    }
101329  }
101330  sqlite3VdbeAddOp0(v, OP_AutoCommit);
101331}
101332
101333/*
101334** Generate VDBE code for a COMMIT statement.
101335*/
101336SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
101337  Vdbe *v;
101338
101339  assert( pParse!=0 );
101340  assert( pParse->db!=0 );
101341  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
101342    return;
101343  }
101344  v = sqlite3GetVdbe(pParse);
101345  if( v ){
101346    sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
101347  }
101348}
101349
101350/*
101351** Generate VDBE code for a ROLLBACK statement.
101352*/
101353SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
101354  Vdbe *v;
101355
101356  assert( pParse!=0 );
101357  assert( pParse->db!=0 );
101358  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
101359    return;
101360  }
101361  v = sqlite3GetVdbe(pParse);
101362  if( v ){
101363    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
101364  }
101365}
101366
101367/*
101368** This function is called by the parser when it parses a command to create,
101369** release or rollback an SQL savepoint.
101370*/
101371SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
101372  char *zName = sqlite3NameFromToken(pParse->db, pName);
101373  if( zName ){
101374    Vdbe *v = sqlite3GetVdbe(pParse);
101375#ifndef SQLITE_OMIT_AUTHORIZATION
101376    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
101377    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
101378#endif
101379    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
101380      sqlite3DbFree(pParse->db, zName);
101381      return;
101382    }
101383    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
101384  }
101385}
101386
101387/*
101388** Make sure the TEMP database is open and available for use.  Return
101389** the number of errors.  Leave any error messages in the pParse structure.
101390*/
101391SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
101392  sqlite3 *db = pParse->db;
101393  if( db->aDb[1].pBt==0 && !pParse->explain ){
101394    int rc;
101395    Btree *pBt;
101396    static const int flags =
101397          SQLITE_OPEN_READWRITE |
101398          SQLITE_OPEN_CREATE |
101399          SQLITE_OPEN_EXCLUSIVE |
101400          SQLITE_OPEN_DELETEONCLOSE |
101401          SQLITE_OPEN_TEMP_DB;
101402
101403    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
101404    if( rc!=SQLITE_OK ){
101405      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
101406        "file for storing temporary tables");
101407      pParse->rc = rc;
101408      return 1;
101409    }
101410    db->aDb[1].pBt = pBt;
101411    assert( db->aDb[1].pSchema );
101412    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
101413      sqlite3OomFault(db);
101414      return 1;
101415    }
101416  }
101417  return 0;
101418}
101419
101420/*
101421** Record the fact that the schema cookie will need to be verified
101422** for database iDb.  The code to actually verify the schema cookie
101423** will occur at the end of the top-level VDBE and will be generated
101424** later, by sqlite3FinishCoding().
101425*/
101426SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
101427  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101428  sqlite3 *db = pToplevel->db;
101429
101430  assert( iDb>=0 && iDb<db->nDb );
101431  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
101432  assert( iDb<SQLITE_MAX_ATTACHED+2 );
101433  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101434  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
101435    DbMaskSet(pToplevel->cookieMask, iDb);
101436    pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
101437    if( !OMIT_TEMPDB && iDb==1 ){
101438      sqlite3OpenTempDatabase(pToplevel);
101439    }
101440  }
101441}
101442
101443/*
101444** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
101445** attached database. Otherwise, invoke it for the database named zDb only.
101446*/
101447SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
101448  sqlite3 *db = pParse->db;
101449  int i;
101450  for(i=0; i<db->nDb; i++){
101451    Db *pDb = &db->aDb[i];
101452    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
101453      sqlite3CodeVerifySchema(pParse, i);
101454    }
101455  }
101456}
101457
101458/*
101459** Generate VDBE code that prepares for doing an operation that
101460** might change the database.
101461**
101462** This routine starts a new transaction if we are not already within
101463** a transaction.  If we are already within a transaction, then a checkpoint
101464** is set if the setStatement parameter is true.  A checkpoint should
101465** be set for operations that might fail (due to a constraint) part of
101466** the way through and which will need to undo some writes without having to
101467** rollback the whole transaction.  For operations where all constraints
101468** can be checked before any changes are made to the database, it is never
101469** necessary to undo a write and the checkpoint should not be set.
101470*/
101471SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
101472  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101473  sqlite3CodeVerifySchema(pParse, iDb);
101474  DbMaskSet(pToplevel->writeMask, iDb);
101475  pToplevel->isMultiWrite |= setStatement;
101476}
101477
101478/*
101479** Indicate that the statement currently under construction might write
101480** more than one entry (example: deleting one row then inserting another,
101481** inserting multiple rows in a table, or inserting a row and index entries.)
101482** If an abort occurs after some of these writes have completed, then it will
101483** be necessary to undo the completed writes.
101484*/
101485SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
101486  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101487  pToplevel->isMultiWrite = 1;
101488}
101489
101490/*
101491** The code generator calls this routine if is discovers that it is
101492** possible to abort a statement prior to completion.  In order to
101493** perform this abort without corrupting the database, we need to make
101494** sure that the statement is protected by a statement transaction.
101495**
101496** Technically, we only need to set the mayAbort flag if the
101497** isMultiWrite flag was previously set.  There is a time dependency
101498** such that the abort must occur after the multiwrite.  This makes
101499** some statements involving the REPLACE conflict resolution algorithm
101500** go a little faster.  But taking advantage of this time dependency
101501** makes it more difficult to prove that the code is correct (in
101502** particular, it prevents us from writing an effective
101503** implementation of sqlite3AssertMayAbort()) and so we have chosen
101504** to take the safe route and skip the optimization.
101505*/
101506SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
101507  Parse *pToplevel = sqlite3ParseToplevel(pParse);
101508  pToplevel->mayAbort = 1;
101509}
101510
101511/*
101512** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
101513** error. The onError parameter determines which (if any) of the statement
101514** and/or current transaction is rolled back.
101515*/
101516SQLITE_PRIVATE void sqlite3HaltConstraint(
101517  Parse *pParse,    /* Parsing context */
101518  int errCode,      /* extended error code */
101519  int onError,      /* Constraint type */
101520  char *p4,         /* Error message */
101521  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
101522  u8 p5Errmsg       /* P5_ErrMsg type */
101523){
101524  Vdbe *v = sqlite3GetVdbe(pParse);
101525  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
101526  if( onError==OE_Abort ){
101527    sqlite3MayAbort(pParse);
101528  }
101529  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
101530  sqlite3VdbeChangeP5(v, p5Errmsg);
101531}
101532
101533/*
101534** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
101535*/
101536SQLITE_PRIVATE void sqlite3UniqueConstraint(
101537  Parse *pParse,    /* Parsing context */
101538  int onError,      /* Constraint type */
101539  Index *pIdx       /* The index that triggers the constraint */
101540){
101541  char *zErr;
101542  int j;
101543  StrAccum errMsg;
101544  Table *pTab = pIdx->pTable;
101545
101546  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
101547  if( pIdx->aColExpr ){
101548    sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
101549  }else{
101550    for(j=0; j<pIdx->nKeyCol; j++){
101551      char *zCol;
101552      assert( pIdx->aiColumn[j]>=0 );
101553      zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
101554      if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
101555      sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
101556    }
101557  }
101558  zErr = sqlite3StrAccumFinish(&errMsg);
101559  sqlite3HaltConstraint(pParse,
101560    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
101561                            : SQLITE_CONSTRAINT_UNIQUE,
101562    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
101563}
101564
101565
101566/*
101567** Code an OP_Halt due to non-unique rowid.
101568*/
101569SQLITE_PRIVATE void sqlite3RowidConstraint(
101570  Parse *pParse,    /* Parsing context */
101571  int onError,      /* Conflict resolution algorithm */
101572  Table *pTab       /* The table with the non-unique rowid */
101573){
101574  char *zMsg;
101575  int rc;
101576  if( pTab->iPKey>=0 ){
101577    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
101578                          pTab->aCol[pTab->iPKey].zName);
101579    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
101580  }else{
101581    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
101582    rc = SQLITE_CONSTRAINT_ROWID;
101583  }
101584  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
101585                        P5_ConstraintUnique);
101586}
101587
101588/*
101589** Check to see if pIndex uses the collating sequence pColl.  Return
101590** true if it does and false if it does not.
101591*/
101592#ifndef SQLITE_OMIT_REINDEX
101593static int collationMatch(const char *zColl, Index *pIndex){
101594  int i;
101595  assert( zColl!=0 );
101596  for(i=0; i<pIndex->nColumn; i++){
101597    const char *z = pIndex->azColl[i];
101598    assert( z!=0 || pIndex->aiColumn[i]<0 );
101599    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
101600      return 1;
101601    }
101602  }
101603  return 0;
101604}
101605#endif
101606
101607/*
101608** Recompute all indices of pTab that use the collating sequence pColl.
101609** If pColl==0 then recompute all indices of pTab.
101610*/
101611#ifndef SQLITE_OMIT_REINDEX
101612static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
101613  Index *pIndex;              /* An index associated with pTab */
101614
101615  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
101616    if( zColl==0 || collationMatch(zColl, pIndex) ){
101617      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101618      sqlite3BeginWriteOperation(pParse, 0, iDb);
101619      sqlite3RefillIndex(pParse, pIndex, -1);
101620    }
101621  }
101622}
101623#endif
101624
101625/*
101626** Recompute all indices of all tables in all databases where the
101627** indices use the collating sequence pColl.  If pColl==0 then recompute
101628** all indices everywhere.
101629*/
101630#ifndef SQLITE_OMIT_REINDEX
101631static void reindexDatabases(Parse *pParse, char const *zColl){
101632  Db *pDb;                    /* A single database */
101633  int iDb;                    /* The database index number */
101634  sqlite3 *db = pParse->db;   /* The database connection */
101635  HashElem *k;                /* For looping over tables in pDb */
101636  Table *pTab;                /* A table in the database */
101637
101638  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
101639  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
101640    assert( pDb!=0 );
101641    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
101642      pTab = (Table*)sqliteHashData(k);
101643      reindexTable(pParse, pTab, zColl);
101644    }
101645  }
101646}
101647#endif
101648
101649/*
101650** Generate code for the REINDEX command.
101651**
101652**        REINDEX                            -- 1
101653**        REINDEX  <collation>               -- 2
101654**        REINDEX  ?<database>.?<tablename>  -- 3
101655**        REINDEX  ?<database>.?<indexname>  -- 4
101656**
101657** Form 1 causes all indices in all attached databases to be rebuilt.
101658** Form 2 rebuilds all indices in all databases that use the named
101659** collating function.  Forms 3 and 4 rebuild the named index or all
101660** indices associated with the named table.
101661*/
101662#ifndef SQLITE_OMIT_REINDEX
101663SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
101664  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
101665  char *z;                    /* Name of a table or index */
101666  const char *zDb;            /* Name of the database */
101667  Table *pTab;                /* A table in the database */
101668  Index *pIndex;              /* An index associated with pTab */
101669  int iDb;                    /* The database index number */
101670  sqlite3 *db = pParse->db;   /* The database connection */
101671  Token *pObjName;            /* Name of the table or index to be reindexed */
101672
101673  /* Read the database schema. If an error occurs, leave an error message
101674  ** and code in pParse and return NULL. */
101675  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101676    return;
101677  }
101678
101679  if( pName1==0 ){
101680    reindexDatabases(pParse, 0);
101681    return;
101682  }else if( NEVER(pName2==0) || pName2->z==0 ){
101683    char *zColl;
101684    assert( pName1->z );
101685    zColl = sqlite3NameFromToken(pParse->db, pName1);
101686    if( !zColl ) return;
101687    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
101688    if( pColl ){
101689      reindexDatabases(pParse, zColl);
101690      sqlite3DbFree(db, zColl);
101691      return;
101692    }
101693    sqlite3DbFree(db, zColl);
101694  }
101695  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
101696  if( iDb<0 ) return;
101697  z = sqlite3NameFromToken(db, pObjName);
101698  if( z==0 ) return;
101699  zDb = db->aDb[iDb].zName;
101700  pTab = sqlite3FindTable(db, z, zDb);
101701  if( pTab ){
101702    reindexTable(pParse, pTab, 0);
101703    sqlite3DbFree(db, z);
101704    return;
101705  }
101706  pIndex = sqlite3FindIndex(db, z, zDb);
101707  sqlite3DbFree(db, z);
101708  if( pIndex ){
101709    sqlite3BeginWriteOperation(pParse, 0, iDb);
101710    sqlite3RefillIndex(pParse, pIndex, -1);
101711    return;
101712  }
101713  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
101714}
101715#endif
101716
101717/*
101718** Return a KeyInfo structure that is appropriate for the given Index.
101719**
101720** The caller should invoke sqlite3KeyInfoUnref() on the returned object
101721** when it has finished using it.
101722*/
101723SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
101724  int i;
101725  int nCol = pIdx->nColumn;
101726  int nKey = pIdx->nKeyCol;
101727  KeyInfo *pKey;
101728  if( pParse->nErr ) return 0;
101729  if( pIdx->uniqNotNull ){
101730    pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
101731  }else{
101732    pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
101733  }
101734  if( pKey ){
101735    assert( sqlite3KeyInfoIsWriteable(pKey) );
101736    for(i=0; i<nCol; i++){
101737      const char *zColl = pIdx->azColl[i];
101738      pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
101739                        sqlite3LocateCollSeq(pParse, zColl);
101740      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
101741    }
101742    if( pParse->nErr ){
101743      sqlite3KeyInfoUnref(pKey);
101744      pKey = 0;
101745    }
101746  }
101747  return pKey;
101748}
101749
101750#ifndef SQLITE_OMIT_CTE
101751/*
101752** This routine is invoked once per CTE by the parser while parsing a
101753** WITH clause.
101754*/
101755SQLITE_PRIVATE With *sqlite3WithAdd(
101756  Parse *pParse,          /* Parsing context */
101757  With *pWith,            /* Existing WITH clause, or NULL */
101758  Token *pName,           /* Name of the common-table */
101759  ExprList *pArglist,     /* Optional column name list for the table */
101760  Select *pQuery          /* Query used to initialize the table */
101761){
101762  sqlite3 *db = pParse->db;
101763  With *pNew;
101764  char *zName;
101765
101766  /* Check that the CTE name is unique within this WITH clause. If
101767  ** not, store an error in the Parse structure. */
101768  zName = sqlite3NameFromToken(pParse->db, pName);
101769  if( zName && pWith ){
101770    int i;
101771    for(i=0; i<pWith->nCte; i++){
101772      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
101773        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
101774      }
101775    }
101776  }
101777
101778  if( pWith ){
101779    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
101780    pNew = sqlite3DbRealloc(db, pWith, nByte);
101781  }else{
101782    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
101783  }
101784  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
101785
101786  if( db->mallocFailed ){
101787    sqlite3ExprListDelete(db, pArglist);
101788    sqlite3SelectDelete(db, pQuery);
101789    sqlite3DbFree(db, zName);
101790    pNew = pWith;
101791  }else{
101792    pNew->a[pNew->nCte].pSelect = pQuery;
101793    pNew->a[pNew->nCte].pCols = pArglist;
101794    pNew->a[pNew->nCte].zName = zName;
101795    pNew->a[pNew->nCte].zCteErr = 0;
101796    pNew->nCte++;
101797  }
101798
101799  return pNew;
101800}
101801
101802/*
101803** Free the contents of the With object passed as the second argument.
101804*/
101805SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
101806  if( pWith ){
101807    int i;
101808    for(i=0; i<pWith->nCte; i++){
101809      struct Cte *pCte = &pWith->a[i];
101810      sqlite3ExprListDelete(db, pCte->pCols);
101811      sqlite3SelectDelete(db, pCte->pSelect);
101812      sqlite3DbFree(db, pCte->zName);
101813    }
101814    sqlite3DbFree(db, pWith);
101815  }
101816}
101817#endif /* !defined(SQLITE_OMIT_CTE) */
101818
101819/************** End of build.c ***********************************************/
101820/************** Begin file callback.c ****************************************/
101821/*
101822** 2005 May 23
101823**
101824** The author disclaims copyright to this source code.  In place of
101825** a legal notice, here is a blessing:
101826**
101827**    May you do good and not evil.
101828**    May you find forgiveness for yourself and forgive others.
101829**    May you share freely, never taking more than you give.
101830**
101831*************************************************************************
101832**
101833** This file contains functions used to access the internal hash tables
101834** of user defined functions and collation sequences.
101835*/
101836
101837/* #include "sqliteInt.h" */
101838
101839/*
101840** Invoke the 'collation needed' callback to request a collation sequence
101841** in the encoding enc of name zName, length nName.
101842*/
101843static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
101844  assert( !db->xCollNeeded || !db->xCollNeeded16 );
101845  if( db->xCollNeeded ){
101846    char *zExternal = sqlite3DbStrDup(db, zName);
101847    if( !zExternal ) return;
101848    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
101849    sqlite3DbFree(db, zExternal);
101850  }
101851#ifndef SQLITE_OMIT_UTF16
101852  if( db->xCollNeeded16 ){
101853    char const *zExternal;
101854    sqlite3_value *pTmp = sqlite3ValueNew(db);
101855    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
101856    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
101857    if( zExternal ){
101858      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
101859    }
101860    sqlite3ValueFree(pTmp);
101861  }
101862#endif
101863}
101864
101865/*
101866** This routine is called if the collation factory fails to deliver a
101867** collation function in the best encoding but there may be other versions
101868** of this collation function (for other text encodings) available. Use one
101869** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
101870** possible.
101871*/
101872static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
101873  CollSeq *pColl2;
101874  char *z = pColl->zName;
101875  int i;
101876  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
101877  for(i=0; i<3; i++){
101878    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
101879    if( pColl2->xCmp!=0 ){
101880      memcpy(pColl, pColl2, sizeof(CollSeq));
101881      pColl->xDel = 0;         /* Do not copy the destructor */
101882      return SQLITE_OK;
101883    }
101884  }
101885  return SQLITE_ERROR;
101886}
101887
101888/*
101889** This function is responsible for invoking the collation factory callback
101890** or substituting a collation sequence of a different encoding when the
101891** requested collation sequence is not available in the desired encoding.
101892**
101893** If it is not NULL, then pColl must point to the database native encoding
101894** collation sequence with name zName, length nName.
101895**
101896** The return value is either the collation sequence to be used in database
101897** db for collation type name zName, length nName, or NULL, if no collation
101898** sequence can be found.  If no collation is found, leave an error message.
101899**
101900** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
101901*/
101902SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
101903  Parse *pParse,        /* Parsing context */
101904  u8 enc,               /* The desired encoding for the collating sequence */
101905  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
101906  const char *zName     /* Collating sequence name */
101907){
101908  CollSeq *p;
101909  sqlite3 *db = pParse->db;
101910
101911  p = pColl;
101912  if( !p ){
101913    p = sqlite3FindCollSeq(db, enc, zName, 0);
101914  }
101915  if( !p || !p->xCmp ){
101916    /* No collation sequence of this type for this encoding is registered.
101917    ** Call the collation factory to see if it can supply us with one.
101918    */
101919    callCollNeeded(db, enc, zName);
101920    p = sqlite3FindCollSeq(db, enc, zName, 0);
101921  }
101922  if( p && !p->xCmp && synthCollSeq(db, p) ){
101923    p = 0;
101924  }
101925  assert( !p || p->xCmp );
101926  if( p==0 ){
101927    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
101928  }
101929  return p;
101930}
101931
101932/*
101933** This routine is called on a collation sequence before it is used to
101934** check that it is defined. An undefined collation sequence exists when
101935** a database is loaded that contains references to collation sequences
101936** that have not been defined by sqlite3_create_collation() etc.
101937**
101938** If required, this routine calls the 'collation needed' callback to
101939** request a definition of the collating sequence. If this doesn't work,
101940** an equivalent collating sequence that uses a text encoding different
101941** from the main database is substituted, if one is available.
101942*/
101943SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
101944  if( pColl ){
101945    const char *zName = pColl->zName;
101946    sqlite3 *db = pParse->db;
101947    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
101948    if( !p ){
101949      return SQLITE_ERROR;
101950    }
101951    assert( p==pColl );
101952  }
101953  return SQLITE_OK;
101954}
101955
101956
101957
101958/*
101959** Locate and return an entry from the db.aCollSeq hash table. If the entry
101960** specified by zName and nName is not found and parameter 'create' is
101961** true, then create a new entry. Otherwise return NULL.
101962**
101963** Each pointer stored in the sqlite3.aCollSeq hash table contains an
101964** array of three CollSeq structures. The first is the collation sequence
101965** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
101966**
101967** Stored immediately after the three collation sequences is a copy of
101968** the collation sequence name. A pointer to this string is stored in
101969** each collation sequence structure.
101970*/
101971static CollSeq *findCollSeqEntry(
101972  sqlite3 *db,          /* Database connection */
101973  const char *zName,    /* Name of the collating sequence */
101974  int create            /* Create a new entry if true */
101975){
101976  CollSeq *pColl;
101977  pColl = sqlite3HashFind(&db->aCollSeq, zName);
101978
101979  if( 0==pColl && create ){
101980    int nName = sqlite3Strlen30(zName);
101981    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
101982    if( pColl ){
101983      CollSeq *pDel = 0;
101984      pColl[0].zName = (char*)&pColl[3];
101985      pColl[0].enc = SQLITE_UTF8;
101986      pColl[1].zName = (char*)&pColl[3];
101987      pColl[1].enc = SQLITE_UTF16LE;
101988      pColl[2].zName = (char*)&pColl[3];
101989      pColl[2].enc = SQLITE_UTF16BE;
101990      memcpy(pColl[0].zName, zName, nName);
101991      pColl[0].zName[nName] = 0;
101992      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
101993
101994      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
101995      ** return the pColl pointer to be deleted (because it wasn't added
101996      ** to the hash table).
101997      */
101998      assert( pDel==0 || pDel==pColl );
101999      if( pDel!=0 ){
102000        sqlite3OomFault(db);
102001        sqlite3DbFree(db, pDel);
102002        pColl = 0;
102003      }
102004    }
102005  }
102006  return pColl;
102007}
102008
102009/*
102010** Parameter zName points to a UTF-8 encoded string nName bytes long.
102011** Return the CollSeq* pointer for the collation sequence named zName
102012** for the encoding 'enc' from the database 'db'.
102013**
102014** If the entry specified is not found and 'create' is true, then create a
102015** new entry.  Otherwise return NULL.
102016**
102017** A separate function sqlite3LocateCollSeq() is a wrapper around
102018** this routine.  sqlite3LocateCollSeq() invokes the collation factory
102019** if necessary and generates an error message if the collating sequence
102020** cannot be found.
102021**
102022** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
102023*/
102024SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
102025  sqlite3 *db,
102026  u8 enc,
102027  const char *zName,
102028  int create
102029){
102030  CollSeq *pColl;
102031  if( zName ){
102032    pColl = findCollSeqEntry(db, zName, create);
102033  }else{
102034    pColl = db->pDfltColl;
102035  }
102036  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
102037  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
102038  if( pColl ) pColl += enc-1;
102039  return pColl;
102040}
102041
102042/* During the search for the best function definition, this procedure
102043** is called to test how well the function passed as the first argument
102044** matches the request for a function with nArg arguments in a system
102045** that uses encoding enc. The value returned indicates how well the
102046** request is matched. A higher value indicates a better match.
102047**
102048** If nArg is -1 that means to only return a match (non-zero) if p->nArg
102049** is also -1.  In other words, we are searching for a function that
102050** takes a variable number of arguments.
102051**
102052** If nArg is -2 that means that we are searching for any function
102053** regardless of the number of arguments it uses, so return a positive
102054** match score for any
102055**
102056** The returned value is always between 0 and 6, as follows:
102057**
102058** 0: Not a match.
102059** 1: UTF8/16 conversion required and function takes any number of arguments.
102060** 2: UTF16 byte order change required and function takes any number of args.
102061** 3: encoding matches and function takes any number of arguments
102062** 4: UTF8/16 conversion required - argument count matches exactly
102063** 5: UTF16 byte order conversion required - argument count matches exactly
102064** 6: Perfect match:  encoding and argument count match exactly.
102065**
102066** If nArg==(-2) then any function with a non-null xSFunc is
102067** a perfect match and any function with xSFunc NULL is
102068** a non-match.
102069*/
102070#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
102071static int matchQuality(
102072  FuncDef *p,     /* The function we are evaluating for match quality */
102073  int nArg,       /* Desired number of arguments.  (-1)==any */
102074  u8 enc          /* Desired text encoding */
102075){
102076  int match;
102077
102078  /* nArg of -2 is a special case */
102079  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
102080
102081  /* Wrong number of arguments means "no match" */
102082  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
102083
102084  /* Give a better score to a function with a specific number of arguments
102085  ** than to function that accepts any number of arguments. */
102086  if( p->nArg==nArg ){
102087    match = 4;
102088  }else{
102089    match = 1;
102090  }
102091
102092  /* Bonus points if the text encoding matches */
102093  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
102094    match += 2;  /* Exact encoding match */
102095  }else if( (enc & p->funcFlags & 2)!=0 ){
102096    match += 1;  /* Both are UTF16, but with different byte orders */
102097  }
102098
102099  return match;
102100}
102101
102102/*
102103** Search a FuncDefHash for a function with the given name.  Return
102104** a pointer to the matching FuncDef if found, or 0 if there is no match.
102105*/
102106static FuncDef *functionSearch(
102107  int h,               /* Hash of the name */
102108  const char *zFunc    /* Name of function */
102109){
102110  FuncDef *p;
102111  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
102112    if( sqlite3StrICmp(p->zName, zFunc)==0 ){
102113      return p;
102114    }
102115  }
102116  return 0;
102117}
102118
102119/*
102120** Insert a new FuncDef into a FuncDefHash hash table.
102121*/
102122SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
102123  FuncDef *aDef,      /* List of global functions to be inserted */
102124  int nDef            /* Length of the apDef[] list */
102125){
102126  int i;
102127  for(i=0; i<nDef; i++){
102128    FuncDef *pOther;
102129    const char *zName = aDef[i].zName;
102130    int nName = sqlite3Strlen30(zName);
102131    int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
102132    pOther = functionSearch(h, zName);
102133    if( pOther ){
102134      assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
102135      aDef[i].pNext = pOther->pNext;
102136      pOther->pNext = &aDef[i];
102137    }else{
102138      aDef[i].pNext = 0;
102139      aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
102140      sqlite3BuiltinFunctions.a[h] = &aDef[i];
102141    }
102142  }
102143}
102144
102145
102146
102147/*
102148** Locate a user function given a name, a number of arguments and a flag
102149** indicating whether the function prefers UTF-16 over UTF-8.  Return a
102150** pointer to the FuncDef structure that defines that function, or return
102151** NULL if the function does not exist.
102152**
102153** If the createFlag argument is true, then a new (blank) FuncDef
102154** structure is created and liked into the "db" structure if a
102155** no matching function previously existed.
102156**
102157** If nArg is -2, then the first valid function found is returned.  A
102158** function is valid if xSFunc is non-zero.  The nArg==(-2)
102159** case is used to see if zName is a valid function name for some number
102160** of arguments.  If nArg is -2, then createFlag must be 0.
102161**
102162** If createFlag is false, then a function with the required name and
102163** number of arguments may be returned even if the eTextRep flag does not
102164** match that requested.
102165*/
102166SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
102167  sqlite3 *db,       /* An open database */
102168  const char *zName, /* Name of the function.  zero-terminated */
102169  int nArg,          /* Number of arguments.  -1 means any number */
102170  u8 enc,            /* Preferred text encoding */
102171  u8 createFlag      /* Create new entry if true and does not otherwise exist */
102172){
102173  FuncDef *p;         /* Iterator variable */
102174  FuncDef *pBest = 0; /* Best match found so far */
102175  int bestScore = 0;  /* Score of best match */
102176  int h;              /* Hash value */
102177  int nName;          /* Length of the name */
102178
102179  assert( nArg>=(-2) );
102180  assert( nArg>=(-1) || createFlag==0 );
102181  nName = sqlite3Strlen30(zName);
102182
102183  /* First search for a match amongst the application-defined functions.
102184  */
102185  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
102186  while( p ){
102187    int score = matchQuality(p, nArg, enc);
102188    if( score>bestScore ){
102189      pBest = p;
102190      bestScore = score;
102191    }
102192    p = p->pNext;
102193  }
102194
102195  /* If no match is found, search the built-in functions.
102196  **
102197  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
102198  ** functions even if a prior app-defined function was found.  And give
102199  ** priority to built-in functions.
102200  **
102201  ** Except, if createFlag is true, that means that we are trying to
102202  ** install a new function.  Whatever FuncDef structure is returned it will
102203  ** have fields overwritten with new information appropriate for the
102204  ** new function.  But the FuncDefs for built-in functions are read-only.
102205  ** So we must not search for built-ins when creating a new function.
102206  */
102207  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
102208    bestScore = 0;
102209    h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
102210    p = functionSearch(h, zName);
102211    while( p ){
102212      int score = matchQuality(p, nArg, enc);
102213      if( score>bestScore ){
102214        pBest = p;
102215        bestScore = score;
102216      }
102217      p = p->pNext;
102218    }
102219  }
102220
102221  /* If the createFlag parameter is true and the search did not reveal an
102222  ** exact match for the name, number of arguments and encoding, then add a
102223  ** new entry to the hash table and return it.
102224  */
102225  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
102226      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
102227    FuncDef *pOther;
102228    pBest->zName = (const char*)&pBest[1];
102229    pBest->nArg = (u16)nArg;
102230    pBest->funcFlags = enc;
102231    memcpy((char*)&pBest[1], zName, nName+1);
102232    pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
102233    if( pOther==pBest ){
102234      sqlite3DbFree(db, pBest);
102235      sqlite3OomFault(db);
102236      return 0;
102237    }else{
102238      pBest->pNext = pOther;
102239    }
102240  }
102241
102242  if( pBest && (pBest->xSFunc || createFlag) ){
102243    return pBest;
102244  }
102245  return 0;
102246}
102247
102248/*
102249** Free all resources held by the schema structure. The void* argument points
102250** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
102251** pointer itself, it just cleans up subsidiary resources (i.e. the contents
102252** of the schema hash tables).
102253**
102254** The Schema.cache_size variable is not cleared.
102255*/
102256SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
102257  Hash temp1;
102258  Hash temp2;
102259  HashElem *pElem;
102260  Schema *pSchema = (Schema *)p;
102261
102262  temp1 = pSchema->tblHash;
102263  temp2 = pSchema->trigHash;
102264  sqlite3HashInit(&pSchema->trigHash);
102265  sqlite3HashClear(&pSchema->idxHash);
102266  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
102267    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
102268  }
102269  sqlite3HashClear(&temp2);
102270  sqlite3HashInit(&pSchema->tblHash);
102271  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
102272    Table *pTab = sqliteHashData(pElem);
102273    sqlite3DeleteTable(0, pTab);
102274  }
102275  sqlite3HashClear(&temp1);
102276  sqlite3HashClear(&pSchema->fkeyHash);
102277  pSchema->pSeqTab = 0;
102278  if( pSchema->schemaFlags & DB_SchemaLoaded ){
102279    pSchema->iGeneration++;
102280    pSchema->schemaFlags &= ~DB_SchemaLoaded;
102281  }
102282}
102283
102284/*
102285** Find and return the schema associated with a BTree.  Create
102286** a new one if necessary.
102287*/
102288SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
102289  Schema * p;
102290  if( pBt ){
102291    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
102292  }else{
102293    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
102294  }
102295  if( !p ){
102296    sqlite3OomFault(db);
102297  }else if ( 0==p->file_format ){
102298    sqlite3HashInit(&p->tblHash);
102299    sqlite3HashInit(&p->idxHash);
102300    sqlite3HashInit(&p->trigHash);
102301    sqlite3HashInit(&p->fkeyHash);
102302    p->enc = SQLITE_UTF8;
102303  }
102304  return p;
102305}
102306
102307/************** End of callback.c ********************************************/
102308/************** Begin file delete.c ******************************************/
102309/*
102310** 2001 September 15
102311**
102312** The author disclaims copyright to this source code.  In place of
102313** a legal notice, here is a blessing:
102314**
102315**    May you do good and not evil.
102316**    May you find forgiveness for yourself and forgive others.
102317**    May you share freely, never taking more than you give.
102318**
102319*************************************************************************
102320** This file contains C code routines that are called by the parser
102321** in order to generate code for DELETE FROM statements.
102322*/
102323/* #include "sqliteInt.h" */
102324
102325/*
102326** While a SrcList can in general represent multiple tables and subqueries
102327** (as in the FROM clause of a SELECT statement) in this case it contains
102328** the name of a single table, as one might find in an INSERT, DELETE,
102329** or UPDATE statement.  Look up that table in the symbol table and
102330** return a pointer.  Set an error message and return NULL if the table
102331** name is not found or if any other error occurs.
102332**
102333** The following fields are initialized appropriate in pSrc:
102334**
102335**    pSrc->a[0].pTab       Pointer to the Table object
102336**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
102337**
102338*/
102339SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
102340  struct SrcList_item *pItem = pSrc->a;
102341  Table *pTab;
102342  assert( pItem && pSrc->nSrc==1 );
102343  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
102344  sqlite3DeleteTable(pParse->db, pItem->pTab);
102345  pItem->pTab = pTab;
102346  if( pTab ){
102347    pTab->nRef++;
102348  }
102349  if( sqlite3IndexedByLookup(pParse, pItem) ){
102350    pTab = 0;
102351  }
102352  return pTab;
102353}
102354
102355/*
102356** Check to make sure the given table is writable.  If it is not
102357** writable, generate an error message and return 1.  If it is
102358** writable return 0;
102359*/
102360SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
102361  /* A table is not writable under the following circumstances:
102362  **
102363  **   1) It is a virtual table and no implementation of the xUpdate method
102364  **      has been provided, or
102365  **   2) It is a system table (i.e. sqlite_master), this call is not
102366  **      part of a nested parse and writable_schema pragma has not
102367  **      been specified.
102368  **
102369  ** In either case leave an error message in pParse and return non-zero.
102370  */
102371  if( ( IsVirtual(pTab)
102372     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
102373   || ( (pTab->tabFlags & TF_Readonly)!=0
102374     && (pParse->db->flags & SQLITE_WriteSchema)==0
102375     && pParse->nested==0 )
102376  ){
102377    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
102378    return 1;
102379  }
102380
102381#ifndef SQLITE_OMIT_VIEW
102382  if( !viewOk && pTab->pSelect ){
102383    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
102384    return 1;
102385  }
102386#endif
102387  return 0;
102388}
102389
102390
102391#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102392/*
102393** Evaluate a view and store its result in an ephemeral table.  The
102394** pWhere argument is an optional WHERE clause that restricts the
102395** set of rows in the view that are to be added to the ephemeral table.
102396*/
102397SQLITE_PRIVATE void sqlite3MaterializeView(
102398  Parse *pParse,       /* Parsing context */
102399  Table *pView,        /* View definition */
102400  Expr *pWhere,        /* Optional WHERE clause to be added */
102401  int iCur             /* Cursor number for ephemeral table */
102402){
102403  SelectDest dest;
102404  Select *pSel;
102405  SrcList *pFrom;
102406  sqlite3 *db = pParse->db;
102407  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
102408  pWhere = sqlite3ExprDup(db, pWhere, 0);
102409  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
102410  if( pFrom ){
102411    assert( pFrom->nSrc==1 );
102412    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
102413    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
102414    assert( pFrom->a[0].pOn==0 );
102415    assert( pFrom->a[0].pUsing==0 );
102416  }
102417  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
102418                          SF_IncludeHidden, 0, 0);
102419  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
102420  sqlite3Select(pParse, pSel, &dest);
102421  sqlite3SelectDelete(db, pSel);
102422}
102423#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
102424
102425#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
102426/*
102427** Generate an expression tree to implement the WHERE, ORDER BY,
102428** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
102429**
102430**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
102431**                            \__________________________/
102432**                               pLimitWhere (pInClause)
102433*/
102434SQLITE_PRIVATE Expr *sqlite3LimitWhere(
102435  Parse *pParse,               /* The parser context */
102436  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
102437  Expr *pWhere,                /* The WHERE clause.  May be null */
102438  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
102439  Expr *pLimit,                /* The LIMIT clause.  May be null */
102440  Expr *pOffset,               /* The OFFSET clause.  May be null */
102441  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
102442){
102443  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
102444  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
102445  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
102446  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
102447  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
102448  Select *pSelect = NULL;      /* Complete SELECT tree */
102449
102450  /* Check that there isn't an ORDER BY without a LIMIT clause.
102451  */
102452  if( pOrderBy && (pLimit == 0) ) {
102453    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
102454    goto limit_where_cleanup;
102455  }
102456
102457  /* We only need to generate a select expression if there
102458  ** is a limit/offset term to enforce.
102459  */
102460  if( pLimit == 0 ) {
102461    /* if pLimit is null, pOffset will always be null as well. */
102462    assert( pOffset == 0 );
102463    return pWhere;
102464  }
102465
102466  /* Generate a select expression tree to enforce the limit/offset
102467  ** term for the DELETE or UPDATE statement.  For example:
102468  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
102469  ** becomes:
102470  **   DELETE FROM table_a WHERE rowid IN (
102471  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
102472  **   );
102473  */
102474
102475  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
102476  if( pSelectRowid == 0 ) goto limit_where_cleanup;
102477  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
102478  if( pEList == 0 ) goto limit_where_cleanup;
102479
102480  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
102481  ** and the SELECT subtree. */
102482  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
102483  if( pSelectSrc == 0 ) {
102484    sqlite3ExprListDelete(pParse->db, pEList);
102485    goto limit_where_cleanup;
102486  }
102487
102488  /* generate the SELECT expression tree. */
102489  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
102490                             pOrderBy,0,pLimit,pOffset);
102491  if( pSelect == 0 ) return 0;
102492
102493  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
102494  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
102495  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
102496  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
102497  return pInClause;
102498
102499limit_where_cleanup:
102500  sqlite3ExprDelete(pParse->db, pWhere);
102501  sqlite3ExprListDelete(pParse->db, pOrderBy);
102502  sqlite3ExprDelete(pParse->db, pLimit);
102503  sqlite3ExprDelete(pParse->db, pOffset);
102504  return 0;
102505}
102506#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
102507       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
102508
102509/*
102510** Generate code for a DELETE FROM statement.
102511**
102512**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
102513**                 \________/       \________________/
102514**                  pTabList              pWhere
102515*/
102516SQLITE_PRIVATE void sqlite3DeleteFrom(
102517  Parse *pParse,         /* The parser context */
102518  SrcList *pTabList,     /* The table from which we should delete things */
102519  Expr *pWhere           /* The WHERE clause.  May be null */
102520){
102521  Vdbe *v;               /* The virtual database engine */
102522  Table *pTab;           /* The table from which records will be deleted */
102523  const char *zDb;       /* Name of database holding pTab */
102524  int i;                 /* Loop counter */
102525  WhereInfo *pWInfo;     /* Information about the WHERE clause */
102526  Index *pIdx;           /* For looping over indices of the table */
102527  int iTabCur;           /* Cursor number for the table */
102528  int iDataCur = 0;      /* VDBE cursor for the canonical data source */
102529  int iIdxCur = 0;       /* Cursor number of the first index */
102530  int nIdx;              /* Number of indices */
102531  sqlite3 *db;           /* Main database structure */
102532  AuthContext sContext;  /* Authorization context */
102533  NameContext sNC;       /* Name context to resolve expressions in */
102534  int iDb;               /* Database number */
102535  int memCnt = -1;       /* Memory cell used for change counting */
102536  int rcauth;            /* Value returned by authorization callback */
102537  int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
102538  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
102539  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
102540  Index *pPk;            /* The PRIMARY KEY index on the table */
102541  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
102542  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
102543  int iKey;              /* Memory cell holding key of row to be deleted */
102544  i16 nKey;              /* Number of memory cells in the row key */
102545  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
102546  int iRowSet = 0;       /* Register for rowset of rows to delete */
102547  int addrBypass = 0;    /* Address of jump over the delete logic */
102548  int addrLoop = 0;      /* Top of the delete loop */
102549  int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
102550  int bComplex;          /* True if there are triggers or FKs or
102551                         ** subqueries in the WHERE clause */
102552
102553#ifndef SQLITE_OMIT_TRIGGER
102554  int isView;                  /* True if attempting to delete from a view */
102555  Trigger *pTrigger;           /* List of table triggers, if required */
102556#endif
102557
102558  memset(&sContext, 0, sizeof(sContext));
102559  db = pParse->db;
102560  if( pParse->nErr || db->mallocFailed ){
102561    goto delete_from_cleanup;
102562  }
102563  assert( pTabList->nSrc==1 );
102564
102565  /* Locate the table which we want to delete.  This table has to be
102566  ** put in an SrcList structure because some of the subroutines we
102567  ** will be calling are designed to work with multiple tables and expect
102568  ** an SrcList* parameter instead of just a Table* parameter.
102569  */
102570  pTab = sqlite3SrcListLookup(pParse, pTabList);
102571  if( pTab==0 )  goto delete_from_cleanup;
102572
102573  /* Figure out if we have any triggers and if the table being
102574  ** deleted from is a view
102575  */
102576#ifndef SQLITE_OMIT_TRIGGER
102577  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
102578  isView = pTab->pSelect!=0;
102579  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
102580#else
102581# define pTrigger 0
102582# define isView 0
102583#endif
102584#ifdef SQLITE_OMIT_VIEW
102585# undef isView
102586# define isView 0
102587#endif
102588
102589  /* If pTab is really a view, make sure it has been initialized.
102590  */
102591  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102592    goto delete_from_cleanup;
102593  }
102594
102595  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
102596    goto delete_from_cleanup;
102597  }
102598  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102599  assert( iDb<db->nDb );
102600  zDb = db->aDb[iDb].zName;
102601  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
102602  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
102603  if( rcauth==SQLITE_DENY ){
102604    goto delete_from_cleanup;
102605  }
102606  assert(!isView || pTrigger);
102607
102608  /* Assign cursor numbers to the table and all its indices.
102609  */
102610  assert( pTabList->nSrc==1 );
102611  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
102612  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
102613    pParse->nTab++;
102614  }
102615
102616  /* Start the view context
102617  */
102618  if( isView ){
102619    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102620  }
102621
102622  /* Begin generating code.
102623  */
102624  v = sqlite3GetVdbe(pParse);
102625  if( v==0 ){
102626    goto delete_from_cleanup;
102627  }
102628  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102629  sqlite3BeginWriteOperation(pParse, 1, iDb);
102630
102631  /* If we are trying to delete from a view, realize that view into
102632  ** an ephemeral table.
102633  */
102634#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102635  if( isView ){
102636    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
102637    iDataCur = iIdxCur = iTabCur;
102638  }
102639#endif
102640
102641  /* Resolve the column names in the WHERE clause.
102642  */
102643  memset(&sNC, 0, sizeof(sNC));
102644  sNC.pParse = pParse;
102645  sNC.pSrcList = pTabList;
102646  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102647    goto delete_from_cleanup;
102648  }
102649
102650  /* Initialize the counter of the number of rows deleted, if
102651  ** we are counting rows.
102652  */
102653  if( db->flags & SQLITE_CountRows ){
102654    memCnt = ++pParse->nMem;
102655    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
102656  }
102657
102658#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
102659  /* Special case: A DELETE without a WHERE clause deletes everything.
102660  ** It is easier just to erase the whole table. Prior to version 3.6.5,
102661  ** this optimization caused the row change count (the value returned by
102662  ** API function sqlite3_count_changes) to be set incorrectly.  */
102663  if( rcauth==SQLITE_OK
102664   && pWhere==0
102665   && !bComplex
102666   && !IsVirtual(pTab)
102667#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102668   && db->xPreUpdateCallback==0
102669#endif
102670  ){
102671    assert( !isView );
102672    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
102673    if( HasRowid(pTab) ){
102674      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
102675                        pTab->zName, P4_STATIC);
102676    }
102677    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102678      assert( pIdx->pSchema==pTab->pSchema );
102679      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
102680    }
102681  }else
102682#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
102683  {
102684    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
102685    if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
102686    wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
102687    if( HasRowid(pTab) ){
102688      /* For a rowid table, initialize the RowSet to an empty set */
102689      pPk = 0;
102690      nPk = 1;
102691      iRowSet = ++pParse->nMem;
102692      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
102693    }else{
102694      /* For a WITHOUT ROWID table, create an ephemeral table used to
102695      ** hold all primary keys for rows to be deleted. */
102696      pPk = sqlite3PrimaryKeyIndex(pTab);
102697      assert( pPk!=0 );
102698      nPk = pPk->nKeyCol;
102699      iPk = pParse->nMem+1;
102700      pParse->nMem += nPk;
102701      iEphCur = pParse->nTab++;
102702      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
102703      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
102704    }
102705
102706    /* Construct a query to find the rowid or primary key for every row
102707    ** to be deleted, based on the WHERE clause. Set variable eOnePass
102708    ** to indicate the strategy used to implement this delete:
102709    **
102710    **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
102711    **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
102712    **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
102713    */
102714    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
102715    if( pWInfo==0 ) goto delete_from_cleanup;
102716    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
102717    assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
102718    assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
102719
102720    /* Keep track of the number of rows to be deleted */
102721    if( db->flags & SQLITE_CountRows ){
102722      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
102723    }
102724
102725    /* Extract the rowid or primary key for the current row */
102726    if( pPk ){
102727      for(i=0; i<nPk; i++){
102728        assert( pPk->aiColumn[i]>=0 );
102729        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
102730                                        pPk->aiColumn[i], iPk+i);
102731      }
102732      iKey = iPk;
102733    }else{
102734      iKey = pParse->nMem + 1;
102735      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
102736      if( iKey>pParse->nMem ) pParse->nMem = iKey;
102737    }
102738
102739    if( eOnePass!=ONEPASS_OFF ){
102740      /* For ONEPASS, no need to store the rowid/primary-key. There is only
102741      ** one, so just keep it in its register(s) and fall through to the
102742      ** delete code.  */
102743      nKey = nPk; /* OP_Found will use an unpacked key */
102744      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
102745      if( aToOpen==0 ){
102746        sqlite3WhereEnd(pWInfo);
102747        goto delete_from_cleanup;
102748      }
102749      memset(aToOpen, 1, nIdx+1);
102750      aToOpen[nIdx+1] = 0;
102751      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
102752      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
102753      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
102754    }else{
102755      if( pPk ){
102756        /* Add the PK key for this row to the temporary table */
102757        iKey = ++pParse->nMem;
102758        nKey = 0;   /* Zero tells OP_Found to use a composite key */
102759        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
102760            sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
102761        sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
102762      }else{
102763        /* Add the rowid of the row to be deleted to the RowSet */
102764        nKey = 1;  /* OP_Seek always uses a single rowid */
102765        sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
102766      }
102767    }
102768
102769    /* If this DELETE cannot use the ONEPASS strategy, this is the
102770    ** end of the WHERE loop */
102771    if( eOnePass!=ONEPASS_OFF ){
102772      addrBypass = sqlite3VdbeMakeLabel(v);
102773    }else{
102774      sqlite3WhereEnd(pWInfo);
102775    }
102776
102777    /* Unless this is a view, open cursors for the table we are
102778    ** deleting from and all its indices. If this is a view, then the
102779    ** only effect this statement has is to fire the INSTEAD OF
102780    ** triggers.
102781    */
102782    if( !isView ){
102783      int iAddrOnce = 0;
102784      if( eOnePass==ONEPASS_MULTI ){
102785        iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
102786      }
102787      testcase( IsVirtual(pTab) );
102788      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
102789                                 iTabCur, aToOpen, &iDataCur, &iIdxCur);
102790      assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
102791      assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
102792      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
102793    }
102794
102795    /* Set up a loop over the rowids/primary-keys that were found in the
102796    ** where-clause loop above.
102797    */
102798    if( eOnePass!=ONEPASS_OFF ){
102799      assert( nKey==nPk );  /* OP_Found will use an unpacked key */
102800      if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
102801        assert( pPk!=0 || pTab->pSelect!=0 );
102802        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
102803        VdbeCoverage(v);
102804      }
102805    }else if( pPk ){
102806      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
102807      sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
102808      assert( nKey==0 );  /* OP_Found will use a composite key */
102809    }else{
102810      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
102811      VdbeCoverage(v);
102812      assert( nKey==1 );
102813    }
102814
102815    /* Delete the row */
102816#ifndef SQLITE_OMIT_VIRTUALTABLE
102817    if( IsVirtual(pTab) ){
102818      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102819      sqlite3VtabMakeWritable(pParse, pTab);
102820      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
102821      sqlite3VdbeChangeP5(v, OE_Abort);
102822      assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
102823      sqlite3MayAbort(pParse);
102824      if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
102825        pParse->isMultiWrite = 0;
102826      }
102827    }else
102828#endif
102829    {
102830      int count = (pParse->nested==0);    /* True to count changes */
102831      int iIdxNoSeek = -1;
102832      if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
102833        iIdxNoSeek = aiCurOnePass[1];
102834      }
102835      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
102836          iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
102837    }
102838
102839    /* End of the loop over all rowids/primary-keys. */
102840    if( eOnePass!=ONEPASS_OFF ){
102841      sqlite3VdbeResolveLabel(v, addrBypass);
102842      sqlite3WhereEnd(pWInfo);
102843    }else if( pPk ){
102844      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
102845      sqlite3VdbeJumpHere(v, addrLoop);
102846    }else{
102847      sqlite3VdbeGoto(v, addrLoop);
102848      sqlite3VdbeJumpHere(v, addrLoop);
102849    }
102850
102851    /* Close the cursors open on the table and its indexes. */
102852    if( !isView && !IsVirtual(pTab) ){
102853      if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
102854      for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
102855        sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
102856      }
102857    }
102858  } /* End non-truncate path */
102859
102860  /* Update the sqlite_sequence table by storing the content of the
102861  ** maximum rowid counter values recorded while inserting into
102862  ** autoincrement tables.
102863  */
102864  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102865    sqlite3AutoincrementEnd(pParse);
102866  }
102867
102868  /* Return the number of rows that were deleted. If this routine is
102869  ** generating code because of a call to sqlite3NestedParse(), do not
102870  ** invoke the callback function.
102871  */
102872  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
102873    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
102874    sqlite3VdbeSetNumCols(v, 1);
102875    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
102876  }
102877
102878delete_from_cleanup:
102879  sqlite3AuthContextPop(&sContext);
102880  sqlite3SrcListDelete(db, pTabList);
102881  sqlite3ExprDelete(db, pWhere);
102882  sqlite3DbFree(db, aToOpen);
102883  return;
102884}
102885/* Make sure "isView" and other macros defined above are undefined. Otherwise
102886** they may interfere with compilation of other functions in this file
102887** (or in another file, if this file becomes part of the amalgamation).  */
102888#ifdef isView
102889 #undef isView
102890#endif
102891#ifdef pTrigger
102892 #undef pTrigger
102893#endif
102894
102895/*
102896** This routine generates VDBE code that causes a single row of a
102897** single table to be deleted.  Both the original table entry and
102898** all indices are removed.
102899**
102900** Preconditions:
102901**
102902**   1.  iDataCur is an open cursor on the btree that is the canonical data
102903**       store for the table.  (This will be either the table itself,
102904**       in the case of a rowid table, or the PRIMARY KEY index in the case
102905**       of a WITHOUT ROWID table.)
102906**
102907**   2.  Read/write cursors for all indices of pTab must be open as
102908**       cursor number iIdxCur+i for the i-th index.
102909**
102910**   3.  The primary key for the row to be deleted must be stored in a
102911**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
102912**       that a search record formed from OP_MakeRecord is contained in the
102913**       single memory location iPk.
102914**
102915** eMode:
102916**   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
102917**   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
102918**   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
102919**   then this function must seek iDataCur to the entry identified by iPk
102920**   and nPk before reading from it.
102921**
102922**   If eMode is ONEPASS_MULTI, then this call is being made as part
102923**   of a ONEPASS delete that affects multiple rows. In this case, if
102924**   iIdxNoSeek is a valid cursor number (>=0), then its position should
102925**   be preserved following the delete operation. Or, if iIdxNoSeek is not
102926**   a valid cursor number, the position of iDataCur should be preserved
102927**   instead.
102928**
102929** iIdxNoSeek:
102930**   If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
102931**   index cursor (from within array of cursors starting at iIdxCur) that
102932**   already points to the index entry to be deleted.
102933*/
102934SQLITE_PRIVATE void sqlite3GenerateRowDelete(
102935  Parse *pParse,     /* Parsing context */
102936  Table *pTab,       /* Table containing the row to be deleted */
102937  Trigger *pTrigger, /* List of triggers to (potentially) fire */
102938  int iDataCur,      /* Cursor from which column data is extracted */
102939  int iIdxCur,       /* First index cursor */
102940  int iPk,           /* First memory cell containing the PRIMARY KEY */
102941  i16 nPk,           /* Number of PRIMARY KEY memory cells */
102942  u8 count,          /* If non-zero, increment the row change counter */
102943  u8 onconf,         /* Default ON CONFLICT policy for triggers */
102944  u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
102945  int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
102946){
102947  Vdbe *v = pParse->pVdbe;        /* Vdbe */
102948  int iOld = 0;                   /* First register in OLD.* array */
102949  int iLabel;                     /* Label resolved to end of generated code */
102950  u8 opSeek;                      /* Seek opcode */
102951
102952  /* Vdbe is guaranteed to have been allocated by this stage. */
102953  assert( v );
102954  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
102955                         iDataCur, iIdxCur, iPk, (int)nPk));
102956
102957  /* Seek cursor iCur to the row to delete. If this row no longer exists
102958  ** (this can happen if a trigger program has already deleted it), do
102959  ** not attempt to delete it or fire any DELETE triggers.  */
102960  iLabel = sqlite3VdbeMakeLabel(v);
102961  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
102962  if( eMode==ONEPASS_OFF ){
102963    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
102964    VdbeCoverageIf(v, opSeek==OP_NotExists);
102965    VdbeCoverageIf(v, opSeek==OP_NotFound);
102966  }
102967
102968  /* If there are any triggers to fire, allocate a range of registers to
102969  ** use for the old.* references in the triggers.  */
102970  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
102971    u32 mask;                     /* Mask of OLD.* columns in use */
102972    int iCol;                     /* Iterator used while populating OLD.* */
102973    int addrStart;                /* Start of BEFORE trigger programs */
102974
102975    /* TODO: Could use temporary registers here. Also could attempt to
102976    ** avoid copying the contents of the rowid register.  */
102977    mask = sqlite3TriggerColmask(
102978        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
102979    );
102980    mask |= sqlite3FkOldmask(pParse, pTab);
102981    iOld = pParse->nMem+1;
102982    pParse->nMem += (1 + pTab->nCol);
102983
102984    /* Populate the OLD.* pseudo-table register array. These values will be
102985    ** used by any BEFORE and AFTER triggers that exist.  */
102986    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
102987    for(iCol=0; iCol<pTab->nCol; iCol++){
102988      testcase( mask!=0xffffffff && iCol==31 );
102989      testcase( mask!=0xffffffff && iCol==32 );
102990      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
102991        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
102992      }
102993    }
102994
102995    /* Invoke BEFORE DELETE trigger programs. */
102996    addrStart = sqlite3VdbeCurrentAddr(v);
102997    sqlite3CodeRowTrigger(pParse, pTrigger,
102998        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
102999    );
103000
103001    /* If any BEFORE triggers were coded, then seek the cursor to the
103002    ** row to be deleted again. It may be that the BEFORE triggers moved
103003    ** the cursor or of already deleted the row that the cursor was
103004    ** pointing to.
103005    */
103006    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
103007      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
103008      VdbeCoverageIf(v, opSeek==OP_NotExists);
103009      VdbeCoverageIf(v, opSeek==OP_NotFound);
103010    }
103011
103012    /* Do FK processing. This call checks that any FK constraints that
103013    ** refer to this table (i.e. constraints attached to other tables)
103014    ** are not violated by deleting this row.  */
103015    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
103016  }
103017
103018  /* Delete the index and table entries. Skip this step if pTab is really
103019  ** a view (in which case the only effect of the DELETE statement is to
103020  ** fire the INSTEAD OF triggers).
103021  **
103022  ** If variable 'count' is non-zero, then this OP_Delete instruction should
103023  ** invoke the update-hook. The pre-update-hook, on the other hand should
103024  ** be invoked unless table pTab is a system table. The difference is that
103025  ** the update-hook is not invoked for rows removed by REPLACE, but the
103026  ** pre-update-hook is.
103027  */
103028  if( pTab->pSelect==0 ){
103029    u8 p5 = 0;
103030    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
103031    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
103032    sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
103033    if( eMode!=ONEPASS_OFF ){
103034      sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
103035    }
103036    if( iIdxNoSeek>=0 ){
103037      sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
103038    }
103039    if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
103040    sqlite3VdbeChangeP5(v, p5);
103041  }
103042
103043  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
103044  ** handle rows (possibly in other tables) that refer via a foreign key
103045  ** to the row just deleted. */
103046  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
103047
103048  /* Invoke AFTER DELETE trigger programs. */
103049  sqlite3CodeRowTrigger(pParse, pTrigger,
103050      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
103051  );
103052
103053  /* Jump here if the row had already been deleted before any BEFORE
103054  ** trigger programs were invoked. Or if a trigger program throws a
103055  ** RAISE(IGNORE) exception.  */
103056  sqlite3VdbeResolveLabel(v, iLabel);
103057  VdbeModuleComment((v, "END: GenRowDel()"));
103058}
103059
103060/*
103061** This routine generates VDBE code that causes the deletion of all
103062** index entries associated with a single row of a single table, pTab
103063**
103064** Preconditions:
103065**
103066**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
103067**       btree for the table pTab.  (This will be either the table itself
103068**       for rowid tables or to the primary key index for WITHOUT ROWID
103069**       tables.)
103070**
103071**   2.  Read/write cursors for all indices of pTab must be open as
103072**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
103073**       index is the 0-th index.)
103074**
103075**   3.  The "iDataCur" cursor must be already be positioned on the row
103076**       that is to be deleted.
103077*/
103078SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
103079  Parse *pParse,     /* Parsing and code generating context */
103080  Table *pTab,       /* Table containing the row to be deleted */
103081  int iDataCur,      /* Cursor of table holding data. */
103082  int iIdxCur,       /* First index cursor */
103083  int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
103084  int iIdxNoSeek     /* Do not delete from this cursor */
103085){
103086  int i;             /* Index loop counter */
103087  int r1 = -1;       /* Register holding an index key */
103088  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
103089  Index *pIdx;       /* Current index */
103090  Index *pPrior = 0; /* Prior index */
103091  Vdbe *v;           /* The prepared statement under construction */
103092  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
103093
103094  v = pParse->pVdbe;
103095  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
103096  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
103097    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
103098    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
103099    if( pIdx==pPk ) continue;
103100    if( iIdxCur+i==iIdxNoSeek ) continue;
103101    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
103102    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
103103        &iPartIdxLabel, pPrior, r1);
103104    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
103105        pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
103106    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
103107    pPrior = pIdx;
103108  }
103109}
103110
103111/*
103112** Generate code that will assemble an index key and stores it in register
103113** regOut.  The key with be for index pIdx which is an index on pTab.
103114** iCur is the index of a cursor open on the pTab table and pointing to
103115** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
103116** iCur must be the cursor of the PRIMARY KEY index.
103117**
103118** Return a register number which is the first in a block of
103119** registers that holds the elements of the index key.  The
103120** block of registers has already been deallocated by the time
103121** this routine returns.
103122**
103123** If *piPartIdxLabel is not NULL, fill it in with a label and jump
103124** to that label if pIdx is a partial index that should be skipped.
103125** The label should be resolved using sqlite3ResolvePartIdxLabel().
103126** A partial index should be skipped if its WHERE clause evaluates
103127** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
103128** will be set to zero which is an empty label that is ignored by
103129** sqlite3ResolvePartIdxLabel().
103130**
103131** The pPrior and regPrior parameters are used to implement a cache to
103132** avoid unnecessary register loads.  If pPrior is not NULL, then it is
103133** a pointer to a different index for which an index key has just been
103134** computed into register regPrior.  If the current pIdx index is generating
103135** its key into the same sequence of registers and if pPrior and pIdx share
103136** a column in common, then the register corresponding to that column already
103137** holds the correct value and the loading of that register is skipped.
103138** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
103139** on a table with multiple indices, and especially with the ROWID or
103140** PRIMARY KEY columns of the index.
103141*/
103142SQLITE_PRIVATE int sqlite3GenerateIndexKey(
103143  Parse *pParse,       /* Parsing context */
103144  Index *pIdx,         /* The index for which to generate a key */
103145  int iDataCur,        /* Cursor number from which to take column data */
103146  int regOut,          /* Put the new key into this register if not 0 */
103147  int prefixOnly,      /* Compute only a unique prefix of the key */
103148  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
103149  Index *pPrior,       /* Previously generated index key */
103150  int regPrior         /* Register holding previous generated key */
103151){
103152  Vdbe *v = pParse->pVdbe;
103153  int j;
103154  int regBase;
103155  int nCol;
103156
103157  if( piPartIdxLabel ){
103158    if( pIdx->pPartIdxWhere ){
103159      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
103160      pParse->iSelfTab = iDataCur;
103161      sqlite3ExprCachePush(pParse);
103162      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
103163                            SQLITE_JUMPIFNULL);
103164    }else{
103165      *piPartIdxLabel = 0;
103166    }
103167  }
103168  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
103169  regBase = sqlite3GetTempRange(pParse, nCol);
103170  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
103171  for(j=0; j<nCol; j++){
103172    if( pPrior
103173     && pPrior->aiColumn[j]==pIdx->aiColumn[j]
103174     && pPrior->aiColumn[j]!=XN_EXPR
103175    ){
103176      /* This column was already computed by the previous index */
103177      continue;
103178    }
103179    sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
103180    /* If the column affinity is REAL but the number is an integer, then it
103181    ** might be stored in the table as an integer (using a compact
103182    ** representation) then converted to REAL by an OP_RealAffinity opcode.
103183    ** But we are getting ready to store this value back into an index, where
103184    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
103185    ** opcode if it is present */
103186    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
103187  }
103188  if( regOut ){
103189    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
103190  }
103191  sqlite3ReleaseTempRange(pParse, regBase, nCol);
103192  return regBase;
103193}
103194
103195/*
103196** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
103197** because it was a partial index, then this routine should be called to
103198** resolve that label.
103199*/
103200SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
103201  if( iLabel ){
103202    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
103203    sqlite3ExprCachePop(pParse);
103204  }
103205}
103206
103207/************** End of delete.c **********************************************/
103208/************** Begin file func.c ********************************************/
103209/*
103210** 2002 February 23
103211**
103212** The author disclaims copyright to this source code.  In place of
103213** a legal notice, here is a blessing:
103214**
103215**    May you do good and not evil.
103216**    May you find forgiveness for yourself and forgive others.
103217**    May you share freely, never taking more than you give.
103218**
103219*************************************************************************
103220** This file contains the C-language implementations for many of the SQL
103221** functions of SQLite.  (Some function, and in particular the date and
103222** time functions, are implemented separately.)
103223*/
103224/* #include "sqliteInt.h" */
103225/* #include <stdlib.h> */
103226/* #include <assert.h> */
103227/* #include "vdbeInt.h" */
103228
103229/*
103230** Return the collating function associated with a function.
103231*/
103232static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
103233  VdbeOp *pOp;
103234  assert( context->pVdbe!=0 );
103235  pOp = &context->pVdbe->aOp[context->iOp-1];
103236  assert( pOp->opcode==OP_CollSeq );
103237  assert( pOp->p4type==P4_COLLSEQ );
103238  return pOp->p4.pColl;
103239}
103240
103241/*
103242** Indicate that the accumulator load should be skipped on this
103243** iteration of the aggregate loop.
103244*/
103245static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
103246  context->skipFlag = 1;
103247}
103248
103249/*
103250** Implementation of the non-aggregate min() and max() functions
103251*/
103252static void minmaxFunc(
103253  sqlite3_context *context,
103254  int argc,
103255  sqlite3_value **argv
103256){
103257  int i;
103258  int mask;    /* 0 for min() or 0xffffffff for max() */
103259  int iBest;
103260  CollSeq *pColl;
103261
103262  assert( argc>1 );
103263  mask = sqlite3_user_data(context)==0 ? 0 : -1;
103264  pColl = sqlite3GetFuncCollSeq(context);
103265  assert( pColl );
103266  assert( mask==-1 || mask==0 );
103267  iBest = 0;
103268  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
103269  for(i=1; i<argc; i++){
103270    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
103271    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
103272      testcase( mask==0 );
103273      iBest = i;
103274    }
103275  }
103276  sqlite3_result_value(context, argv[iBest]);
103277}
103278
103279/*
103280** Return the type of the argument.
103281*/
103282static void typeofFunc(
103283  sqlite3_context *context,
103284  int NotUsed,
103285  sqlite3_value **argv
103286){
103287  const char *z = 0;
103288  UNUSED_PARAMETER(NotUsed);
103289  switch( sqlite3_value_type(argv[0]) ){
103290    case SQLITE_INTEGER: z = "integer"; break;
103291    case SQLITE_TEXT:    z = "text";    break;
103292    case SQLITE_FLOAT:   z = "real";    break;
103293    case SQLITE_BLOB:    z = "blob";    break;
103294    default:             z = "null";    break;
103295  }
103296  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
103297}
103298
103299
103300/*
103301** Implementation of the length() function
103302*/
103303static void lengthFunc(
103304  sqlite3_context *context,
103305  int argc,
103306  sqlite3_value **argv
103307){
103308  int len;
103309
103310  assert( argc==1 );
103311  UNUSED_PARAMETER(argc);
103312  switch( sqlite3_value_type(argv[0]) ){
103313    case SQLITE_BLOB:
103314    case SQLITE_INTEGER:
103315    case SQLITE_FLOAT: {
103316      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
103317      break;
103318    }
103319    case SQLITE_TEXT: {
103320      const unsigned char *z = sqlite3_value_text(argv[0]);
103321      if( z==0 ) return;
103322      len = 0;
103323      while( *z ){
103324        len++;
103325        SQLITE_SKIP_UTF8(z);
103326      }
103327      sqlite3_result_int(context, len);
103328      break;
103329    }
103330    default: {
103331      sqlite3_result_null(context);
103332      break;
103333    }
103334  }
103335}
103336
103337/*
103338** Implementation of the abs() function.
103339**
103340** IMP: R-23979-26855 The abs(X) function returns the absolute value of
103341** the numeric argument X.
103342*/
103343static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103344  assert( argc==1 );
103345  UNUSED_PARAMETER(argc);
103346  switch( sqlite3_value_type(argv[0]) ){
103347    case SQLITE_INTEGER: {
103348      i64 iVal = sqlite3_value_int64(argv[0]);
103349      if( iVal<0 ){
103350        if( iVal==SMALLEST_INT64 ){
103351          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
103352          ** then abs(X) throws an integer overflow error since there is no
103353          ** equivalent positive 64-bit two complement value. */
103354          sqlite3_result_error(context, "integer overflow", -1);
103355          return;
103356        }
103357        iVal = -iVal;
103358      }
103359      sqlite3_result_int64(context, iVal);
103360      break;
103361    }
103362    case SQLITE_NULL: {
103363      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
103364      sqlite3_result_null(context);
103365      break;
103366    }
103367    default: {
103368      /* Because sqlite3_value_double() returns 0.0 if the argument is not
103369      ** something that can be converted into a number, we have:
103370      ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
103371      ** that cannot be converted to a numeric value.
103372      */
103373      double rVal = sqlite3_value_double(argv[0]);
103374      if( rVal<0 ) rVal = -rVal;
103375      sqlite3_result_double(context, rVal);
103376      break;
103377    }
103378  }
103379}
103380
103381/*
103382** Implementation of the instr() function.
103383**
103384** instr(haystack,needle) finds the first occurrence of needle
103385** in haystack and returns the number of previous characters plus 1,
103386** or 0 if needle does not occur within haystack.
103387**
103388** If both haystack and needle are BLOBs, then the result is one more than
103389** the number of bytes in haystack prior to the first occurrence of needle,
103390** or 0 if needle never occurs in haystack.
103391*/
103392static void instrFunc(
103393  sqlite3_context *context,
103394  int argc,
103395  sqlite3_value **argv
103396){
103397  const unsigned char *zHaystack;
103398  const unsigned char *zNeedle;
103399  int nHaystack;
103400  int nNeedle;
103401  int typeHaystack, typeNeedle;
103402  int N = 1;
103403  int isText;
103404
103405  UNUSED_PARAMETER(argc);
103406  typeHaystack = sqlite3_value_type(argv[0]);
103407  typeNeedle = sqlite3_value_type(argv[1]);
103408  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
103409  nHaystack = sqlite3_value_bytes(argv[0]);
103410  nNeedle = sqlite3_value_bytes(argv[1]);
103411  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
103412    zHaystack = sqlite3_value_blob(argv[0]);
103413    zNeedle = sqlite3_value_blob(argv[1]);
103414    isText = 0;
103415  }else{
103416    zHaystack = sqlite3_value_text(argv[0]);
103417    zNeedle = sqlite3_value_text(argv[1]);
103418    isText = 1;
103419  }
103420  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
103421    N++;
103422    do{
103423      nHaystack--;
103424      zHaystack++;
103425    }while( isText && (zHaystack[0]&0xc0)==0x80 );
103426  }
103427  if( nNeedle>nHaystack ) N = 0;
103428  sqlite3_result_int(context, N);
103429}
103430
103431/*
103432** Implementation of the printf() function.
103433*/
103434static void printfFunc(
103435  sqlite3_context *context,
103436  int argc,
103437  sqlite3_value **argv
103438){
103439  PrintfArguments x;
103440  StrAccum str;
103441  const char *zFormat;
103442  int n;
103443  sqlite3 *db = sqlite3_context_db_handle(context);
103444
103445  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
103446    x.nArg = argc-1;
103447    x.nUsed = 0;
103448    x.apArg = argv+1;
103449    sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
103450    str.printfFlags = SQLITE_PRINTF_SQLFUNC;
103451    sqlite3XPrintf(&str, zFormat, &x);
103452    n = str.nChar;
103453    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
103454                        SQLITE_DYNAMIC);
103455  }
103456}
103457
103458/*
103459** Implementation of the substr() function.
103460**
103461** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
103462** p1 is 1-indexed.  So substr(x,1,1) returns the first character
103463** of x.  If x is text, then we actually count UTF-8 characters.
103464** If x is a blob, then we count bytes.
103465**
103466** If p1 is negative, then we begin abs(p1) from the end of x[].
103467**
103468** If p2 is negative, return the p2 characters preceding p1.
103469*/
103470static void substrFunc(
103471  sqlite3_context *context,
103472  int argc,
103473  sqlite3_value **argv
103474){
103475  const unsigned char *z;
103476  const unsigned char *z2;
103477  int len;
103478  int p0type;
103479  i64 p1, p2;
103480  int negP2 = 0;
103481
103482  assert( argc==3 || argc==2 );
103483  if( sqlite3_value_type(argv[1])==SQLITE_NULL
103484   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
103485  ){
103486    return;
103487  }
103488  p0type = sqlite3_value_type(argv[0]);
103489  p1 = sqlite3_value_int(argv[1]);
103490  if( p0type==SQLITE_BLOB ){
103491    len = sqlite3_value_bytes(argv[0]);
103492    z = sqlite3_value_blob(argv[0]);
103493    if( z==0 ) return;
103494    assert( len==sqlite3_value_bytes(argv[0]) );
103495  }else{
103496    z = sqlite3_value_text(argv[0]);
103497    if( z==0 ) return;
103498    len = 0;
103499    if( p1<0 ){
103500      for(z2=z; *z2; len++){
103501        SQLITE_SKIP_UTF8(z2);
103502      }
103503    }
103504  }
103505#ifdef SQLITE_SUBSTR_COMPATIBILITY
103506  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
103507  ** as substr(X,1,N) - it returns the first N characters of X.  This
103508  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
103509  ** from 2009-02-02 for compatibility of applications that exploited the
103510  ** old buggy behavior. */
103511  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
103512#endif
103513  if( argc==3 ){
103514    p2 = sqlite3_value_int(argv[2]);
103515    if( p2<0 ){
103516      p2 = -p2;
103517      negP2 = 1;
103518    }
103519  }else{
103520    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
103521  }
103522  if( p1<0 ){
103523    p1 += len;
103524    if( p1<0 ){
103525      p2 += p1;
103526      if( p2<0 ) p2 = 0;
103527      p1 = 0;
103528    }
103529  }else if( p1>0 ){
103530    p1--;
103531  }else if( p2>0 ){
103532    p2--;
103533  }
103534  if( negP2 ){
103535    p1 -= p2;
103536    if( p1<0 ){
103537      p2 += p1;
103538      p1 = 0;
103539    }
103540  }
103541  assert( p1>=0 && p2>=0 );
103542  if( p0type!=SQLITE_BLOB ){
103543    while( *z && p1 ){
103544      SQLITE_SKIP_UTF8(z);
103545      p1--;
103546    }
103547    for(z2=z; *z2 && p2; p2--){
103548      SQLITE_SKIP_UTF8(z2);
103549    }
103550    sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
103551                          SQLITE_UTF8);
103552  }else{
103553    if( p1+p2>len ){
103554      p2 = len-p1;
103555      if( p2<0 ) p2 = 0;
103556    }
103557    sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
103558  }
103559}
103560
103561/*
103562** Implementation of the round() function
103563*/
103564#ifndef SQLITE_OMIT_FLOATING_POINT
103565static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103566  int n = 0;
103567  double r;
103568  char *zBuf;
103569  assert( argc==1 || argc==2 );
103570  if( argc==2 ){
103571    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
103572    n = sqlite3_value_int(argv[1]);
103573    if( n>30 ) n = 30;
103574    if( n<0 ) n = 0;
103575  }
103576  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
103577  r = sqlite3_value_double(argv[0]);
103578  /* If Y==0 and X will fit in a 64-bit int,
103579  ** handle the rounding directly,
103580  ** otherwise use printf.
103581  */
103582  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
103583    r = (double)((sqlite_int64)(r+0.5));
103584  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
103585    r = -(double)((sqlite_int64)((-r)+0.5));
103586  }else{
103587    zBuf = sqlite3_mprintf("%.*f",n,r);
103588    if( zBuf==0 ){
103589      sqlite3_result_error_nomem(context);
103590      return;
103591    }
103592    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
103593    sqlite3_free(zBuf);
103594  }
103595  sqlite3_result_double(context, r);
103596}
103597#endif
103598
103599/*
103600** Allocate nByte bytes of space using sqlite3Malloc(). If the
103601** allocation fails, call sqlite3_result_error_nomem() to notify
103602** the database handle that malloc() has failed and return NULL.
103603** If nByte is larger than the maximum string or blob length, then
103604** raise an SQLITE_TOOBIG exception and return NULL.
103605*/
103606static void *contextMalloc(sqlite3_context *context, i64 nByte){
103607  char *z;
103608  sqlite3 *db = sqlite3_context_db_handle(context);
103609  assert( nByte>0 );
103610  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
103611  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
103612  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
103613    sqlite3_result_error_toobig(context);
103614    z = 0;
103615  }else{
103616    z = sqlite3Malloc(nByte);
103617    if( !z ){
103618      sqlite3_result_error_nomem(context);
103619    }
103620  }
103621  return z;
103622}
103623
103624/*
103625** Implementation of the upper() and lower() SQL functions.
103626*/
103627static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103628  char *z1;
103629  const char *z2;
103630  int i, n;
103631  UNUSED_PARAMETER(argc);
103632  z2 = (char*)sqlite3_value_text(argv[0]);
103633  n = sqlite3_value_bytes(argv[0]);
103634  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103635  assert( z2==(char*)sqlite3_value_text(argv[0]) );
103636  if( z2 ){
103637    z1 = contextMalloc(context, ((i64)n)+1);
103638    if( z1 ){
103639      for(i=0; i<n; i++){
103640        z1[i] = (char)sqlite3Toupper(z2[i]);
103641      }
103642      sqlite3_result_text(context, z1, n, sqlite3_free);
103643    }
103644  }
103645}
103646static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103647  char *z1;
103648  const char *z2;
103649  int i, n;
103650  UNUSED_PARAMETER(argc);
103651  z2 = (char*)sqlite3_value_text(argv[0]);
103652  n = sqlite3_value_bytes(argv[0]);
103653  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103654  assert( z2==(char*)sqlite3_value_text(argv[0]) );
103655  if( z2 ){
103656    z1 = contextMalloc(context, ((i64)n)+1);
103657    if( z1 ){
103658      for(i=0; i<n; i++){
103659        z1[i] = sqlite3Tolower(z2[i]);
103660      }
103661      sqlite3_result_text(context, z1, n, sqlite3_free);
103662    }
103663  }
103664}
103665
103666/*
103667** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
103668** as VDBE code so that unused argument values do not have to be computed.
103669** However, we still need some kind of function implementation for this
103670** routines in the function table.  The noopFunc macro provides this.
103671** noopFunc will never be called so it doesn't matter what the implementation
103672** is.  We might as well use the "version()" function as a substitute.
103673*/
103674#define noopFunc versionFunc   /* Substitute function - never called */
103675
103676/*
103677** Implementation of random().  Return a random integer.
103678*/
103679static void randomFunc(
103680  sqlite3_context *context,
103681  int NotUsed,
103682  sqlite3_value **NotUsed2
103683){
103684  sqlite_int64 r;
103685  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103686  sqlite3_randomness(sizeof(r), &r);
103687  if( r<0 ){
103688    /* We need to prevent a random number of 0x8000000000000000
103689    ** (or -9223372036854775808) since when you do abs() of that
103690    ** number of you get the same value back again.  To do this
103691    ** in a way that is testable, mask the sign bit off of negative
103692    ** values, resulting in a positive value.  Then take the
103693    ** 2s complement of that positive value.  The end result can
103694    ** therefore be no less than -9223372036854775807.
103695    */
103696    r = -(r & LARGEST_INT64);
103697  }
103698  sqlite3_result_int64(context, r);
103699}
103700
103701/*
103702** Implementation of randomblob(N).  Return a random blob
103703** that is N bytes long.
103704*/
103705static void randomBlob(
103706  sqlite3_context *context,
103707  int argc,
103708  sqlite3_value **argv
103709){
103710  int n;
103711  unsigned char *p;
103712  assert( argc==1 );
103713  UNUSED_PARAMETER(argc);
103714  n = sqlite3_value_int(argv[0]);
103715  if( n<1 ){
103716    n = 1;
103717  }
103718  p = contextMalloc(context, n);
103719  if( p ){
103720    sqlite3_randomness(n, p);
103721    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
103722  }
103723}
103724
103725/*
103726** Implementation of the last_insert_rowid() SQL function.  The return
103727** value is the same as the sqlite3_last_insert_rowid() API function.
103728*/
103729static void last_insert_rowid(
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  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
103737  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
103738  ** function. */
103739  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
103740}
103741
103742/*
103743** Implementation of the changes() SQL function.
103744**
103745** IMP: R-62073-11209 The changes() SQL function is a wrapper
103746** around the sqlite3_changes() C/C++ function and hence follows the same
103747** rules for counting changes.
103748*/
103749static void changes(
103750  sqlite3_context *context,
103751  int NotUsed,
103752  sqlite3_value **NotUsed2
103753){
103754  sqlite3 *db = sqlite3_context_db_handle(context);
103755  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103756  sqlite3_result_int(context, sqlite3_changes(db));
103757}
103758
103759/*
103760** Implementation of the total_changes() SQL function.  The return value is
103761** the same as the sqlite3_total_changes() API function.
103762*/
103763static void total_changes(
103764  sqlite3_context *context,
103765  int NotUsed,
103766  sqlite3_value **NotUsed2
103767){
103768  sqlite3 *db = sqlite3_context_db_handle(context);
103769  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103770  /* IMP: R-52756-41993 This function is a wrapper around the
103771  ** sqlite3_total_changes() C/C++ interface. */
103772  sqlite3_result_int(context, sqlite3_total_changes(db));
103773}
103774
103775/*
103776** A structure defining how to do GLOB-style comparisons.
103777*/
103778struct compareInfo {
103779  u8 matchAll;          /* "*" or "%" */
103780  u8 matchOne;          /* "?" or "_" */
103781  u8 matchSet;          /* "[" or 0 */
103782  u8 noCase;            /* true to ignore case differences */
103783};
103784
103785/*
103786** For LIKE and GLOB matching on EBCDIC machines, assume that every
103787** character is exactly one byte in size.  Also, provde the Utf8Read()
103788** macro for fast reading of the next character in the common case where
103789** the next character is ASCII.
103790*/
103791#if defined(SQLITE_EBCDIC)
103792# define sqlite3Utf8Read(A)        (*((*A)++))
103793# define Utf8Read(A)               (*(A++))
103794#else
103795# define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
103796#endif
103797
103798static const struct compareInfo globInfo = { '*', '?', '[', 0 };
103799/* The correct SQL-92 behavior is for the LIKE operator to ignore
103800** case.  Thus  'a' LIKE 'A' would be true. */
103801static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
103802/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
103803** is case sensitive causing 'a' LIKE 'A' to be false */
103804static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
103805
103806/*
103807** Compare two UTF-8 strings for equality where the first string can
103808** potentially be a "glob" or "like" expression.  Return true (1) if they
103809** are the same and false (0) if they are different.
103810**
103811** Globbing rules:
103812**
103813**      '*'       Matches any sequence of zero or more characters.
103814**
103815**      '?'       Matches exactly one character.
103816**
103817**     [...]      Matches one character from the enclosed list of
103818**                characters.
103819**
103820**     [^...]     Matches one character not in the enclosed list.
103821**
103822** With the [...] and [^...] matching, a ']' character can be included
103823** in the list by making it the first character after '[' or '^'.  A
103824** range of characters can be specified using '-'.  Example:
103825** "[a-z]" matches any single lower-case letter.  To match a '-', make
103826** it the last character in the list.
103827**
103828** Like matching rules:
103829**
103830**      '%'       Matches any sequence of zero or more characters
103831**
103832***     '_'       Matches any one character
103833**
103834**      Ec        Where E is the "esc" character and c is any other
103835**                character, including '%', '_', and esc, match exactly c.
103836**
103837** The comments within this routine usually assume glob matching.
103838**
103839** This routine is usually quick, but can be N**2 in the worst case.
103840*/
103841static int patternCompare(
103842  const u8 *zPattern,              /* The glob pattern */
103843  const u8 *zString,               /* The string to compare against the glob */
103844  const struct compareInfo *pInfo, /* Information about how to do the compare */
103845  u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
103846){
103847  u32 c, c2;                       /* Next pattern and input string chars */
103848  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
103849  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
103850  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
103851  const u8 *zEscaped = 0;          /* One past the last escaped input char */
103852
103853  while( (c = Utf8Read(zPattern))!=0 ){
103854    if( c==matchAll ){  /* Match "*" */
103855      /* Skip over multiple "*" characters in the pattern.  If there
103856      ** are also "?" characters, skip those as well, but consume a
103857      ** single character of the input string for each "?" skipped */
103858      while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
103859        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
103860          return 0;
103861        }
103862      }
103863      if( c==0 ){
103864        return 1;   /* "*" at the end of the pattern matches */
103865      }else if( c==matchOther ){
103866        if( pInfo->matchSet==0 ){
103867          c = sqlite3Utf8Read(&zPattern);
103868          if( c==0 ) return 0;
103869        }else{
103870          /* "[...]" immediately follows the "*".  We have to do a slow
103871          ** recursive search in this case, but it is an unusual case. */
103872          assert( matchOther<0x80 );  /* '[' is a single-byte character */
103873          while( *zString
103874                 && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
103875            SQLITE_SKIP_UTF8(zString);
103876          }
103877          return *zString!=0;
103878        }
103879      }
103880
103881      /* At this point variable c contains the first character of the
103882      ** pattern string past the "*".  Search in the input string for the
103883      ** first matching character and recursively contine the match from
103884      ** that point.
103885      **
103886      ** For a case-insensitive search, set variable cx to be the same as
103887      ** c but in the other case and search the input string for either
103888      ** c or cx.
103889      */
103890      if( c<=0x80 ){
103891        u32 cx;
103892        if( noCase ){
103893          cx = sqlite3Toupper(c);
103894          c = sqlite3Tolower(c);
103895        }else{
103896          cx = c;
103897        }
103898        while( (c2 = *(zString++))!=0 ){
103899          if( c2!=c && c2!=cx ) continue;
103900          if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103901        }
103902      }else{
103903        while( (c2 = Utf8Read(zString))!=0 ){
103904          if( c2!=c ) continue;
103905          if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103906        }
103907      }
103908      return 0;
103909    }
103910    if( c==matchOther ){
103911      if( pInfo->matchSet==0 ){
103912        c = sqlite3Utf8Read(&zPattern);
103913        if( c==0 ) return 0;
103914        zEscaped = zPattern;
103915      }else{
103916        u32 prior_c = 0;
103917        int seen = 0;
103918        int invert = 0;
103919        c = sqlite3Utf8Read(&zString);
103920        if( c==0 ) return 0;
103921        c2 = sqlite3Utf8Read(&zPattern);
103922        if( c2=='^' ){
103923          invert = 1;
103924          c2 = sqlite3Utf8Read(&zPattern);
103925        }
103926        if( c2==']' ){
103927          if( c==']' ) seen = 1;
103928          c2 = sqlite3Utf8Read(&zPattern);
103929        }
103930        while( c2 && c2!=']' ){
103931          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
103932            c2 = sqlite3Utf8Read(&zPattern);
103933            if( c>=prior_c && c<=c2 ) seen = 1;
103934            prior_c = 0;
103935          }else{
103936            if( c==c2 ){
103937              seen = 1;
103938            }
103939            prior_c = c2;
103940          }
103941          c2 = sqlite3Utf8Read(&zPattern);
103942        }
103943        if( c2==0 || (seen ^ invert)==0 ){
103944          return 0;
103945        }
103946        continue;
103947      }
103948    }
103949    c2 = Utf8Read(zString);
103950    if( c==c2 ) continue;
103951    if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
103952      continue;
103953    }
103954    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
103955    return 0;
103956  }
103957  return *zString==0;
103958}
103959
103960/*
103961** The sqlite3_strglob() interface.
103962*/
103963SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
103964  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
103965}
103966
103967/*
103968** The sqlite3_strlike() interface.
103969*/
103970SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
103971  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
103972}
103973
103974/*
103975** Count the number of times that the LIKE operator (or GLOB which is
103976** just a variation of LIKE) gets called.  This is used for testing
103977** only.
103978*/
103979#ifdef SQLITE_TEST
103980SQLITE_API int sqlite3_like_count = 0;
103981#endif
103982
103983
103984/*
103985** Implementation of the like() SQL function.  This function implements
103986** the build-in LIKE operator.  The first argument to the function is the
103987** pattern and the second argument is the string.  So, the SQL statements:
103988**
103989**       A LIKE B
103990**
103991** is implemented as like(B,A).
103992**
103993** This same function (with a different compareInfo structure) computes
103994** the GLOB operator.
103995*/
103996static void likeFunc(
103997  sqlite3_context *context,
103998  int argc,
103999  sqlite3_value **argv
104000){
104001  const unsigned char *zA, *zB;
104002  u32 escape;
104003  int nPat;
104004  sqlite3 *db = sqlite3_context_db_handle(context);
104005  struct compareInfo *pInfo = sqlite3_user_data(context);
104006
104007#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
104008  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
104009   || sqlite3_value_type(argv[1])==SQLITE_BLOB
104010  ){
104011#ifdef SQLITE_TEST
104012    sqlite3_like_count++;
104013#endif
104014    sqlite3_result_int(context, 0);
104015    return;
104016  }
104017#endif
104018  zB = sqlite3_value_text(argv[0]);
104019  zA = sqlite3_value_text(argv[1]);
104020
104021  /* Limit the length of the LIKE or GLOB pattern to avoid problems
104022  ** of deep recursion and N*N behavior in patternCompare().
104023  */
104024  nPat = sqlite3_value_bytes(argv[0]);
104025  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
104026  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
104027  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
104028    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
104029    return;
104030  }
104031  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
104032
104033  if( argc==3 ){
104034    /* The escape character string must consist of a single UTF-8 character.
104035    ** Otherwise, return an error.
104036    */
104037    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
104038    if( zEsc==0 ) return;
104039    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
104040      sqlite3_result_error(context,
104041          "ESCAPE expression must be a single character", -1);
104042      return;
104043    }
104044    escape = sqlite3Utf8Read(&zEsc);
104045  }else{
104046    escape = pInfo->matchSet;
104047  }
104048  if( zA && zB ){
104049#ifdef SQLITE_TEST
104050    sqlite3_like_count++;
104051#endif
104052    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
104053  }
104054}
104055
104056/*
104057** Implementation of the NULLIF(x,y) function.  The result is the first
104058** argument if the arguments are different.  The result is NULL if the
104059** arguments are equal to each other.
104060*/
104061static void nullifFunc(
104062  sqlite3_context *context,
104063  int NotUsed,
104064  sqlite3_value **argv
104065){
104066  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104067  UNUSED_PARAMETER(NotUsed);
104068  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
104069    sqlite3_result_value(context, argv[0]);
104070  }
104071}
104072
104073/*
104074** Implementation of the sqlite_version() function.  The result is the version
104075** of the SQLite library that is running.
104076*/
104077static void versionFunc(
104078  sqlite3_context *context,
104079  int NotUsed,
104080  sqlite3_value **NotUsed2
104081){
104082  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104083  /* IMP: R-48699-48617 This function is an SQL wrapper around the
104084  ** sqlite3_libversion() C-interface. */
104085  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
104086}
104087
104088/*
104089** Implementation of the sqlite_source_id() function. The result is a string
104090** that identifies the particular version of the source code used to build
104091** SQLite.
104092*/
104093static void sourceidFunc(
104094  sqlite3_context *context,
104095  int NotUsed,
104096  sqlite3_value **NotUsed2
104097){
104098  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104099  /* IMP: R-24470-31136 This function is an SQL wrapper around the
104100  ** sqlite3_sourceid() C interface. */
104101  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
104102}
104103
104104/*
104105** Implementation of the sqlite_log() function.  This is a wrapper around
104106** sqlite3_log().  The return value is NULL.  The function exists purely for
104107** its side-effects.
104108*/
104109static void errlogFunc(
104110  sqlite3_context *context,
104111  int argc,
104112  sqlite3_value **argv
104113){
104114  UNUSED_PARAMETER(argc);
104115  UNUSED_PARAMETER(context);
104116  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
104117}
104118
104119/*
104120** Implementation of the sqlite_compileoption_used() function.
104121** The result is an integer that identifies if the compiler option
104122** was used to build SQLite.
104123*/
104124#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104125static void compileoptionusedFunc(
104126  sqlite3_context *context,
104127  int argc,
104128  sqlite3_value **argv
104129){
104130  const char *zOptName;
104131  assert( argc==1 );
104132  UNUSED_PARAMETER(argc);
104133  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
104134  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
104135  ** function.
104136  */
104137  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
104138    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
104139  }
104140}
104141#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104142
104143/*
104144** Implementation of the sqlite_compileoption_get() function.
104145** The result is a string that identifies the compiler options
104146** used to build SQLite.
104147*/
104148#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104149static void compileoptiongetFunc(
104150  sqlite3_context *context,
104151  int argc,
104152  sqlite3_value **argv
104153){
104154  int n;
104155  assert( argc==1 );
104156  UNUSED_PARAMETER(argc);
104157  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
104158  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
104159  */
104160  n = sqlite3_value_int(argv[0]);
104161  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
104162}
104163#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104164
104165/* Array for converting from half-bytes (nybbles) into ASCII hex
104166** digits. */
104167static const char hexdigits[] = {
104168  '0', '1', '2', '3', '4', '5', '6', '7',
104169  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
104170};
104171
104172/*
104173** Implementation of the QUOTE() function.  This function takes a single
104174** argument.  If the argument is numeric, the return value is the same as
104175** the argument.  If the argument is NULL, the return value is the string
104176** "NULL".  Otherwise, the argument is enclosed in single quotes with
104177** single-quote escapes.
104178*/
104179static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104180  assert( argc==1 );
104181  UNUSED_PARAMETER(argc);
104182  switch( sqlite3_value_type(argv[0]) ){
104183    case SQLITE_FLOAT: {
104184      double r1, r2;
104185      char zBuf[50];
104186      r1 = sqlite3_value_double(argv[0]);
104187      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
104188      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
104189      if( r1!=r2 ){
104190        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
104191      }
104192      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
104193      break;
104194    }
104195    case SQLITE_INTEGER: {
104196      sqlite3_result_value(context, argv[0]);
104197      break;
104198    }
104199    case SQLITE_BLOB: {
104200      char *zText = 0;
104201      char const *zBlob = sqlite3_value_blob(argv[0]);
104202      int nBlob = sqlite3_value_bytes(argv[0]);
104203      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
104204      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
104205      if( zText ){
104206        int i;
104207        for(i=0; i<nBlob; i++){
104208          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
104209          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
104210        }
104211        zText[(nBlob*2)+2] = '\'';
104212        zText[(nBlob*2)+3] = '\0';
104213        zText[0] = 'X';
104214        zText[1] = '\'';
104215        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
104216        sqlite3_free(zText);
104217      }
104218      break;
104219    }
104220    case SQLITE_TEXT: {
104221      int i,j;
104222      u64 n;
104223      const unsigned char *zArg = sqlite3_value_text(argv[0]);
104224      char *z;
104225
104226      if( zArg==0 ) return;
104227      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
104228      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
104229      if( z ){
104230        z[0] = '\'';
104231        for(i=0, j=1; zArg[i]; i++){
104232          z[j++] = zArg[i];
104233          if( zArg[i]=='\'' ){
104234            z[j++] = '\'';
104235          }
104236        }
104237        z[j++] = '\'';
104238        z[j] = 0;
104239        sqlite3_result_text(context, z, j, sqlite3_free);
104240      }
104241      break;
104242    }
104243    default: {
104244      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
104245      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
104246      break;
104247    }
104248  }
104249}
104250
104251/*
104252** The unicode() function.  Return the integer unicode code-point value
104253** for the first character of the input string.
104254*/
104255static void unicodeFunc(
104256  sqlite3_context *context,
104257  int argc,
104258  sqlite3_value **argv
104259){
104260  const unsigned char *z = sqlite3_value_text(argv[0]);
104261  (void)argc;
104262  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
104263}
104264
104265/*
104266** The char() function takes zero or more arguments, each of which is
104267** an integer.  It constructs a string where each character of the string
104268** is the unicode character for the corresponding integer argument.
104269*/
104270static void charFunc(
104271  sqlite3_context *context,
104272  int argc,
104273  sqlite3_value **argv
104274){
104275  unsigned char *z, *zOut;
104276  int i;
104277  zOut = z = sqlite3_malloc64( argc*4+1 );
104278  if( z==0 ){
104279    sqlite3_result_error_nomem(context);
104280    return;
104281  }
104282  for(i=0; i<argc; i++){
104283    sqlite3_int64 x;
104284    unsigned c;
104285    x = sqlite3_value_int64(argv[i]);
104286    if( x<0 || x>0x10ffff ) x = 0xfffd;
104287    c = (unsigned)(x & 0x1fffff);
104288    if( c<0x00080 ){
104289      *zOut++ = (u8)(c&0xFF);
104290    }else if( c<0x00800 ){
104291      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
104292      *zOut++ = 0x80 + (u8)(c & 0x3F);
104293    }else if( c<0x10000 ){
104294      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
104295      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
104296      *zOut++ = 0x80 + (u8)(c & 0x3F);
104297    }else{
104298      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
104299      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
104300      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
104301      *zOut++ = 0x80 + (u8)(c & 0x3F);
104302    }                                                    \
104303  }
104304  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
104305}
104306
104307/*
104308** The hex() function.  Interpret the argument as a blob.  Return
104309** a hexadecimal rendering as text.
104310*/
104311static void hexFunc(
104312  sqlite3_context *context,
104313  int argc,
104314  sqlite3_value **argv
104315){
104316  int i, n;
104317  const unsigned char *pBlob;
104318  char *zHex, *z;
104319  assert( argc==1 );
104320  UNUSED_PARAMETER(argc);
104321  pBlob = sqlite3_value_blob(argv[0]);
104322  n = sqlite3_value_bytes(argv[0]);
104323  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
104324  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
104325  if( zHex ){
104326    for(i=0; i<n; i++, pBlob++){
104327      unsigned char c = *pBlob;
104328      *(z++) = hexdigits[(c>>4)&0xf];
104329      *(z++) = hexdigits[c&0xf];
104330    }
104331    *z = 0;
104332    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
104333  }
104334}
104335
104336/*
104337** The zeroblob(N) function returns a zero-filled blob of size N bytes.
104338*/
104339static void zeroblobFunc(
104340  sqlite3_context *context,
104341  int argc,
104342  sqlite3_value **argv
104343){
104344  i64 n;
104345  int rc;
104346  assert( argc==1 );
104347  UNUSED_PARAMETER(argc);
104348  n = sqlite3_value_int64(argv[0]);
104349  if( n<0 ) n = 0;
104350  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
104351  if( rc ){
104352    sqlite3_result_error_code(context, rc);
104353  }
104354}
104355
104356/*
104357** The replace() function.  Three arguments are all strings: call
104358** them A, B, and C. The result is also a string which is derived
104359** from A by replacing every occurrence of B with C.  The match
104360** must be exact.  Collating sequences are not used.
104361*/
104362static void replaceFunc(
104363  sqlite3_context *context,
104364  int argc,
104365  sqlite3_value **argv
104366){
104367  const unsigned char *zStr;        /* The input string A */
104368  const unsigned char *zPattern;    /* The pattern string B */
104369  const unsigned char *zRep;        /* The replacement string C */
104370  unsigned char *zOut;              /* The output */
104371  int nStr;                /* Size of zStr */
104372  int nPattern;            /* Size of zPattern */
104373  int nRep;                /* Size of zRep */
104374  i64 nOut;                /* Maximum size of zOut */
104375  int loopLimit;           /* Last zStr[] that might match zPattern[] */
104376  int i, j;                /* Loop counters */
104377
104378  assert( argc==3 );
104379  UNUSED_PARAMETER(argc);
104380  zStr = sqlite3_value_text(argv[0]);
104381  if( zStr==0 ) return;
104382  nStr = sqlite3_value_bytes(argv[0]);
104383  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
104384  zPattern = sqlite3_value_text(argv[1]);
104385  if( zPattern==0 ){
104386    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
104387            || sqlite3_context_db_handle(context)->mallocFailed );
104388    return;
104389  }
104390  if( zPattern[0]==0 ){
104391    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
104392    sqlite3_result_value(context, argv[0]);
104393    return;
104394  }
104395  nPattern = sqlite3_value_bytes(argv[1]);
104396  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
104397  zRep = sqlite3_value_text(argv[2]);
104398  if( zRep==0 ) return;
104399  nRep = sqlite3_value_bytes(argv[2]);
104400  assert( zRep==sqlite3_value_text(argv[2]) );
104401  nOut = nStr + 1;
104402  assert( nOut<SQLITE_MAX_LENGTH );
104403  zOut = contextMalloc(context, (i64)nOut);
104404  if( zOut==0 ){
104405    return;
104406  }
104407  loopLimit = nStr - nPattern;
104408  for(i=j=0; i<=loopLimit; i++){
104409    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
104410      zOut[j++] = zStr[i];
104411    }else{
104412      u8 *zOld;
104413      sqlite3 *db = sqlite3_context_db_handle(context);
104414      nOut += nRep - nPattern;
104415      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
104416      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
104417      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
104418        sqlite3_result_error_toobig(context);
104419        sqlite3_free(zOut);
104420        return;
104421      }
104422      zOld = zOut;
104423      zOut = sqlite3_realloc64(zOut, (int)nOut);
104424      if( zOut==0 ){
104425        sqlite3_result_error_nomem(context);
104426        sqlite3_free(zOld);
104427        return;
104428      }
104429      memcpy(&zOut[j], zRep, nRep);
104430      j += nRep;
104431      i += nPattern-1;
104432    }
104433  }
104434  assert( j+nStr-i+1==nOut );
104435  memcpy(&zOut[j], &zStr[i], nStr-i);
104436  j += nStr - i;
104437  assert( j<=nOut );
104438  zOut[j] = 0;
104439  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
104440}
104441
104442/*
104443** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
104444** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
104445*/
104446static void trimFunc(
104447  sqlite3_context *context,
104448  int argc,
104449  sqlite3_value **argv
104450){
104451  const unsigned char *zIn;         /* Input string */
104452  const unsigned char *zCharSet;    /* Set of characters to trim */
104453  int nIn;                          /* Number of bytes in input */
104454  int flags;                        /* 1: trimleft  2: trimright  3: trim */
104455  int i;                            /* Loop counter */
104456  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
104457  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
104458  int nChar;                        /* Number of characters in zCharSet */
104459
104460  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104461    return;
104462  }
104463  zIn = sqlite3_value_text(argv[0]);
104464  if( zIn==0 ) return;
104465  nIn = sqlite3_value_bytes(argv[0]);
104466  assert( zIn==sqlite3_value_text(argv[0]) );
104467  if( argc==1 ){
104468    static const unsigned char lenOne[] = { 1 };
104469    static unsigned char * const azOne[] = { (u8*)" " };
104470    nChar = 1;
104471    aLen = (u8*)lenOne;
104472    azChar = (unsigned char **)azOne;
104473    zCharSet = 0;
104474  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
104475    return;
104476  }else{
104477    const unsigned char *z;
104478    for(z=zCharSet, nChar=0; *z; nChar++){
104479      SQLITE_SKIP_UTF8(z);
104480    }
104481    if( nChar>0 ){
104482      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
104483      if( azChar==0 ){
104484        return;
104485      }
104486      aLen = (unsigned char*)&azChar[nChar];
104487      for(z=zCharSet, nChar=0; *z; nChar++){
104488        azChar[nChar] = (unsigned char *)z;
104489        SQLITE_SKIP_UTF8(z);
104490        aLen[nChar] = (u8)(z - azChar[nChar]);
104491      }
104492    }
104493  }
104494  if( nChar>0 ){
104495    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
104496    if( flags & 1 ){
104497      while( nIn>0 ){
104498        int len = 0;
104499        for(i=0; i<nChar; i++){
104500          len = aLen[i];
104501          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
104502        }
104503        if( i>=nChar ) break;
104504        zIn += len;
104505        nIn -= len;
104506      }
104507    }
104508    if( flags & 2 ){
104509      while( nIn>0 ){
104510        int len = 0;
104511        for(i=0; i<nChar; i++){
104512          len = aLen[i];
104513          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
104514        }
104515        if( i>=nChar ) break;
104516        nIn -= len;
104517      }
104518    }
104519    if( zCharSet ){
104520      sqlite3_free(azChar);
104521    }
104522  }
104523  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
104524}
104525
104526
104527#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
104528/*
104529** The "unknown" function is automatically substituted in place of
104530** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
104531** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
104532** When the "sqlite3" command-line shell is built using this functionality,
104533** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
104534** involving application-defined functions to be examined in a generic
104535** sqlite3 shell.
104536*/
104537static void unknownFunc(
104538  sqlite3_context *context,
104539  int argc,
104540  sqlite3_value **argv
104541){
104542  /* no-op */
104543}
104544#endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
104545
104546
104547/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
104548** is only available if the SQLITE_SOUNDEX compile-time option is used
104549** when SQLite is built.
104550*/
104551#ifdef SQLITE_SOUNDEX
104552/*
104553** Compute the soundex encoding of a word.
104554**
104555** IMP: R-59782-00072 The soundex(X) function returns a string that is the
104556** soundex encoding of the string X.
104557*/
104558static void soundexFunc(
104559  sqlite3_context *context,
104560  int argc,
104561  sqlite3_value **argv
104562){
104563  char zResult[8];
104564  const u8 *zIn;
104565  int i, j;
104566  static const unsigned char iCode[] = {
104567    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104568    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104569    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104570    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104571    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
104572    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
104573    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
104574    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
104575  };
104576  assert( argc==1 );
104577  zIn = (u8*)sqlite3_value_text(argv[0]);
104578  if( zIn==0 ) zIn = (u8*)"";
104579  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
104580  if( zIn[i] ){
104581    u8 prevcode = iCode[zIn[i]&0x7f];
104582    zResult[0] = sqlite3Toupper(zIn[i]);
104583    for(j=1; j<4 && zIn[i]; i++){
104584      int code = iCode[zIn[i]&0x7f];
104585      if( code>0 ){
104586        if( code!=prevcode ){
104587          prevcode = code;
104588          zResult[j++] = code + '0';
104589        }
104590      }else{
104591        prevcode = 0;
104592      }
104593    }
104594    while( j<4 ){
104595      zResult[j++] = '0';
104596    }
104597    zResult[j] = 0;
104598    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
104599  }else{
104600    /* IMP: R-64894-50321 The string "?000" is returned if the argument
104601    ** is NULL or contains no ASCII alphabetic characters. */
104602    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
104603  }
104604}
104605#endif /* SQLITE_SOUNDEX */
104606
104607#ifndef SQLITE_OMIT_LOAD_EXTENSION
104608/*
104609** A function that loads a shared-library extension then returns NULL.
104610*/
104611static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
104612  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
104613  const char *zProc;
104614  sqlite3 *db = sqlite3_context_db_handle(context);
104615  char *zErrMsg = 0;
104616
104617  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
104618  ** flag is set.  See the sqlite3_enable_load_extension() API.
104619  */
104620  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
104621    sqlite3_result_error(context, "not authorized", -1);
104622    return;
104623  }
104624
104625  if( argc==2 ){
104626    zProc = (const char *)sqlite3_value_text(argv[1]);
104627  }else{
104628    zProc = 0;
104629  }
104630  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
104631    sqlite3_result_error(context, zErrMsg, -1);
104632    sqlite3_free(zErrMsg);
104633  }
104634}
104635#endif
104636
104637
104638/*
104639** An instance of the following structure holds the context of a
104640** sum() or avg() aggregate computation.
104641*/
104642typedef struct SumCtx SumCtx;
104643struct SumCtx {
104644  double rSum;      /* Floating point sum */
104645  i64 iSum;         /* Integer sum */
104646  i64 cnt;          /* Number of elements summed */
104647  u8 overflow;      /* True if integer overflow seen */
104648  u8 approx;        /* True if non-integer value was input to the sum */
104649};
104650
104651/*
104652** Routines used to compute the sum, average, and total.
104653**
104654** The SUM() function follows the (broken) SQL standard which means
104655** that it returns NULL if it sums over no inputs.  TOTAL returns
104656** 0.0 in that case.  In addition, TOTAL always returns a float where
104657** SUM might return an integer if it never encounters a floating point
104658** value.  TOTAL never fails, but SUM might through an exception if
104659** it overflows an integer.
104660*/
104661static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104662  SumCtx *p;
104663  int type;
104664  assert( argc==1 );
104665  UNUSED_PARAMETER(argc);
104666  p = sqlite3_aggregate_context(context, sizeof(*p));
104667  type = sqlite3_value_numeric_type(argv[0]);
104668  if( p && type!=SQLITE_NULL ){
104669    p->cnt++;
104670    if( type==SQLITE_INTEGER ){
104671      i64 v = sqlite3_value_int64(argv[0]);
104672      p->rSum += v;
104673      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
104674        p->overflow = 1;
104675      }
104676    }else{
104677      p->rSum += sqlite3_value_double(argv[0]);
104678      p->approx = 1;
104679    }
104680  }
104681}
104682static void sumFinalize(sqlite3_context *context){
104683  SumCtx *p;
104684  p = sqlite3_aggregate_context(context, 0);
104685  if( p && p->cnt>0 ){
104686    if( p->overflow ){
104687      sqlite3_result_error(context,"integer overflow",-1);
104688    }else if( p->approx ){
104689      sqlite3_result_double(context, p->rSum);
104690    }else{
104691      sqlite3_result_int64(context, p->iSum);
104692    }
104693  }
104694}
104695static void avgFinalize(sqlite3_context *context){
104696  SumCtx *p;
104697  p = sqlite3_aggregate_context(context, 0);
104698  if( p && p->cnt>0 ){
104699    sqlite3_result_double(context, p->rSum/(double)p->cnt);
104700  }
104701}
104702static void totalFinalize(sqlite3_context *context){
104703  SumCtx *p;
104704  p = sqlite3_aggregate_context(context, 0);
104705  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104706  sqlite3_result_double(context, p ? p->rSum : (double)0);
104707}
104708
104709/*
104710** The following structure keeps track of state information for the
104711** count() aggregate function.
104712*/
104713typedef struct CountCtx CountCtx;
104714struct CountCtx {
104715  i64 n;
104716};
104717
104718/*
104719** Routines to implement the count() aggregate function.
104720*/
104721static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104722  CountCtx *p;
104723  p = sqlite3_aggregate_context(context, sizeof(*p));
104724  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
104725    p->n++;
104726  }
104727
104728#ifndef SQLITE_OMIT_DEPRECATED
104729  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
104730  ** sure it still operates correctly, verify that its count agrees with our
104731  ** internal count when using count(*) and when the total count can be
104732  ** expressed as a 32-bit integer. */
104733  assert( argc==1 || p==0 || p->n>0x7fffffff
104734          || p->n==sqlite3_aggregate_count(context) );
104735#endif
104736}
104737static void countFinalize(sqlite3_context *context){
104738  CountCtx *p;
104739  p = sqlite3_aggregate_context(context, 0);
104740  sqlite3_result_int64(context, p ? p->n : 0);
104741}
104742
104743/*
104744** Routines to implement min() and max() aggregate functions.
104745*/
104746static void minmaxStep(
104747  sqlite3_context *context,
104748  int NotUsed,
104749  sqlite3_value **argv
104750){
104751  Mem *pArg  = (Mem *)argv[0];
104752  Mem *pBest;
104753  UNUSED_PARAMETER(NotUsed);
104754
104755  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
104756  if( !pBest ) return;
104757
104758  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104759    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
104760  }else if( pBest->flags ){
104761    int max;
104762    int cmp;
104763    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104764    /* This step function is used for both the min() and max() aggregates,
104765    ** the only difference between the two being that the sense of the
104766    ** comparison is inverted. For the max() aggregate, the
104767    ** sqlite3_user_data() function returns (void *)-1. For min() it
104768    ** returns (void *)db, where db is the sqlite3* database pointer.
104769    ** Therefore the next statement sets variable 'max' to 1 for the max()
104770    ** aggregate, or 0 for min().
104771    */
104772    max = sqlite3_user_data(context)!=0;
104773    cmp = sqlite3MemCompare(pBest, pArg, pColl);
104774    if( (max && cmp<0) || (!max && cmp>0) ){
104775      sqlite3VdbeMemCopy(pBest, pArg);
104776    }else{
104777      sqlite3SkipAccumulatorLoad(context);
104778    }
104779  }else{
104780    pBest->db = sqlite3_context_db_handle(context);
104781    sqlite3VdbeMemCopy(pBest, pArg);
104782  }
104783}
104784static void minMaxFinalize(sqlite3_context *context){
104785  sqlite3_value *pRes;
104786  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
104787  if( pRes ){
104788    if( pRes->flags ){
104789      sqlite3_result_value(context, pRes);
104790    }
104791    sqlite3VdbeMemRelease(pRes);
104792  }
104793}
104794
104795/*
104796** group_concat(EXPR, ?SEPARATOR?)
104797*/
104798static void groupConcatStep(
104799  sqlite3_context *context,
104800  int argc,
104801  sqlite3_value **argv
104802){
104803  const char *zVal;
104804  StrAccum *pAccum;
104805  const char *zSep;
104806  int nVal, nSep;
104807  assert( argc==1 || argc==2 );
104808  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104809  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
104810
104811  if( pAccum ){
104812    sqlite3 *db = sqlite3_context_db_handle(context);
104813    int firstTerm = pAccum->mxAlloc==0;
104814    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
104815    if( !firstTerm ){
104816      if( argc==2 ){
104817        zSep = (char*)sqlite3_value_text(argv[1]);
104818        nSep = sqlite3_value_bytes(argv[1]);
104819      }else{
104820        zSep = ",";
104821        nSep = 1;
104822      }
104823      if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
104824    }
104825    zVal = (char*)sqlite3_value_text(argv[0]);
104826    nVal = sqlite3_value_bytes(argv[0]);
104827    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
104828  }
104829}
104830static void groupConcatFinalize(sqlite3_context *context){
104831  StrAccum *pAccum;
104832  pAccum = sqlite3_aggregate_context(context, 0);
104833  if( pAccum ){
104834    if( pAccum->accError==STRACCUM_TOOBIG ){
104835      sqlite3_result_error_toobig(context);
104836    }else if( pAccum->accError==STRACCUM_NOMEM ){
104837      sqlite3_result_error_nomem(context);
104838    }else{
104839      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
104840                          sqlite3_free);
104841    }
104842  }
104843}
104844
104845/*
104846** This routine does per-connection function registration.  Most
104847** of the built-in functions above are part of the global function set.
104848** This routine only deals with those that are not global.
104849*/
104850SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
104851  int rc = sqlite3_overload_function(db, "MATCH", 2);
104852  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
104853  if( rc==SQLITE_NOMEM ){
104854    sqlite3OomFault(db);
104855  }
104856}
104857
104858/*
104859** Set the LIKEOPT flag on the 2-argument function with the given name.
104860*/
104861static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
104862  FuncDef *pDef;
104863  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
104864  if( ALWAYS(pDef) ){
104865    pDef->funcFlags |= flagVal;
104866  }
104867}
104868
104869/*
104870** Register the built-in LIKE and GLOB functions.  The caseSensitive
104871** parameter determines whether or not the LIKE operator is case
104872** sensitive.  GLOB is always case sensitive.
104873*/
104874SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
104875  struct compareInfo *pInfo;
104876  if( caseSensitive ){
104877    pInfo = (struct compareInfo*)&likeInfoAlt;
104878  }else{
104879    pInfo = (struct compareInfo*)&likeInfoNorm;
104880  }
104881  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104882  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104883  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
104884      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
104885  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
104886  setLikeOptFlag(db, "like",
104887      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
104888}
104889
104890/*
104891** pExpr points to an expression which implements a function.  If
104892** it is appropriate to apply the LIKE optimization to that function
104893** then set aWc[0] through aWc[2] to the wildcard characters and
104894** return TRUE.  If the function is not a LIKE-style function then
104895** return FALSE.
104896**
104897** *pIsNocase is set to true if uppercase and lowercase are equivalent for
104898** the function (default for LIKE).  If the function makes the distinction
104899** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
104900** false.
104901*/
104902SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
104903  FuncDef *pDef;
104904  if( pExpr->op!=TK_FUNCTION
104905   || !pExpr->x.pList
104906   || pExpr->x.pList->nExpr!=2
104907  ){
104908    return 0;
104909  }
104910  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
104911  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
104912  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
104913    return 0;
104914  }
104915
104916  /* The memcpy() statement assumes that the wildcard characters are
104917  ** the first three statements in the compareInfo structure.  The
104918  ** asserts() that follow verify that assumption
104919  */
104920  memcpy(aWc, pDef->pUserData, 3);
104921  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
104922  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
104923  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
104924  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
104925  return 1;
104926}
104927
104928/*
104929** All of the FuncDef structures in the aBuiltinFunc[] array above
104930** to the global function hash table.  This occurs at start-time (as
104931** a consequence of calling sqlite3_initialize()).
104932**
104933** After this routine runs
104934*/
104935SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
104936  /*
104937  ** The following array holds FuncDef structures for all of the functions
104938  ** defined in this file.
104939  **
104940  ** The array cannot be constant since changes are made to the
104941  ** FuncDef.pHash elements at start-time.  The elements of this array
104942  ** are read-only after initialization is complete.
104943  **
104944  ** For peak efficiency, put the most frequently used function last.
104945  */
104946  static FuncDef aBuiltinFunc[] = {
104947#ifdef SQLITE_SOUNDEX
104948    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
104949#endif
104950#ifndef SQLITE_OMIT_LOAD_EXTENSION
104951    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
104952    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
104953#endif
104954#if SQLITE_USER_AUTHENTICATION
104955    FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
104956#endif
104957#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104958    DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
104959    DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
104960#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104961    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104962    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104963    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104964    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
104965    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
104966    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
104967    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
104968    FUNCTION(trim,               1, 3, 0, trimFunc         ),
104969    FUNCTION(trim,               2, 3, 0, trimFunc         ),
104970    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
104971    FUNCTION(min,                0, 0, 1, 0                ),
104972    AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
104973                                          SQLITE_FUNC_MINMAX ),
104974    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
104975    FUNCTION(max,                0, 1, 1, 0                ),
104976    AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
104977                                          SQLITE_FUNC_MINMAX ),
104978    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
104979    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
104980    FUNCTION(instr,              2, 0, 0, instrFunc        ),
104981    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
104982    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
104983    FUNCTION(char,              -1, 0, 0, charFunc         ),
104984    FUNCTION(abs,                1, 0, 0, absFunc          ),
104985#ifndef SQLITE_OMIT_FLOATING_POINT
104986    FUNCTION(round,              1, 0, 0, roundFunc        ),
104987    FUNCTION(round,              2, 0, 0, roundFunc        ),
104988#endif
104989    FUNCTION(upper,              1, 0, 0, upperFunc        ),
104990    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
104991    FUNCTION(hex,                1, 0, 0, hexFunc          ),
104992    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
104993    VFUNCTION(random,            0, 0, 0, randomFunc       ),
104994    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
104995    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
104996    DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
104997    DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
104998    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
104999    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
105000    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
105001    VFUNCTION(changes,           0, 0, 0, changes          ),
105002    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
105003    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
105004    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
105005    FUNCTION(substr,             2, 0, 0, substrFunc       ),
105006    FUNCTION(substr,             3, 0, 0, substrFunc       ),
105007    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
105008    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
105009    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
105010    AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
105011               SQLITE_FUNC_COUNT  ),
105012    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
105013    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
105014    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
105015
105016    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105017#ifdef SQLITE_CASE_SENSITIVE_LIKE
105018    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105019    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105020#else
105021    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
105022    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
105023#endif
105024#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105025    FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
105026#endif
105027    FUNCTION(coalesce,           1, 0, 0, 0                ),
105028    FUNCTION(coalesce,           0, 0, 0, 0                ),
105029    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
105030  };
105031#ifndef SQLITE_OMIT_ALTERTABLE
105032  sqlite3AlterFunctions();
105033#endif
105034#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
105035  sqlite3AnalyzeFunctions();
105036#endif
105037  sqlite3RegisterDateTimeFunctions();
105038  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
105039
105040#if 0  /* Enable to print out how the built-in functions are hashed */
105041  {
105042    int i;
105043    FuncDef *p;
105044    for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
105045      printf("FUNC-HASH %02d:", i);
105046      for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
105047        int n = sqlite3Strlen30(p->zName);
105048        int h = p->zName[0] + n;
105049        printf(" %s(%d)", p->zName, h);
105050      }
105051      printf("\n");
105052    }
105053  }
105054#endif
105055}
105056
105057/************** End of func.c ************************************************/
105058/************** Begin file fkey.c ********************************************/
105059/*
105060**
105061** The author disclaims copyright to this source code.  In place of
105062** a legal notice, here is a blessing:
105063**
105064**    May you do good and not evil.
105065**    May you find forgiveness for yourself and forgive others.
105066**    May you share freely, never taking more than you give.
105067**
105068*************************************************************************
105069** This file contains code used by the compiler to add foreign key
105070** support to compiled SQL statements.
105071*/
105072/* #include "sqliteInt.h" */
105073
105074#ifndef SQLITE_OMIT_FOREIGN_KEY
105075#ifndef SQLITE_OMIT_TRIGGER
105076
105077/*
105078** Deferred and Immediate FKs
105079** --------------------------
105080**
105081** Foreign keys in SQLite come in two flavours: deferred and immediate.
105082** If an immediate foreign key constraint is violated,
105083** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
105084** statement transaction rolled back. If a
105085** deferred foreign key constraint is violated, no action is taken
105086** immediately. However if the application attempts to commit the
105087** transaction before fixing the constraint violation, the attempt fails.
105088**
105089** Deferred constraints are implemented using a simple counter associated
105090** with the database handle. The counter is set to zero each time a
105091** database transaction is opened. Each time a statement is executed
105092** that causes a foreign key violation, the counter is incremented. Each
105093** time a statement is executed that removes an existing violation from
105094** the database, the counter is decremented. When the transaction is
105095** committed, the commit fails if the current value of the counter is
105096** greater than zero. This scheme has two big drawbacks:
105097**
105098**   * When a commit fails due to a deferred foreign key constraint,
105099**     there is no way to tell which foreign constraint is not satisfied,
105100**     or which row it is not satisfied for.
105101**
105102**   * If the database contains foreign key violations when the
105103**     transaction is opened, this may cause the mechanism to malfunction.
105104**
105105** Despite these problems, this approach is adopted as it seems simpler
105106** than the alternatives.
105107**
105108** INSERT operations:
105109**
105110**   I.1) For each FK for which the table is the child table, search
105111**        the parent table for a match. If none is found increment the
105112**        constraint counter.
105113**
105114**   I.2) For each FK for which the table is the parent table,
105115**        search the child table for rows that correspond to the new
105116**        row in the parent table. Decrement the counter for each row
105117**        found (as the constraint is now satisfied).
105118**
105119** DELETE operations:
105120**
105121**   D.1) For each FK for which the table is the child table,
105122**        search the parent table for a row that corresponds to the
105123**        deleted row in the child table. If such a row is not found,
105124**        decrement the counter.
105125**
105126**   D.2) For each FK for which the table is the parent table, search
105127**        the child table for rows that correspond to the deleted row
105128**        in the parent table. For each found increment the counter.
105129**
105130** UPDATE operations:
105131**
105132**   An UPDATE command requires that all 4 steps above are taken, but only
105133**   for FK constraints for which the affected columns are actually
105134**   modified (values must be compared at runtime).
105135**
105136** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
105137** This simplifies the implementation a bit.
105138**
105139** For the purposes of immediate FK constraints, the OR REPLACE conflict
105140** resolution is considered to delete rows before the new row is inserted.
105141** If a delete caused by OR REPLACE violates an FK constraint, an exception
105142** is thrown, even if the FK constraint would be satisfied after the new
105143** row is inserted.
105144**
105145** Immediate constraints are usually handled similarly. The only difference
105146** is that the counter used is stored as part of each individual statement
105147** object (struct Vdbe). If, after the statement has run, its immediate
105148** constraint counter is greater than zero,
105149** it returns SQLITE_CONSTRAINT_FOREIGNKEY
105150** and the statement transaction is rolled back. An exception is an INSERT
105151** statement that inserts a single row only (no triggers). In this case,
105152** instead of using a counter, an exception is thrown immediately if the
105153** INSERT violates a foreign key constraint. This is necessary as such
105154** an INSERT does not open a statement transaction.
105155**
105156** TODO: How should dropping a table be handled? How should renaming a
105157** table be handled?
105158**
105159**
105160** Query API Notes
105161** ---------------
105162**
105163** Before coding an UPDATE or DELETE row operation, the code-generator
105164** for those two operations needs to know whether or not the operation
105165** requires any FK processing and, if so, which columns of the original
105166** row are required by the FK processing VDBE code (i.e. if FKs were
105167** implemented using triggers, which of the old.* columns would be
105168** accessed). No information is required by the code-generator before
105169** coding an INSERT operation. The functions used by the UPDATE/DELETE
105170** generation code to query for this information are:
105171**
105172**   sqlite3FkRequired() - Test to see if FK processing is required.
105173**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
105174**
105175**
105176** Externally accessible module functions
105177** --------------------------------------
105178**
105179**   sqlite3FkCheck()    - Check for foreign key violations.
105180**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
105181**   sqlite3FkDelete()   - Delete an FKey structure.
105182*/
105183
105184/*
105185** VDBE Calling Convention
105186** -----------------------
105187**
105188** Example:
105189**
105190**   For the following INSERT statement:
105191**
105192**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
105193**     INSERT INTO t1 VALUES(1, 2, 3.1);
105194**
105195**   Register (x):        2    (type integer)
105196**   Register (x+1):      1    (type integer)
105197**   Register (x+2):      NULL (type NULL)
105198**   Register (x+3):      3.1  (type real)
105199*/
105200
105201/*
105202** A foreign key constraint requires that the key columns in the parent
105203** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
105204** Given that pParent is the parent table for foreign key constraint pFKey,
105205** search the schema for a unique index on the parent key columns.
105206**
105207** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
105208** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
105209** is set to point to the unique index.
105210**
105211** If the parent key consists of a single column (the foreign key constraint
105212** is not a composite foreign key), output variable *paiCol is set to NULL.
105213** Otherwise, it is set to point to an allocated array of size N, where
105214** N is the number of columns in the parent key. The first element of the
105215** array is the index of the child table column that is mapped by the FK
105216** constraint to the parent table column stored in the left-most column
105217** of index *ppIdx. The second element of the array is the index of the
105218** child table column that corresponds to the second left-most column of
105219** *ppIdx, and so on.
105220**
105221** If the required index cannot be found, either because:
105222**
105223**   1) The named parent key columns do not exist, or
105224**
105225**   2) The named parent key columns do exist, but are not subject to a
105226**      UNIQUE or PRIMARY KEY constraint, or
105227**
105228**   3) No parent key columns were provided explicitly as part of the
105229**      foreign key definition, and the parent table does not have a
105230**      PRIMARY KEY, or
105231**
105232**   4) No parent key columns were provided explicitly as part of the
105233**      foreign key definition, and the PRIMARY KEY of the parent table
105234**      consists of a different number of columns to the child key in
105235**      the child table.
105236**
105237** then non-zero is returned, and a "foreign key mismatch" error loaded
105238** into pParse. If an OOM error occurs, non-zero is returned and the
105239** pParse->db->mallocFailed flag is set.
105240*/
105241SQLITE_PRIVATE int sqlite3FkLocateIndex(
105242  Parse *pParse,                  /* Parse context to store any error in */
105243  Table *pParent,                 /* Parent table of FK constraint pFKey */
105244  FKey *pFKey,                    /* Foreign key to find index for */
105245  Index **ppIdx,                  /* OUT: Unique index on parent table */
105246  int **paiCol                    /* OUT: Map of index columns in pFKey */
105247){
105248  Index *pIdx = 0;                    /* Value to return via *ppIdx */
105249  int *aiCol = 0;                     /* Value to return via *paiCol */
105250  int nCol = pFKey->nCol;             /* Number of columns in parent key */
105251  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
105252
105253  /* The caller is responsible for zeroing output parameters. */
105254  assert( ppIdx && *ppIdx==0 );
105255  assert( !paiCol || *paiCol==0 );
105256  assert( pParse );
105257
105258  /* If this is a non-composite (single column) foreign key, check if it
105259  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
105260  ** and *paiCol set to zero and return early.
105261  **
105262  ** Otherwise, for a composite foreign key (more than one column), allocate
105263  ** space for the aiCol array (returned via output parameter *paiCol).
105264  ** Non-composite foreign keys do not require the aiCol array.
105265  */
105266  if( nCol==1 ){
105267    /* The FK maps to the IPK if any of the following are true:
105268    **
105269    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
105270    **      mapped to the primary key of table pParent, or
105271    **   2) The FK is explicitly mapped to a column declared as INTEGER
105272    **      PRIMARY KEY.
105273    */
105274    if( pParent->iPKey>=0 ){
105275      if( !zKey ) return 0;
105276      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
105277    }
105278  }else if( paiCol ){
105279    assert( nCol>1 );
105280    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
105281    if( !aiCol ) return 1;
105282    *paiCol = aiCol;
105283  }
105284
105285  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
105286    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
105287      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
105288      ** of columns. If each indexed column corresponds to a foreign key
105289      ** column of pFKey, then this index is a winner.  */
105290
105291      if( zKey==0 ){
105292        /* If zKey is NULL, then this foreign key is implicitly mapped to
105293        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
105294        ** identified by the test.  */
105295        if( IsPrimaryKeyIndex(pIdx) ){
105296          if( aiCol ){
105297            int i;
105298            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
105299          }
105300          break;
105301        }
105302      }else{
105303        /* If zKey is non-NULL, then this foreign key was declared to
105304        ** map to an explicit list of columns in table pParent. Check if this
105305        ** index matches those columns. Also, check that the index uses
105306        ** the default collation sequences for each column. */
105307        int i, j;
105308        for(i=0; i<nCol; i++){
105309          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
105310          const char *zDfltColl;            /* Def. collation for column */
105311          char *zIdxCol;                    /* Name of indexed column */
105312
105313          if( iCol<0 ) break; /* No foreign keys against expression indexes */
105314
105315          /* If the index uses a collation sequence that is different from
105316          ** the default collation sequence for the column, this index is
105317          ** unusable. Bail out early in this case.  */
105318          zDfltColl = pParent->aCol[iCol].zColl;
105319          if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
105320          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
105321
105322          zIdxCol = pParent->aCol[iCol].zName;
105323          for(j=0; j<nCol; j++){
105324            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
105325              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
105326              break;
105327            }
105328          }
105329          if( j==nCol ) break;
105330        }
105331        if( i==nCol ) break;      /* pIdx is usable */
105332      }
105333    }
105334  }
105335
105336  if( !pIdx ){
105337    if( !pParse->disableTriggers ){
105338      sqlite3ErrorMsg(pParse,
105339           "foreign key mismatch - \"%w\" referencing \"%w\"",
105340           pFKey->pFrom->zName, pFKey->zTo);
105341    }
105342    sqlite3DbFree(pParse->db, aiCol);
105343    return 1;
105344  }
105345
105346  *ppIdx = pIdx;
105347  return 0;
105348}
105349
105350/*
105351** This function is called when a row is inserted into or deleted from the
105352** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
105353** on the child table of pFKey, this function is invoked twice for each row
105354** affected - once to "delete" the old row, and then again to "insert" the
105355** new row.
105356**
105357** Each time it is called, this function generates VDBE code to locate the
105358** row in the parent table that corresponds to the row being inserted into
105359** or deleted from the child table. If the parent row can be found, no
105360** special action is taken. Otherwise, if the parent row can *not* be
105361** found in the parent table:
105362**
105363**   Operation | FK type   | Action taken
105364**   --------------------------------------------------------------------------
105365**   INSERT      immediate   Increment the "immediate constraint counter".
105366**
105367**   DELETE      immediate   Decrement the "immediate constraint counter".
105368**
105369**   INSERT      deferred    Increment the "deferred constraint counter".
105370**
105371**   DELETE      deferred    Decrement the "deferred constraint counter".
105372**
105373** These operations are identified in the comment at the top of this file
105374** (fkey.c) as "I.1" and "D.1".
105375*/
105376static void fkLookupParent(
105377  Parse *pParse,        /* Parse context */
105378  int iDb,              /* Index of database housing pTab */
105379  Table *pTab,          /* Parent table of FK pFKey */
105380  Index *pIdx,          /* Unique index on parent key columns in pTab */
105381  FKey *pFKey,          /* Foreign key constraint */
105382  int *aiCol,           /* Map from parent key columns to child table columns */
105383  int regData,          /* Address of array containing child table row */
105384  int nIncr,            /* Increment constraint counter by this */
105385  int isIgnore          /* If true, pretend pTab contains all NULL values */
105386){
105387  int i;                                    /* Iterator variable */
105388  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
105389  int iCur = pParse->nTab - 1;              /* Cursor number to use */
105390  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
105391
105392  /* If nIncr is less than zero, then check at runtime if there are any
105393  ** outstanding constraints to resolve. If there are not, there is no need
105394  ** to check if deleting this row resolves any outstanding violations.
105395  **
105396  ** Check if any of the key columns in the child table row are NULL. If
105397  ** any are, then the constraint is considered satisfied. No need to
105398  ** search for a matching row in the parent table.  */
105399  if( nIncr<0 ){
105400    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
105401    VdbeCoverage(v);
105402  }
105403  for(i=0; i<pFKey->nCol; i++){
105404    int iReg = aiCol[i] + regData + 1;
105405    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
105406  }
105407
105408  if( isIgnore==0 ){
105409    if( pIdx==0 ){
105410      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
105411      ** column of the parent table (table pTab).  */
105412      int iMustBeInt;               /* Address of MustBeInt instruction */
105413      int regTemp = sqlite3GetTempReg(pParse);
105414
105415      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
105416      ** apply the affinity of the parent key). If this fails, then there
105417      ** is no matching parent key. Before using MustBeInt, make a copy of
105418      ** the value. Otherwise, the value inserted into the child key column
105419      ** will have INTEGER affinity applied to it, which may not be correct.  */
105420      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
105421      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
105422      VdbeCoverage(v);
105423
105424      /* If the parent table is the same as the child table, and we are about
105425      ** to increment the constraint-counter (i.e. this is an INSERT operation),
105426      ** then check if the row being inserted matches itself. If so, do not
105427      ** increment the constraint-counter.  */
105428      if( pTab==pFKey->pFrom && nIncr==1 ){
105429        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
105430        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
105431      }
105432
105433      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
105434      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
105435      sqlite3VdbeGoto(v, iOk);
105436      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
105437      sqlite3VdbeJumpHere(v, iMustBeInt);
105438      sqlite3ReleaseTempReg(pParse, regTemp);
105439    }else{
105440      int nCol = pFKey->nCol;
105441      int regTemp = sqlite3GetTempRange(pParse, nCol);
105442      int regRec = sqlite3GetTempReg(pParse);
105443
105444      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
105445      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
105446      for(i=0; i<nCol; i++){
105447        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
105448      }
105449
105450      /* If the parent table is the same as the child table, and we are about
105451      ** to increment the constraint-counter (i.e. this is an INSERT operation),
105452      ** then check if the row being inserted matches itself. If so, do not
105453      ** increment the constraint-counter.
105454      **
105455      ** If any of the parent-key values are NULL, then the row cannot match
105456      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
105457      ** of the parent-key values are NULL (at this point it is known that
105458      ** none of the child key values are).
105459      */
105460      if( pTab==pFKey->pFrom && nIncr==1 ){
105461        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
105462        for(i=0; i<nCol; i++){
105463          int iChild = aiCol[i]+1+regData;
105464          int iParent = pIdx->aiColumn[i]+1+regData;
105465          assert( pIdx->aiColumn[i]>=0 );
105466          assert( aiCol[i]!=pTab->iPKey );
105467          if( pIdx->aiColumn[i]==pTab->iPKey ){
105468            /* The parent key is a composite key that includes the IPK column */
105469            iParent = regData;
105470          }
105471          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
105472          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
105473        }
105474        sqlite3VdbeGoto(v, iOk);
105475      }
105476
105477      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
105478                        sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
105479      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
105480
105481      sqlite3ReleaseTempReg(pParse, regRec);
105482      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
105483    }
105484  }
105485
105486  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
105487   && !pParse->pToplevel
105488   && !pParse->isMultiWrite
105489  ){
105490    /* Special case: If this is an INSERT statement that will insert exactly
105491    ** one row into the table, raise a constraint immediately instead of
105492    ** incrementing a counter. This is necessary as the VM code is being
105493    ** generated for will not open a statement transaction.  */
105494    assert( nIncr==1 );
105495    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
105496        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
105497  }else{
105498    if( nIncr>0 && pFKey->isDeferred==0 ){
105499      sqlite3MayAbort(pParse);
105500    }
105501    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105502  }
105503
105504  sqlite3VdbeResolveLabel(v, iOk);
105505  sqlite3VdbeAddOp1(v, OP_Close, iCur);
105506}
105507
105508
105509/*
105510** Return an Expr object that refers to a memory register corresponding
105511** to column iCol of table pTab.
105512**
105513** regBase is the first of an array of register that contains the data
105514** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
105515** column.  regBase+2 holds the second column, and so forth.
105516*/
105517static Expr *exprTableRegister(
105518  Parse *pParse,     /* Parsing and code generating context */
105519  Table *pTab,       /* The table whose content is at r[regBase]... */
105520  int regBase,       /* Contents of table pTab */
105521  i16 iCol           /* Which column of pTab is desired */
105522){
105523  Expr *pExpr;
105524  Column *pCol;
105525  const char *zColl;
105526  sqlite3 *db = pParse->db;
105527
105528  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
105529  if( pExpr ){
105530    if( iCol>=0 && iCol!=pTab->iPKey ){
105531      pCol = &pTab->aCol[iCol];
105532      pExpr->iTable = regBase + iCol + 1;
105533      pExpr->affinity = pCol->affinity;
105534      zColl = pCol->zColl;
105535      if( zColl==0 ) zColl = db->pDfltColl->zName;
105536      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
105537    }else{
105538      pExpr->iTable = regBase;
105539      pExpr->affinity = SQLITE_AFF_INTEGER;
105540    }
105541  }
105542  return pExpr;
105543}
105544
105545/*
105546** Return an Expr object that refers to column iCol of table pTab which
105547** has cursor iCur.
105548*/
105549static Expr *exprTableColumn(
105550  sqlite3 *db,      /* The database connection */
105551  Table *pTab,      /* The table whose column is desired */
105552  int iCursor,      /* The open cursor on the table */
105553  i16 iCol          /* The column that is wanted */
105554){
105555  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
105556  if( pExpr ){
105557    pExpr->pTab = pTab;
105558    pExpr->iTable = iCursor;
105559    pExpr->iColumn = iCol;
105560  }
105561  return pExpr;
105562}
105563
105564/*
105565** This function is called to generate code executed when a row is deleted
105566** from the parent table of foreign key constraint pFKey and, if pFKey is
105567** deferred, when a row is inserted into the same table. When generating
105568** code for an SQL UPDATE operation, this function may be called twice -
105569** once to "delete" the old row and once to "insert" the new row.
105570**
105571** Parameter nIncr is passed -1 when inserting a row (as this may decrease
105572** the number of FK violations in the db) or +1 when deleting one (as this
105573** may increase the number of FK constraint problems).
105574**
105575** The code generated by this function scans through the rows in the child
105576** table that correspond to the parent table row being deleted or inserted.
105577** For each child row found, one of the following actions is taken:
105578**
105579**   Operation | FK type   | Action taken
105580**   --------------------------------------------------------------------------
105581**   DELETE      immediate   Increment the "immediate constraint counter".
105582**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
105583**                           throw a "FOREIGN KEY constraint failed" exception.
105584**
105585**   INSERT      immediate   Decrement the "immediate constraint counter".
105586**
105587**   DELETE      deferred    Increment the "deferred constraint counter".
105588**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
105589**                           throw a "FOREIGN KEY constraint failed" exception.
105590**
105591**   INSERT      deferred    Decrement the "deferred constraint counter".
105592**
105593** These operations are identified in the comment at the top of this file
105594** (fkey.c) as "I.2" and "D.2".
105595*/
105596static void fkScanChildren(
105597  Parse *pParse,                  /* Parse context */
105598  SrcList *pSrc,                  /* The child table to be scanned */
105599  Table *pTab,                    /* The parent table */
105600  Index *pIdx,                    /* Index on parent covering the foreign key */
105601  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
105602  int *aiCol,                     /* Map from pIdx cols to child table cols */
105603  int regData,                    /* Parent row data starts here */
105604  int nIncr                       /* Amount to increment deferred counter by */
105605){
105606  sqlite3 *db = pParse->db;       /* Database handle */
105607  int i;                          /* Iterator variable */
105608  Expr *pWhere = 0;               /* WHERE clause to scan with */
105609  NameContext sNameContext;       /* Context used to resolve WHERE clause */
105610  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
105611  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
105612  Vdbe *v = sqlite3GetVdbe(pParse);
105613
105614  assert( pIdx==0 || pIdx->pTable==pTab );
105615  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
105616  assert( pIdx!=0 || pFKey->nCol==1 );
105617  assert( pIdx!=0 || HasRowid(pTab) );
105618
105619  if( nIncr<0 ){
105620    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
105621    VdbeCoverage(v);
105622  }
105623
105624  /* Create an Expr object representing an SQL expression like:
105625  **
105626  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
105627  **
105628  ** The collation sequence used for the comparison should be that of
105629  ** the parent key columns. The affinity of the parent key column should
105630  ** be applied to each child key value before the comparison takes place.
105631  */
105632  for(i=0; i<pFKey->nCol; i++){
105633    Expr *pLeft;                  /* Value from parent table row */
105634    Expr *pRight;                 /* Column ref to child table */
105635    Expr *pEq;                    /* Expression (pLeft = pRight) */
105636    i16 iCol;                     /* Index of column in child table */
105637    const char *zCol;             /* Name of column in child table */
105638
105639    iCol = pIdx ? pIdx->aiColumn[i] : -1;
105640    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105641    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
105642    assert( iCol>=0 );
105643    zCol = pFKey->pFrom->aCol[iCol].zName;
105644    pRight = sqlite3Expr(db, TK_ID, zCol);
105645    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105646    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
105647  }
105648
105649  /* If the child table is the same as the parent table, then add terms
105650  ** to the WHERE clause that prevent this entry from being scanned.
105651  ** The added WHERE clause terms are like this:
105652  **
105653  **     $current_rowid!=rowid
105654  **     NOT( $current_a==a AND $current_b==b AND ... )
105655  **
105656  ** The first form is used for rowid tables.  The second form is used
105657  ** for WITHOUT ROWID tables.  In the second form, the primary key is
105658  ** (a,b,...)
105659  */
105660  if( pTab==pFKey->pFrom && nIncr>0 ){
105661    Expr *pNe;                    /* Expression (pLeft != pRight) */
105662    Expr *pLeft;                  /* Value from parent table row */
105663    Expr *pRight;                 /* Column ref to child table */
105664    if( HasRowid(pTab) ){
105665      pLeft = exprTableRegister(pParse, pTab, regData, -1);
105666      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
105667      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
105668    }else{
105669      Expr *pEq, *pAll = 0;
105670      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
105671      assert( pIdx!=0 );
105672      for(i=0; i<pPk->nKeyCol; i++){
105673        i16 iCol = pIdx->aiColumn[i];
105674        assert( iCol>=0 );
105675        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105676        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
105677        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105678        pAll = sqlite3ExprAnd(db, pAll, pEq);
105679      }
105680      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
105681    }
105682    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
105683  }
105684
105685  /* Resolve the references in the WHERE clause. */
105686  memset(&sNameContext, 0, sizeof(NameContext));
105687  sNameContext.pSrcList = pSrc;
105688  sNameContext.pParse = pParse;
105689  sqlite3ResolveExprNames(&sNameContext, pWhere);
105690
105691  /* Create VDBE to loop through the entries in pSrc that match the WHERE
105692  ** clause. For each row found, increment either the deferred or immediate
105693  ** foreign key constraint counter. */
105694  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
105695  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105696  if( pWInfo ){
105697    sqlite3WhereEnd(pWInfo);
105698  }
105699
105700  /* Clean up the WHERE clause constructed above. */
105701  sqlite3ExprDelete(db, pWhere);
105702  if( iFkIfZero ){
105703    sqlite3VdbeJumpHere(v, iFkIfZero);
105704  }
105705}
105706
105707/*
105708** This function returns a linked list of FKey objects (connected by
105709** FKey.pNextTo) holding all children of table pTab.  For example,
105710** given the following schema:
105711**
105712**   CREATE TABLE t1(a PRIMARY KEY);
105713**   CREATE TABLE t2(b REFERENCES t1(a);
105714**
105715** Calling this function with table "t1" as an argument returns a pointer
105716** to the FKey structure representing the foreign key constraint on table
105717** "t2". Calling this function with "t2" as the argument would return a
105718** NULL pointer (as there are no FK constraints for which t2 is the parent
105719** table).
105720*/
105721SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
105722  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
105723}
105724
105725/*
105726** The second argument is a Trigger structure allocated by the
105727** fkActionTrigger() routine. This function deletes the Trigger structure
105728** and all of its sub-components.
105729**
105730** The Trigger structure or any of its sub-components may be allocated from
105731** the lookaside buffer belonging to database handle dbMem.
105732*/
105733static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
105734  if( p ){
105735    TriggerStep *pStep = p->step_list;
105736    sqlite3ExprDelete(dbMem, pStep->pWhere);
105737    sqlite3ExprListDelete(dbMem, pStep->pExprList);
105738    sqlite3SelectDelete(dbMem, pStep->pSelect);
105739    sqlite3ExprDelete(dbMem, p->pWhen);
105740    sqlite3DbFree(dbMem, p);
105741  }
105742}
105743
105744/*
105745** This function is called to generate code that runs when table pTab is
105746** being dropped from the database. The SrcList passed as the second argument
105747** to this function contains a single entry guaranteed to resolve to
105748** table pTab.
105749**
105750** Normally, no code is required. However, if either
105751**
105752**   (a) The table is the parent table of a FK constraint, or
105753**   (b) The table is the child table of a deferred FK constraint and it is
105754**       determined at runtime that there are outstanding deferred FK
105755**       constraint violations in the database,
105756**
105757** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
105758** the table from the database. Triggers are disabled while running this
105759** DELETE, but foreign key actions are not.
105760*/
105761SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
105762  sqlite3 *db = pParse->db;
105763  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
105764    int iSkip = 0;
105765    Vdbe *v = sqlite3GetVdbe(pParse);
105766
105767    assert( v );                  /* VDBE has already been allocated */
105768    if( sqlite3FkReferences(pTab)==0 ){
105769      /* Search for a deferred foreign key constraint for which this table
105770      ** is the child table. If one cannot be found, return without
105771      ** generating any VDBE code. If one can be found, then jump over
105772      ** the entire DELETE if there are no outstanding deferred constraints
105773      ** when this statement is run.  */
105774      FKey *p;
105775      for(p=pTab->pFKey; p; p=p->pNextFrom){
105776        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
105777      }
105778      if( !p ) return;
105779      iSkip = sqlite3VdbeMakeLabel(v);
105780      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
105781    }
105782
105783    pParse->disableTriggers = 1;
105784    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
105785    pParse->disableTriggers = 0;
105786
105787    /* If the DELETE has generated immediate foreign key constraint
105788    ** violations, halt the VDBE and return an error at this point, before
105789    ** any modifications to the schema are made. This is because statement
105790    ** transactions are not able to rollback schema changes.
105791    **
105792    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
105793    ** the statement transaction will not be rolled back even if FK
105794    ** constraints are violated.
105795    */
105796    if( (db->flags & SQLITE_DeferFKs)==0 ){
105797      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
105798      VdbeCoverage(v);
105799      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
105800          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
105801    }
105802
105803    if( iSkip ){
105804      sqlite3VdbeResolveLabel(v, iSkip);
105805    }
105806  }
105807}
105808
105809
105810/*
105811** The second argument points to an FKey object representing a foreign key
105812** for which pTab is the child table. An UPDATE statement against pTab
105813** is currently being processed. For each column of the table that is
105814** actually updated, the corresponding element in the aChange[] array
105815** is zero or greater (if a column is unmodified the corresponding element
105816** is set to -1). If the rowid column is modified by the UPDATE statement
105817** the bChngRowid argument is non-zero.
105818**
105819** This function returns true if any of the columns that are part of the
105820** child key for FK constraint *p are modified.
105821*/
105822static int fkChildIsModified(
105823  Table *pTab,                    /* Table being updated */
105824  FKey *p,                        /* Foreign key for which pTab is the child */
105825  int *aChange,                   /* Array indicating modified columns */
105826  int bChngRowid                  /* True if rowid is modified by this update */
105827){
105828  int i;
105829  for(i=0; i<p->nCol; i++){
105830    int iChildKey = p->aCol[i].iFrom;
105831    if( aChange[iChildKey]>=0 ) return 1;
105832    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
105833  }
105834  return 0;
105835}
105836
105837/*
105838** The second argument points to an FKey object representing a foreign key
105839** for which pTab is the parent table. An UPDATE statement against pTab
105840** is currently being processed. For each column of the table that is
105841** actually updated, the corresponding element in the aChange[] array
105842** is zero or greater (if a column is unmodified the corresponding element
105843** is set to -1). If the rowid column is modified by the UPDATE statement
105844** the bChngRowid argument is non-zero.
105845**
105846** This function returns true if any of the columns that are part of the
105847** parent key for FK constraint *p are modified.
105848*/
105849static int fkParentIsModified(
105850  Table *pTab,
105851  FKey *p,
105852  int *aChange,
105853  int bChngRowid
105854){
105855  int i;
105856  for(i=0; i<p->nCol; i++){
105857    char *zKey = p->aCol[i].zCol;
105858    int iKey;
105859    for(iKey=0; iKey<pTab->nCol; iKey++){
105860      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
105861        Column *pCol = &pTab->aCol[iKey];
105862        if( zKey ){
105863          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
105864        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
105865          return 1;
105866        }
105867      }
105868    }
105869  }
105870  return 0;
105871}
105872
105873/*
105874** Return true if the parser passed as the first argument is being
105875** used to code a trigger that is really a "SET NULL" action belonging
105876** to trigger pFKey.
105877*/
105878static int isSetNullAction(Parse *pParse, FKey *pFKey){
105879  Parse *pTop = sqlite3ParseToplevel(pParse);
105880  if( pTop->pTriggerPrg ){
105881    Trigger *p = pTop->pTriggerPrg->pTrigger;
105882    if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
105883     || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
105884    ){
105885      return 1;
105886    }
105887  }
105888  return 0;
105889}
105890
105891/*
105892** This function is called when inserting, deleting or updating a row of
105893** table pTab to generate VDBE code to perform foreign key constraint
105894** processing for the operation.
105895**
105896** For a DELETE operation, parameter regOld is passed the index of the
105897** first register in an array of (pTab->nCol+1) registers containing the
105898** rowid of the row being deleted, followed by each of the column values
105899** of the row being deleted, from left to right. Parameter regNew is passed
105900** zero in this case.
105901**
105902** For an INSERT operation, regOld is passed zero and regNew is passed the
105903** first register of an array of (pTab->nCol+1) registers containing the new
105904** row data.
105905**
105906** For an UPDATE operation, this function is called twice. Once before
105907** the original record is deleted from the table using the calling convention
105908** described for DELETE. Then again after the original record is deleted
105909** but before the new record is inserted using the INSERT convention.
105910*/
105911SQLITE_PRIVATE void sqlite3FkCheck(
105912  Parse *pParse,                  /* Parse context */
105913  Table *pTab,                    /* Row is being deleted from this table */
105914  int regOld,                     /* Previous row data is stored here */
105915  int regNew,                     /* New row data is stored here */
105916  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
105917  int bChngRowid                  /* True if rowid is UPDATEd */
105918){
105919  sqlite3 *db = pParse->db;       /* Database handle */
105920  FKey *pFKey;                    /* Used to iterate through FKs */
105921  int iDb;                        /* Index of database containing pTab */
105922  const char *zDb;                /* Name of database containing pTab */
105923  int isIgnoreErrors = pParse->disableTriggers;
105924
105925  /* Exactly one of regOld and regNew should be non-zero. */
105926  assert( (regOld==0)!=(regNew==0) );
105927
105928  /* If foreign-keys are disabled, this function is a no-op. */
105929  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
105930
105931  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105932  zDb = db->aDb[iDb].zName;
105933
105934  /* Loop through all the foreign key constraints for which pTab is the
105935  ** child table (the table that the foreign key definition is part of).  */
105936  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
105937    Table *pTo;                   /* Parent table of foreign key pFKey */
105938    Index *pIdx = 0;              /* Index on key columns in pTo */
105939    int *aiFree = 0;
105940    int *aiCol;
105941    int iCol;
105942    int i;
105943    int bIgnore = 0;
105944
105945    if( aChange
105946     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
105947     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
105948    ){
105949      continue;
105950    }
105951
105952    /* Find the parent table of this foreign key. Also find a unique index
105953    ** on the parent key columns in the parent table. If either of these
105954    ** schema items cannot be located, set an error in pParse and return
105955    ** early.  */
105956    if( pParse->disableTriggers ){
105957      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
105958    }else{
105959      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
105960    }
105961    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
105962      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
105963      if( !isIgnoreErrors || db->mallocFailed ) return;
105964      if( pTo==0 ){
105965        /* If isIgnoreErrors is true, then a table is being dropped. In this
105966        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
105967        ** before actually dropping it in order to check FK constraints.
105968        ** If the parent table of an FK constraint on the current table is
105969        ** missing, behave as if it is empty. i.e. decrement the relevant
105970        ** FK counter for each row of the current table with non-NULL keys.
105971        */
105972        Vdbe *v = sqlite3GetVdbe(pParse);
105973        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
105974        for(i=0; i<pFKey->nCol; i++){
105975          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
105976          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
105977        }
105978        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
105979      }
105980      continue;
105981    }
105982    assert( pFKey->nCol==1 || (aiFree && pIdx) );
105983
105984    if( aiFree ){
105985      aiCol = aiFree;
105986    }else{
105987      iCol = pFKey->aCol[0].iFrom;
105988      aiCol = &iCol;
105989    }
105990    for(i=0; i<pFKey->nCol; i++){
105991      if( aiCol[i]==pTab->iPKey ){
105992        aiCol[i] = -1;
105993      }
105994      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
105995#ifndef SQLITE_OMIT_AUTHORIZATION
105996      /* Request permission to read the parent key columns. If the
105997      ** authorization callback returns SQLITE_IGNORE, behave as if any
105998      ** values read from the parent table are NULL. */
105999      if( db->xAuth ){
106000        int rcauth;
106001        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
106002        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
106003        bIgnore = (rcauth==SQLITE_IGNORE);
106004      }
106005#endif
106006    }
106007
106008    /* Take a shared-cache advisory read-lock on the parent table. Allocate
106009    ** a cursor to use to search the unique index on the parent key columns
106010    ** in the parent table.  */
106011    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
106012    pParse->nTab++;
106013
106014    if( regOld!=0 ){
106015      /* A row is being removed from the child table. Search for the parent.
106016      ** If the parent does not exist, removing the child row resolves an
106017      ** outstanding foreign key constraint violation. */
106018      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
106019    }
106020    if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
106021      /* A row is being added to the child table. If a parent row cannot
106022      ** be found, adding the child row has violated the FK constraint.
106023      **
106024      ** If this operation is being performed as part of a trigger program
106025      ** that is actually a "SET NULL" action belonging to this very
106026      ** foreign key, then omit this scan altogether. As all child key
106027      ** values are guaranteed to be NULL, it is not possible for adding
106028      ** this row to cause an FK violation.  */
106029      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
106030    }
106031
106032    sqlite3DbFree(db, aiFree);
106033  }
106034
106035  /* Loop through all the foreign key constraints that refer to this table.
106036  ** (the "child" constraints) */
106037  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106038    Index *pIdx = 0;              /* Foreign key index for pFKey */
106039    SrcList *pSrc;
106040    int *aiCol = 0;
106041
106042    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
106043      continue;
106044    }
106045
106046    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
106047     && !pParse->pToplevel && !pParse->isMultiWrite
106048    ){
106049      assert( regOld==0 && regNew!=0 );
106050      /* Inserting a single row into a parent table cannot cause (or fix)
106051      ** an immediate foreign key violation. So do nothing in this case.  */
106052      continue;
106053    }
106054
106055    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
106056      if( !isIgnoreErrors || db->mallocFailed ) return;
106057      continue;
106058    }
106059    assert( aiCol || pFKey->nCol==1 );
106060
106061    /* Create a SrcList structure containing the child table.  We need the
106062    ** child table as a SrcList for sqlite3WhereBegin() */
106063    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
106064    if( pSrc ){
106065      struct SrcList_item *pItem = pSrc->a;
106066      pItem->pTab = pFKey->pFrom;
106067      pItem->zName = pFKey->pFrom->zName;
106068      pItem->pTab->nRef++;
106069      pItem->iCursor = pParse->nTab++;
106070
106071      if( regNew!=0 ){
106072        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
106073      }
106074      if( regOld!=0 ){
106075        int eAction = pFKey->aAction[aChange!=0];
106076        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
106077        /* If this is a deferred FK constraint, or a CASCADE or SET NULL
106078        ** action applies, then any foreign key violations caused by
106079        ** removing the parent key will be rectified by the action trigger.
106080        ** So do not set the "may-abort" flag in this case.
106081        **
106082        ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
106083        ** may-abort flag will eventually be set on this statement anyway
106084        ** (when this function is called as part of processing the UPDATE
106085        ** within the action trigger).
106086        **
106087        ** Note 2: At first glance it may seem like SQLite could simply omit
106088        ** all OP_FkCounter related scans when either CASCADE or SET NULL
106089        ** applies. The trouble starts if the CASCADE or SET NULL action
106090        ** trigger causes other triggers or action rules attached to the
106091        ** child table to fire. In these cases the fk constraint counters
106092        ** might be set incorrectly if any OP_FkCounter related scans are
106093        ** omitted.  */
106094        if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
106095          sqlite3MayAbort(pParse);
106096        }
106097      }
106098      pItem->zName = 0;
106099      sqlite3SrcListDelete(db, pSrc);
106100    }
106101    sqlite3DbFree(db, aiCol);
106102  }
106103}
106104
106105#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
106106
106107/*
106108** This function is called before generating code to update or delete a
106109** row contained in table pTab.
106110*/
106111SQLITE_PRIVATE u32 sqlite3FkOldmask(
106112  Parse *pParse,                  /* Parse context */
106113  Table *pTab                     /* Table being modified */
106114){
106115  u32 mask = 0;
106116  if( pParse->db->flags&SQLITE_ForeignKeys ){
106117    FKey *p;
106118    int i;
106119    for(p=pTab->pFKey; p; p=p->pNextFrom){
106120      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
106121    }
106122    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
106123      Index *pIdx = 0;
106124      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
106125      if( pIdx ){
106126        for(i=0; i<pIdx->nKeyCol; i++){
106127          assert( pIdx->aiColumn[i]>=0 );
106128          mask |= COLUMN_MASK(pIdx->aiColumn[i]);
106129        }
106130      }
106131    }
106132  }
106133  return mask;
106134}
106135
106136
106137/*
106138** This function is called before generating code to update or delete a
106139** row contained in table pTab. If the operation is a DELETE, then
106140** parameter aChange is passed a NULL value. For an UPDATE, aChange points
106141** to an array of size N, where N is the number of columns in table pTab.
106142** If the i'th column is not modified by the UPDATE, then the corresponding
106143** entry in the aChange[] array is set to -1. If the column is modified,
106144** the value is 0 or greater. Parameter chngRowid is set to true if the
106145** UPDATE statement modifies the rowid fields of the table.
106146**
106147** If any foreign key processing will be required, this function returns
106148** true. If there is no foreign key related processing, this function
106149** returns false.
106150*/
106151SQLITE_PRIVATE int sqlite3FkRequired(
106152  Parse *pParse,                  /* Parse context */
106153  Table *pTab,                    /* Table being modified */
106154  int *aChange,                   /* Non-NULL for UPDATE operations */
106155  int chngRowid                   /* True for UPDATE that affects rowid */
106156){
106157  if( pParse->db->flags&SQLITE_ForeignKeys ){
106158    if( !aChange ){
106159      /* A DELETE operation. Foreign key processing is required if the
106160      ** table in question is either the child or parent table for any
106161      ** foreign key constraint.  */
106162      return (sqlite3FkReferences(pTab) || pTab->pFKey);
106163    }else{
106164      /* This is an UPDATE. Foreign key processing is only required if the
106165      ** operation modifies one or more child or parent key columns. */
106166      FKey *p;
106167
106168      /* Check if any child key columns are being modified. */
106169      for(p=pTab->pFKey; p; p=p->pNextFrom){
106170        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
106171      }
106172
106173      /* Check if any parent key columns are being modified. */
106174      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
106175        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
106176      }
106177    }
106178  }
106179  return 0;
106180}
106181
106182/*
106183** This function is called when an UPDATE or DELETE operation is being
106184** compiled on table pTab, which is the parent table of foreign-key pFKey.
106185** If the current operation is an UPDATE, then the pChanges parameter is
106186** passed a pointer to the list of columns being modified. If it is a
106187** DELETE, pChanges is passed a NULL pointer.
106188**
106189** It returns a pointer to a Trigger structure containing a trigger
106190** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
106191** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
106192** returned (these actions require no special handling by the triggers
106193** sub-system, code for them is created by fkScanChildren()).
106194**
106195** For example, if pFKey is the foreign key and pTab is table "p" in
106196** the following schema:
106197**
106198**   CREATE TABLE p(pk PRIMARY KEY);
106199**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
106200**
106201** then the returned trigger structure is equivalent to:
106202**
106203**   CREATE TRIGGER ... DELETE ON p BEGIN
106204**     DELETE FROM c WHERE ck = old.pk;
106205**   END;
106206**
106207** The returned pointer is cached as part of the foreign key object. It
106208** is eventually freed along with the rest of the foreign key object by
106209** sqlite3FkDelete().
106210*/
106211static Trigger *fkActionTrigger(
106212  Parse *pParse,                  /* Parse context */
106213  Table *pTab,                    /* Table being updated or deleted from */
106214  FKey *pFKey,                    /* Foreign key to get action for */
106215  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
106216){
106217  sqlite3 *db = pParse->db;       /* Database handle */
106218  int action;                     /* One of OE_None, OE_Cascade etc. */
106219  Trigger *pTrigger;              /* Trigger definition to return */
106220  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
106221
106222  action = pFKey->aAction[iAction];
106223  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
106224    return 0;
106225  }
106226  pTrigger = pFKey->apTrigger[iAction];
106227
106228  if( action!=OE_None && !pTrigger ){
106229    char const *zFrom;            /* Name of child table */
106230    int nFrom;                    /* Length in bytes of zFrom */
106231    Index *pIdx = 0;              /* Parent key index for this FK */
106232    int *aiCol = 0;               /* child table cols -> parent key cols */
106233    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
106234    Expr *pWhere = 0;             /* WHERE clause of trigger step */
106235    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
106236    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
106237    int i;                        /* Iterator variable */
106238    Expr *pWhen = 0;              /* WHEN clause for the trigger */
106239
106240    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
106241    assert( aiCol || pFKey->nCol==1 );
106242
106243    for(i=0; i<pFKey->nCol; i++){
106244      Token tOld = { "old", 3 };  /* Literal "old" token */
106245      Token tNew = { "new", 3 };  /* Literal "new" token */
106246      Token tFromCol;             /* Name of column in child table */
106247      Token tToCol;               /* Name of column in parent table */
106248      int iFromCol;               /* Idx of column in child table */
106249      Expr *pEq;                  /* tFromCol = OLD.tToCol */
106250
106251      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
106252      assert( iFromCol>=0 );
106253      assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
106254      assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
106255      sqlite3TokenInit(&tToCol,
106256                   pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
106257      sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
106258
106259      /* Create the expression "OLD.zToCol = zFromCol". It is important
106260      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
106261      ** that the affinity and collation sequence associated with the
106262      ** parent table are used for the comparison. */
106263      pEq = sqlite3PExpr(pParse, TK_EQ,
106264          sqlite3PExpr(pParse, TK_DOT,
106265            sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
106266            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
106267          , 0),
106268          sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
106269      , 0);
106270      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
106271
106272      /* For ON UPDATE, construct the next term of the WHEN clause.
106273      ** The final WHEN clause will be like this:
106274      **
106275      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
106276      */
106277      if( pChanges ){
106278        pEq = sqlite3PExpr(pParse, TK_IS,
106279            sqlite3PExpr(pParse, TK_DOT,
106280              sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
106281              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
106282              0),
106283            sqlite3PExpr(pParse, TK_DOT,
106284              sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
106285              sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
106286              0),
106287            0);
106288        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
106289      }
106290
106291      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
106292        Expr *pNew;
106293        if( action==OE_Cascade ){
106294          pNew = sqlite3PExpr(pParse, TK_DOT,
106295            sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
106296            sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
106297          , 0);
106298        }else if( action==OE_SetDflt ){
106299          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
106300          if( pDflt ){
106301            pNew = sqlite3ExprDup(db, pDflt, 0);
106302          }else{
106303            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
106304          }
106305        }else{
106306          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
106307        }
106308        pList = sqlite3ExprListAppend(pParse, pList, pNew);
106309        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
106310      }
106311    }
106312    sqlite3DbFree(db, aiCol);
106313
106314    zFrom = pFKey->pFrom->zName;
106315    nFrom = sqlite3Strlen30(zFrom);
106316
106317    if( action==OE_Restrict ){
106318      Token tFrom;
106319      Expr *pRaise;
106320
106321      tFrom.z = zFrom;
106322      tFrom.n = nFrom;
106323      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
106324      if( pRaise ){
106325        pRaise->affinity = OE_Abort;
106326      }
106327      pSelect = sqlite3SelectNew(pParse,
106328          sqlite3ExprListAppend(pParse, 0, pRaise),
106329          sqlite3SrcListAppend(db, 0, &tFrom, 0),
106330          pWhere,
106331          0, 0, 0, 0, 0, 0
106332      );
106333      pWhere = 0;
106334    }
106335
106336    /* Disable lookaside memory allocation */
106337    db->lookaside.bDisable++;
106338
106339    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
106340        sizeof(Trigger) +         /* struct Trigger */
106341        sizeof(TriggerStep) +     /* Single step in trigger program */
106342        nFrom + 1                 /* Space for pStep->zTarget */
106343    );
106344    if( pTrigger ){
106345      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
106346      pStep->zTarget = (char *)&pStep[1];
106347      memcpy((char *)pStep->zTarget, zFrom, nFrom);
106348
106349      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
106350      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
106351      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
106352      if( pWhen ){
106353        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
106354        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
106355      }
106356    }
106357
106358    /* Re-enable the lookaside buffer, if it was disabled earlier. */
106359    db->lookaside.bDisable--;
106360
106361    sqlite3ExprDelete(db, pWhere);
106362    sqlite3ExprDelete(db, pWhen);
106363    sqlite3ExprListDelete(db, pList);
106364    sqlite3SelectDelete(db, pSelect);
106365    if( db->mallocFailed==1 ){
106366      fkTriggerDelete(db, pTrigger);
106367      return 0;
106368    }
106369    assert( pStep!=0 );
106370
106371    switch( action ){
106372      case OE_Restrict:
106373        pStep->op = TK_SELECT;
106374        break;
106375      case OE_Cascade:
106376        if( !pChanges ){
106377          pStep->op = TK_DELETE;
106378          break;
106379        }
106380      default:
106381        pStep->op = TK_UPDATE;
106382    }
106383    pStep->pTrig = pTrigger;
106384    pTrigger->pSchema = pTab->pSchema;
106385    pTrigger->pTabSchema = pTab->pSchema;
106386    pFKey->apTrigger[iAction] = pTrigger;
106387    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
106388  }
106389
106390  return pTrigger;
106391}
106392
106393/*
106394** This function is called when deleting or updating a row to implement
106395** any required CASCADE, SET NULL or SET DEFAULT actions.
106396*/
106397SQLITE_PRIVATE void sqlite3FkActions(
106398  Parse *pParse,                  /* Parse context */
106399  Table *pTab,                    /* Table being updated or deleted from */
106400  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
106401  int regOld,                     /* Address of array containing old row */
106402  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
106403  int bChngRowid                  /* True if rowid is UPDATEd */
106404){
106405  /* If foreign-key support is enabled, iterate through all FKs that
106406  ** refer to table pTab. If there is an action associated with the FK
106407  ** for this operation (either update or delete), invoke the associated
106408  ** trigger sub-program.  */
106409  if( pParse->db->flags&SQLITE_ForeignKeys ){
106410    FKey *pFKey;                  /* Iterator variable */
106411    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106412      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
106413        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
106414        if( pAct ){
106415          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
106416        }
106417      }
106418    }
106419  }
106420}
106421
106422#endif /* ifndef SQLITE_OMIT_TRIGGER */
106423
106424/*
106425** Free all memory associated with foreign key definitions attached to
106426** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
106427** hash table.
106428*/
106429SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
106430  FKey *pFKey;                    /* Iterator variable */
106431  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
106432
106433  assert( db==0 || IsVirtual(pTab)
106434         || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
106435  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
106436
106437    /* Remove the FK from the fkeyHash hash table. */
106438    if( !db || db->pnBytesFreed==0 ){
106439      if( pFKey->pPrevTo ){
106440        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
106441      }else{
106442        void *p = (void *)pFKey->pNextTo;
106443        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
106444        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
106445      }
106446      if( pFKey->pNextTo ){
106447        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
106448      }
106449    }
106450
106451    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
106452    ** classified as either immediate or deferred.
106453    */
106454    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
106455
106456    /* Delete any triggers created to implement actions for this FK. */
106457#ifndef SQLITE_OMIT_TRIGGER
106458    fkTriggerDelete(db, pFKey->apTrigger[0]);
106459    fkTriggerDelete(db, pFKey->apTrigger[1]);
106460#endif
106461
106462    pNext = pFKey->pNextFrom;
106463    sqlite3DbFree(db, pFKey);
106464  }
106465}
106466#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
106467
106468/************** End of fkey.c ************************************************/
106469/************** Begin file insert.c ******************************************/
106470/*
106471** 2001 September 15
106472**
106473** The author disclaims copyright to this source code.  In place of
106474** a legal notice, here is a blessing:
106475**
106476**    May you do good and not evil.
106477**    May you find forgiveness for yourself and forgive others.
106478**    May you share freely, never taking more than you give.
106479**
106480*************************************************************************
106481** This file contains C code routines that are called by the parser
106482** to handle INSERT statements in SQLite.
106483*/
106484/* #include "sqliteInt.h" */
106485
106486/*
106487** Generate code that will
106488**
106489**   (1) acquire a lock for table pTab then
106490**   (2) open pTab as cursor iCur.
106491**
106492** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
106493** for that table that is actually opened.
106494*/
106495SQLITE_PRIVATE void sqlite3OpenTable(
106496  Parse *pParse,  /* Generate code into this VDBE */
106497  int iCur,       /* The cursor number of the table */
106498  int iDb,        /* The database index in sqlite3.aDb[] */
106499  Table *pTab,    /* The table to be opened */
106500  int opcode      /* OP_OpenRead or OP_OpenWrite */
106501){
106502  Vdbe *v;
106503  assert( !IsVirtual(pTab) );
106504  v = sqlite3GetVdbe(pParse);
106505  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
106506  sqlite3TableLock(pParse, iDb, pTab->tnum,
106507                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
106508  if( HasRowid(pTab) ){
106509    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
106510    VdbeComment((v, "%s", pTab->zName));
106511  }else{
106512    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106513    assert( pPk!=0 );
106514    assert( pPk->tnum==pTab->tnum );
106515    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
106516    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
106517    VdbeComment((v, "%s", pTab->zName));
106518  }
106519}
106520
106521/*
106522** Return a pointer to the column affinity string associated with index
106523** pIdx. A column affinity string has one character for each column in
106524** the table, according to the affinity of the column:
106525**
106526**  Character      Column affinity
106527**  ------------------------------
106528**  'A'            BLOB
106529**  'B'            TEXT
106530**  'C'            NUMERIC
106531**  'D'            INTEGER
106532**  'F'            REAL
106533**
106534** An extra 'D' is appended to the end of the string to cover the
106535** rowid that appears as the last column in every index.
106536**
106537** Memory for the buffer containing the column index affinity string
106538** is managed along with the rest of the Index structure. It will be
106539** released when sqlite3DeleteIndex() is called.
106540*/
106541SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
106542  if( !pIdx->zColAff ){
106543    /* The first time a column affinity string for a particular index is
106544    ** required, it is allocated and populated here. It is then stored as
106545    ** a member of the Index structure for subsequent use.
106546    **
106547    ** The column affinity string will eventually be deleted by
106548    ** sqliteDeleteIndex() when the Index structure itself is cleaned
106549    ** up.
106550    */
106551    int n;
106552    Table *pTab = pIdx->pTable;
106553    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
106554    if( !pIdx->zColAff ){
106555      sqlite3OomFault(db);
106556      return 0;
106557    }
106558    for(n=0; n<pIdx->nColumn; n++){
106559      i16 x = pIdx->aiColumn[n];
106560      if( x>=0 ){
106561        pIdx->zColAff[n] = pTab->aCol[x].affinity;
106562      }else if( x==XN_ROWID ){
106563        pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
106564      }else{
106565        char aff;
106566        assert( x==XN_EXPR );
106567        assert( pIdx->aColExpr!=0 );
106568        aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
106569        if( aff==0 ) aff = SQLITE_AFF_BLOB;
106570        pIdx->zColAff[n] = aff;
106571      }
106572    }
106573    pIdx->zColAff[n] = 0;
106574  }
106575
106576  return pIdx->zColAff;
106577}
106578
106579/*
106580** Compute the affinity string for table pTab, if it has not already been
106581** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
106582**
106583** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
106584** if iReg>0 then code an OP_Affinity opcode that will set the affinities
106585** for register iReg and following.  Or if affinities exists and iReg==0,
106586** then just set the P4 operand of the previous opcode (which should  be
106587** an OP_MakeRecord) to the affinity string.
106588**
106589** A column affinity string has one character per column:
106590**
106591**  Character      Column affinity
106592**  ------------------------------
106593**  'A'            BLOB
106594**  'B'            TEXT
106595**  'C'            NUMERIC
106596**  'D'            INTEGER
106597**  'E'            REAL
106598*/
106599SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
106600  int i;
106601  char *zColAff = pTab->zColAff;
106602  if( zColAff==0 ){
106603    sqlite3 *db = sqlite3VdbeDb(v);
106604    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
106605    if( !zColAff ){
106606      sqlite3OomFault(db);
106607      return;
106608    }
106609
106610    for(i=0; i<pTab->nCol; i++){
106611      zColAff[i] = pTab->aCol[i].affinity;
106612    }
106613    do{
106614      zColAff[i--] = 0;
106615    }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
106616    pTab->zColAff = zColAff;
106617  }
106618  i = sqlite3Strlen30(zColAff);
106619  if( i ){
106620    if( iReg ){
106621      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
106622    }else{
106623      sqlite3VdbeChangeP4(v, -1, zColAff, i);
106624    }
106625  }
106626}
106627
106628/*
106629** Return non-zero if the table pTab in database iDb or any of its indices
106630** have been opened at any point in the VDBE program. This is used to see if
106631** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
106632** run without using a temporary table for the results of the SELECT.
106633*/
106634static int readsTable(Parse *p, int iDb, Table *pTab){
106635  Vdbe *v = sqlite3GetVdbe(p);
106636  int i;
106637  int iEnd = sqlite3VdbeCurrentAddr(v);
106638#ifndef SQLITE_OMIT_VIRTUALTABLE
106639  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
106640#endif
106641
106642  for(i=1; i<iEnd; i++){
106643    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
106644    assert( pOp!=0 );
106645    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
106646      Index *pIndex;
106647      int tnum = pOp->p2;
106648      if( tnum==pTab->tnum ){
106649        return 1;
106650      }
106651      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
106652        if( tnum==pIndex->tnum ){
106653          return 1;
106654        }
106655      }
106656    }
106657#ifndef SQLITE_OMIT_VIRTUALTABLE
106658    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
106659      assert( pOp->p4.pVtab!=0 );
106660      assert( pOp->p4type==P4_VTAB );
106661      return 1;
106662    }
106663#endif
106664  }
106665  return 0;
106666}
106667
106668#ifndef SQLITE_OMIT_AUTOINCREMENT
106669/*
106670** Locate or create an AutoincInfo structure associated with table pTab
106671** which is in database iDb.  Return the register number for the register
106672** that holds the maximum rowid.
106673**
106674** There is at most one AutoincInfo structure per table even if the
106675** same table is autoincremented multiple times due to inserts within
106676** triggers.  A new AutoincInfo structure is created if this is the
106677** first use of table pTab.  On 2nd and subsequent uses, the original
106678** AutoincInfo structure is used.
106679**
106680** Three memory locations are allocated:
106681**
106682**   (1)  Register to hold the name of the pTab table.
106683**   (2)  Register to hold the maximum ROWID of pTab.
106684**   (3)  Register to hold the rowid in sqlite_sequence of pTab
106685**
106686** The 2nd register is the one that is returned.  That is all the
106687** insert routine needs to know about.
106688*/
106689static int autoIncBegin(
106690  Parse *pParse,      /* Parsing context */
106691  int iDb,            /* Index of the database holding pTab */
106692  Table *pTab         /* The table we are writing to */
106693){
106694  int memId = 0;      /* Register holding maximum rowid */
106695  if( pTab->tabFlags & TF_Autoincrement ){
106696    Parse *pToplevel = sqlite3ParseToplevel(pParse);
106697    AutoincInfo *pInfo;
106698
106699    pInfo = pToplevel->pAinc;
106700    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
106701    if( pInfo==0 ){
106702      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
106703      if( pInfo==0 ) return 0;
106704      pInfo->pNext = pToplevel->pAinc;
106705      pToplevel->pAinc = pInfo;
106706      pInfo->pTab = pTab;
106707      pInfo->iDb = iDb;
106708      pToplevel->nMem++;                  /* Register to hold name of table */
106709      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
106710      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
106711    }
106712    memId = pInfo->regCtr;
106713  }
106714  return memId;
106715}
106716
106717/*
106718** This routine generates code that will initialize all of the
106719** register used by the autoincrement tracker.
106720*/
106721SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
106722  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
106723  sqlite3 *db = pParse->db;  /* The database connection */
106724  Db *pDb;                   /* Database only autoinc table */
106725  int memId;                 /* Register holding max rowid */
106726  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
106727
106728  /* This routine is never called during trigger-generation.  It is
106729  ** only called from the top-level */
106730  assert( pParse->pTriggerTab==0 );
106731  assert( sqlite3IsToplevel(pParse) );
106732
106733  assert( v );   /* We failed long ago if this is not so */
106734  for(p = pParse->pAinc; p; p = p->pNext){
106735    static const int iLn = VDBE_OFFSET_LINENO(2);
106736    static const VdbeOpList autoInc[] = {
106737      /* 0  */ {OP_Null,    0,  0, 0},
106738      /* 1  */ {OP_Rewind,  0,  9, 0},
106739      /* 2  */ {OP_Column,  0,  0, 0},
106740      /* 3  */ {OP_Ne,      0,  7, 0},
106741      /* 4  */ {OP_Rowid,   0,  0, 0},
106742      /* 5  */ {OP_Column,  0,  1, 0},
106743      /* 6  */ {OP_Goto,    0,  9, 0},
106744      /* 7  */ {OP_Next,    0,  2, 0},
106745      /* 8  */ {OP_Integer, 0,  0, 0},
106746      /* 9  */ {OP_Close,   0,  0, 0}
106747    };
106748    VdbeOp *aOp;
106749    pDb = &db->aDb[p->iDb];
106750    memId = p->regCtr;
106751    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106752    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
106753    sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
106754    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
106755    if( aOp==0 ) break;
106756    aOp[0].p2 = memId;
106757    aOp[0].p3 = memId+1;
106758    aOp[2].p3 = memId;
106759    aOp[3].p1 = memId-1;
106760    aOp[3].p3 = memId;
106761    aOp[3].p5 = SQLITE_JUMPIFNULL;
106762    aOp[4].p2 = memId+1;
106763    aOp[5].p3 = memId;
106764    aOp[8].p2 = memId;
106765  }
106766}
106767
106768/*
106769** Update the maximum rowid for an autoincrement calculation.
106770**
106771** This routine should be called when the regRowid register holds a
106772** new rowid that is about to be inserted.  If that new rowid is
106773** larger than the maximum rowid in the memId memory cell, then the
106774** memory cell is updated.
106775*/
106776static void autoIncStep(Parse *pParse, int memId, int regRowid){
106777  if( memId>0 ){
106778    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
106779  }
106780}
106781
106782/*
106783** This routine generates the code needed to write autoincrement
106784** maximum rowid values back into the sqlite_sequence register.
106785** Every statement that might do an INSERT into an autoincrement
106786** table (either directly or through triggers) needs to call this
106787** routine just before the "exit" code.
106788*/
106789static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
106790  AutoincInfo *p;
106791  Vdbe *v = pParse->pVdbe;
106792  sqlite3 *db = pParse->db;
106793
106794  assert( v );
106795  for(p = pParse->pAinc; p; p = p->pNext){
106796    static const int iLn = VDBE_OFFSET_LINENO(2);
106797    static const VdbeOpList autoIncEnd[] = {
106798      /* 0 */ {OP_NotNull,     0, 2, 0},
106799      /* 1 */ {OP_NewRowid,    0, 0, 0},
106800      /* 2 */ {OP_MakeRecord,  0, 2, 0},
106801      /* 3 */ {OP_Insert,      0, 0, 0},
106802      /* 4 */ {OP_Close,       0, 0, 0}
106803    };
106804    VdbeOp *aOp;
106805    Db *pDb = &db->aDb[p->iDb];
106806    int iRec;
106807    int memId = p->regCtr;
106808
106809    iRec = sqlite3GetTempReg(pParse);
106810    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106811    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
106812    aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
106813    if( aOp==0 ) break;
106814    aOp[0].p1 = memId+1;
106815    aOp[1].p2 = memId+1;
106816    aOp[2].p1 = memId-1;
106817    aOp[2].p3 = iRec;
106818    aOp[3].p2 = iRec;
106819    aOp[3].p3 = memId+1;
106820    aOp[3].p5 = OPFLAG_APPEND;
106821    sqlite3ReleaseTempReg(pParse, iRec);
106822  }
106823}
106824SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
106825  if( pParse->pAinc ) autoIncrementEnd(pParse);
106826}
106827#else
106828/*
106829** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
106830** above are all no-ops
106831*/
106832# define autoIncBegin(A,B,C) (0)
106833# define autoIncStep(A,B,C)
106834#endif /* SQLITE_OMIT_AUTOINCREMENT */
106835
106836
106837/* Forward declaration */
106838static int xferOptimization(
106839  Parse *pParse,        /* Parser context */
106840  Table *pDest,         /* The table we are inserting into */
106841  Select *pSelect,      /* A SELECT statement to use as the data source */
106842  int onError,          /* How to handle constraint errors */
106843  int iDbDest           /* The database of pDest */
106844);
106845
106846/*
106847** This routine is called to handle SQL of the following forms:
106848**
106849**    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
106850**    insert into TABLE (IDLIST) select
106851**    insert into TABLE (IDLIST) default values
106852**
106853** The IDLIST following the table name is always optional.  If omitted,
106854** then a list of all (non-hidden) columns for the table is substituted.
106855** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
106856** is omitted.
106857**
106858** For the pSelect parameter holds the values to be inserted for the
106859** first two forms shown above.  A VALUES clause is really just short-hand
106860** for a SELECT statement that omits the FROM clause and everything else
106861** that follows.  If the pSelect parameter is NULL, that means that the
106862** DEFAULT VALUES form of the INSERT statement is intended.
106863**
106864** The code generated follows one of four templates.  For a simple
106865** insert with data coming from a single-row VALUES clause, the code executes
106866** once straight down through.  Pseudo-code follows (we call this
106867** the "1st template"):
106868**
106869**         open write cursor to <table> and its indices
106870**         put VALUES clause expressions into registers
106871**         write the resulting record into <table>
106872**         cleanup
106873**
106874** The three remaining templates assume the statement is of the form
106875**
106876**   INSERT INTO <table> SELECT ...
106877**
106878** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
106879** in other words if the SELECT pulls all columns from a single table
106880** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
106881** if <table2> and <table1> are distinct tables but have identical
106882** schemas, including all the same indices, then a special optimization
106883** is invoked that copies raw records from <table2> over to <table1>.
106884** See the xferOptimization() function for the implementation of this
106885** template.  This is the 2nd template.
106886**
106887**         open a write cursor to <table>
106888**         open read cursor on <table2>
106889**         transfer all records in <table2> over to <table>
106890**         close cursors
106891**         foreach index on <table>
106892**           open a write cursor on the <table> index
106893**           open a read cursor on the corresponding <table2> index
106894**           transfer all records from the read to the write cursors
106895**           close cursors
106896**         end foreach
106897**
106898** The 3rd template is for when the second template does not apply
106899** and the SELECT clause does not read from <table> at any time.
106900** The generated code follows this template:
106901**
106902**         X <- A
106903**         goto B
106904**      A: setup for the SELECT
106905**         loop over the rows in the SELECT
106906**           load values into registers R..R+n
106907**           yield X
106908**         end loop
106909**         cleanup after the SELECT
106910**         end-coroutine X
106911**      B: open write cursor to <table> and its indices
106912**      C: yield X, at EOF goto D
106913**         insert the select result into <table> from R..R+n
106914**         goto C
106915**      D: cleanup
106916**
106917** The 4th template is used if the insert statement takes its
106918** values from a SELECT but the data is being inserted into a table
106919** that is also read as part of the SELECT.  In the third form,
106920** we have to use an intermediate table to store the results of
106921** the select.  The template is like this:
106922**
106923**         X <- A
106924**         goto B
106925**      A: setup for the SELECT
106926**         loop over the tables in the SELECT
106927**           load value into register R..R+n
106928**           yield X
106929**         end loop
106930**         cleanup after the SELECT
106931**         end co-routine R
106932**      B: open temp table
106933**      L: yield X, at EOF goto M
106934**         insert row from R..R+n into temp table
106935**         goto L
106936**      M: open write cursor to <table> and its indices
106937**         rewind temp table
106938**      C: loop over rows of intermediate table
106939**           transfer values form intermediate table into <table>
106940**         end loop
106941**      D: cleanup
106942*/
106943SQLITE_PRIVATE void sqlite3Insert(
106944  Parse *pParse,        /* Parser context */
106945  SrcList *pTabList,    /* Name of table into which we are inserting */
106946  Select *pSelect,      /* A SELECT statement to use as the data source */
106947  IdList *pColumn,      /* Column names corresponding to IDLIST. */
106948  int onError           /* How to handle constraint errors */
106949){
106950  sqlite3 *db;          /* The main database structure */
106951  Table *pTab;          /* The table to insert into.  aka TABLE */
106952  char *zTab;           /* Name of the table into which we are inserting */
106953  const char *zDb;      /* Name of the database holding this table */
106954  int i, j, idx;        /* Loop counters */
106955  Vdbe *v;              /* Generate code into this virtual machine */
106956  Index *pIdx;          /* For looping over indices of the table */
106957  int nColumn;          /* Number of columns in the data */
106958  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
106959  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
106960  int iIdxCur = 0;      /* First index cursor */
106961  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
106962  int endOfLoop;        /* Label for the end of the insertion loop */
106963  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
106964  int addrInsTop = 0;   /* Jump to label "D" */
106965  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
106966  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
106967  int iDb;              /* Index of database holding TABLE */
106968  Db *pDb;              /* The database containing table being inserted into */
106969  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
106970  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
106971  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
106972  u8 bIdListInOrder;    /* True if IDLIST is in table order */
106973  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
106974
106975  /* Register allocations */
106976  int regFromSelect = 0;/* Base register for data coming from SELECT */
106977  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
106978  int regRowCount = 0;  /* Memory cell used for the row counter */
106979  int regIns;           /* Block of regs holding rowid+data being inserted */
106980  int regRowid;         /* registers holding insert rowid */
106981  int regData;          /* register holding first column to insert */
106982  int *aRegIdx = 0;     /* One register allocated to each index */
106983
106984#ifndef SQLITE_OMIT_TRIGGER
106985  int isView;                 /* True if attempting to insert into a view */
106986  Trigger *pTrigger;          /* List of triggers on pTab, if required */
106987  int tmask;                  /* Mask of trigger times */
106988#endif
106989
106990  db = pParse->db;
106991  memset(&dest, 0, sizeof(dest));
106992  if( pParse->nErr || db->mallocFailed ){
106993    goto insert_cleanup;
106994  }
106995
106996  /* If the Select object is really just a simple VALUES() list with a
106997  ** single row (the common case) then keep that one row of values
106998  ** and discard the other (unused) parts of the pSelect object
106999  */
107000  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
107001    pList = pSelect->pEList;
107002    pSelect->pEList = 0;
107003    sqlite3SelectDelete(db, pSelect);
107004    pSelect = 0;
107005  }
107006
107007  /* Locate the table into which we will be inserting new information.
107008  */
107009  assert( pTabList->nSrc==1 );
107010  zTab = pTabList->a[0].zName;
107011  if( NEVER(zTab==0) ) goto insert_cleanup;
107012  pTab = sqlite3SrcListLookup(pParse, pTabList);
107013  if( pTab==0 ){
107014    goto insert_cleanup;
107015  }
107016  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107017  assert( iDb<db->nDb );
107018  pDb = &db->aDb[iDb];
107019  zDb = pDb->zName;
107020  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
107021    goto insert_cleanup;
107022  }
107023  withoutRowid = !HasRowid(pTab);
107024
107025  /* Figure out if we have any triggers and if the table being
107026  ** inserted into is a view
107027  */
107028#ifndef SQLITE_OMIT_TRIGGER
107029  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
107030  isView = pTab->pSelect!=0;
107031#else
107032# define pTrigger 0
107033# define tmask 0
107034# define isView 0
107035#endif
107036#ifdef SQLITE_OMIT_VIEW
107037# undef isView
107038# define isView 0
107039#endif
107040  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
107041
107042  /* If pTab is really a view, make sure it has been initialized.
107043  ** ViewGetColumnNames() is a no-op if pTab is not a view.
107044  */
107045  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107046    goto insert_cleanup;
107047  }
107048
107049  /* Cannot insert into a read-only table.
107050  */
107051  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
107052    goto insert_cleanup;
107053  }
107054
107055  /* Allocate a VDBE
107056  */
107057  v = sqlite3GetVdbe(pParse);
107058  if( v==0 ) goto insert_cleanup;
107059  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
107060  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
107061
107062#ifndef SQLITE_OMIT_XFER_OPT
107063  /* If the statement is of the form
107064  **
107065  **       INSERT INTO <table1> SELECT * FROM <table2>;
107066  **
107067  ** Then special optimizations can be applied that make the transfer
107068  ** very fast and which reduce fragmentation of indices.
107069  **
107070  ** This is the 2nd template.
107071  */
107072  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
107073    assert( !pTrigger );
107074    assert( pList==0 );
107075    goto insert_end;
107076  }
107077#endif /* SQLITE_OMIT_XFER_OPT */
107078
107079  /* If this is an AUTOINCREMENT table, look up the sequence number in the
107080  ** sqlite_sequence table and store it in memory cell regAutoinc.
107081  */
107082  regAutoinc = autoIncBegin(pParse, iDb, pTab);
107083
107084  /* Allocate registers for holding the rowid of the new row,
107085  ** the content of the new row, and the assembled row record.
107086  */
107087  regRowid = regIns = pParse->nMem+1;
107088  pParse->nMem += pTab->nCol + 1;
107089  if( IsVirtual(pTab) ){
107090    regRowid++;
107091    pParse->nMem++;
107092  }
107093  regData = regRowid+1;
107094
107095  /* If the INSERT statement included an IDLIST term, then make sure
107096  ** all elements of the IDLIST really are columns of the table and
107097  ** remember the column indices.
107098  **
107099  ** If the table has an INTEGER PRIMARY KEY column and that column
107100  ** is named in the IDLIST, then record in the ipkColumn variable
107101  ** the index into IDLIST of the primary key column.  ipkColumn is
107102  ** the index of the primary key as it appears in IDLIST, not as
107103  ** is appears in the original table.  (The index of the INTEGER
107104  ** PRIMARY KEY in the original table is pTab->iPKey.)
107105  */
107106  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
107107  if( pColumn ){
107108    for(i=0; i<pColumn->nId; i++){
107109      pColumn->a[i].idx = -1;
107110    }
107111    for(i=0; i<pColumn->nId; i++){
107112      for(j=0; j<pTab->nCol; j++){
107113        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
107114          pColumn->a[i].idx = j;
107115          if( i!=j ) bIdListInOrder = 0;
107116          if( j==pTab->iPKey ){
107117            ipkColumn = i;  assert( !withoutRowid );
107118          }
107119          break;
107120        }
107121      }
107122      if( j>=pTab->nCol ){
107123        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
107124          ipkColumn = i;
107125          bIdListInOrder = 0;
107126        }else{
107127          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
107128              pTabList, 0, pColumn->a[i].zName);
107129          pParse->checkSchema = 1;
107130          goto insert_cleanup;
107131        }
107132      }
107133    }
107134  }
107135
107136  /* Figure out how many columns of data are supplied.  If the data
107137  ** is coming from a SELECT statement, then generate a co-routine that
107138  ** produces a single row of the SELECT on each invocation.  The
107139  ** co-routine is the common header to the 3rd and 4th templates.
107140  */
107141  if( pSelect ){
107142    /* Data is coming from a SELECT or from a multi-row VALUES clause.
107143    ** Generate a co-routine to run the SELECT. */
107144    int regYield;       /* Register holding co-routine entry-point */
107145    int addrTop;        /* Top of the co-routine */
107146    int rc;             /* Result code */
107147
107148    regYield = ++pParse->nMem;
107149    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
107150    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
107151    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
107152    dest.iSdst = bIdListInOrder ? regData : 0;
107153    dest.nSdst = pTab->nCol;
107154    rc = sqlite3Select(pParse, pSelect, &dest);
107155    regFromSelect = dest.iSdst;
107156    if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
107157    sqlite3VdbeEndCoroutine(v, regYield);
107158    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
107159    assert( pSelect->pEList );
107160    nColumn = pSelect->pEList->nExpr;
107161
107162    /* Set useTempTable to TRUE if the result of the SELECT statement
107163    ** should be written into a temporary table (template 4).  Set to
107164    ** FALSE if each output row of the SELECT can be written directly into
107165    ** the destination table (template 3).
107166    **
107167    ** A temp table must be used if the table being updated is also one
107168    ** of the tables being read by the SELECT statement.  Also use a
107169    ** temp table in the case of row triggers.
107170    */
107171    if( pTrigger || readsTable(pParse, iDb, pTab) ){
107172      useTempTable = 1;
107173    }
107174
107175    if( useTempTable ){
107176      /* Invoke the coroutine to extract information from the SELECT
107177      ** and add it to a transient table srcTab.  The code generated
107178      ** here is from the 4th template:
107179      **
107180      **      B: open temp table
107181      **      L: yield X, goto M at EOF
107182      **         insert row from R..R+n into temp table
107183      **         goto L
107184      **      M: ...
107185      */
107186      int regRec;          /* Register to hold packed record */
107187      int regTempRowid;    /* Register to hold temp table ROWID */
107188      int addrL;           /* Label "L" */
107189
107190      srcTab = pParse->nTab++;
107191      regRec = sqlite3GetTempReg(pParse);
107192      regTempRowid = sqlite3GetTempReg(pParse);
107193      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
107194      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
107195      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
107196      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
107197      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
107198      sqlite3VdbeGoto(v, addrL);
107199      sqlite3VdbeJumpHere(v, addrL);
107200      sqlite3ReleaseTempReg(pParse, regRec);
107201      sqlite3ReleaseTempReg(pParse, regTempRowid);
107202    }
107203  }else{
107204    /* This is the case if the data for the INSERT is coming from a
107205    ** single-row VALUES clause
107206    */
107207    NameContext sNC;
107208    memset(&sNC, 0, sizeof(sNC));
107209    sNC.pParse = pParse;
107210    srcTab = -1;
107211    assert( useTempTable==0 );
107212    if( pList ){
107213      nColumn = pList->nExpr;
107214      if( sqlite3ResolveExprListNames(&sNC, pList) ){
107215        goto insert_cleanup;
107216      }
107217    }else{
107218      nColumn = 0;
107219    }
107220  }
107221
107222  /* If there is no IDLIST term but the table has an integer primary
107223  ** key, the set the ipkColumn variable to the integer primary key
107224  ** column index in the original table definition.
107225  */
107226  if( pColumn==0 && nColumn>0 ){
107227    ipkColumn = pTab->iPKey;
107228  }
107229
107230  /* Make sure the number of columns in the source data matches the number
107231  ** of columns to be inserted into the table.
107232  */
107233  for(i=0; i<pTab->nCol; i++){
107234    nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
107235  }
107236  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
107237    sqlite3ErrorMsg(pParse,
107238       "table %S has %d columns but %d values were supplied",
107239       pTabList, 0, pTab->nCol-nHidden, nColumn);
107240    goto insert_cleanup;
107241  }
107242  if( pColumn!=0 && nColumn!=pColumn->nId ){
107243    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
107244    goto insert_cleanup;
107245  }
107246
107247  /* Initialize the count of rows to be inserted
107248  */
107249  if( db->flags & SQLITE_CountRows ){
107250    regRowCount = ++pParse->nMem;
107251    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
107252  }
107253
107254  /* If this is not a view, open the table and and all indices */
107255  if( !isView ){
107256    int nIdx;
107257    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
107258                                      &iDataCur, &iIdxCur);
107259    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
107260    if( aRegIdx==0 ){
107261      goto insert_cleanup;
107262    }
107263    for(i=0; i<nIdx; i++){
107264      aRegIdx[i] = ++pParse->nMem;
107265    }
107266  }
107267
107268  /* This is the top of the main insertion loop */
107269  if( useTempTable ){
107270    /* This block codes the top of loop only.  The complete loop is the
107271    ** following pseudocode (template 4):
107272    **
107273    **         rewind temp table, if empty goto D
107274    **      C: loop over rows of intermediate table
107275    **           transfer values form intermediate table into <table>
107276    **         end loop
107277    **      D: ...
107278    */
107279    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
107280    addrCont = sqlite3VdbeCurrentAddr(v);
107281  }else if( pSelect ){
107282    /* This block codes the top of loop only.  The complete loop is the
107283    ** following pseudocode (template 3):
107284    **
107285    **      C: yield X, at EOF goto D
107286    **         insert the select result into <table> from R..R+n
107287    **         goto C
107288    **      D: ...
107289    */
107290    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
107291    VdbeCoverage(v);
107292  }
107293
107294  /* Run the BEFORE and INSTEAD OF triggers, if there are any
107295  */
107296  endOfLoop = sqlite3VdbeMakeLabel(v);
107297  if( tmask & TRIGGER_BEFORE ){
107298    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
107299
107300    /* build the NEW.* reference row.  Note that if there is an INTEGER
107301    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
107302    ** translated into a unique ID for the row.  But on a BEFORE trigger,
107303    ** we do not know what the unique ID will be (because the insert has
107304    ** not happened yet) so we substitute a rowid of -1
107305    */
107306    if( ipkColumn<0 ){
107307      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
107308    }else{
107309      int addr1;
107310      assert( !withoutRowid );
107311      if( useTempTable ){
107312        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
107313      }else{
107314        assert( pSelect==0 );  /* Otherwise useTempTable is true */
107315        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
107316      }
107317      addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
107318      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
107319      sqlite3VdbeJumpHere(v, addr1);
107320      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
107321    }
107322
107323    /* Cannot have triggers on a virtual table. If it were possible,
107324    ** this block would have to account for hidden column.
107325    */
107326    assert( !IsVirtual(pTab) );
107327
107328    /* Create the new column data
107329    */
107330    for(i=j=0; i<pTab->nCol; i++){
107331      if( pColumn ){
107332        for(j=0; j<pColumn->nId; j++){
107333          if( pColumn->a[j].idx==i ) break;
107334        }
107335      }
107336      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
107337            || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
107338        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
107339      }else if( useTempTable ){
107340        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
107341      }else{
107342        assert( pSelect==0 ); /* Otherwise useTempTable is true */
107343        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
107344      }
107345      if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
107346    }
107347
107348    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
107349    ** do not attempt any conversions before assembling the record.
107350    ** If this is a real table, attempt conversions as required by the
107351    ** table column affinities.
107352    */
107353    if( !isView ){
107354      sqlite3TableAffinity(v, pTab, regCols+1);
107355    }
107356
107357    /* Fire BEFORE or INSTEAD OF triggers */
107358    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
107359        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
107360
107361    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
107362  }
107363
107364  /* Compute the content of the next row to insert into a range of
107365  ** registers beginning at regIns.
107366  */
107367  if( !isView ){
107368    if( IsVirtual(pTab) ){
107369      /* The row that the VUpdate opcode will delete: none */
107370      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
107371    }
107372    if( ipkColumn>=0 ){
107373      if( useTempTable ){
107374        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
107375      }else if( pSelect ){
107376        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
107377      }else{
107378        VdbeOp *pOp;
107379        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
107380        pOp = sqlite3VdbeGetOp(v, -1);
107381        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
107382          appendFlag = 1;
107383          pOp->opcode = OP_NewRowid;
107384          pOp->p1 = iDataCur;
107385          pOp->p2 = regRowid;
107386          pOp->p3 = regAutoinc;
107387        }
107388      }
107389      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
107390      ** to generate a unique primary key value.
107391      */
107392      if( !appendFlag ){
107393        int addr1;
107394        if( !IsVirtual(pTab) ){
107395          addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
107396          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
107397          sqlite3VdbeJumpHere(v, addr1);
107398        }else{
107399          addr1 = sqlite3VdbeCurrentAddr(v);
107400          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
107401        }
107402        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
107403      }
107404    }else if( IsVirtual(pTab) || withoutRowid ){
107405      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
107406    }else{
107407      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
107408      appendFlag = 1;
107409    }
107410    autoIncStep(pParse, regAutoinc, regRowid);
107411
107412    /* Compute data for all columns of the new entry, beginning
107413    ** with the first column.
107414    */
107415    nHidden = 0;
107416    for(i=0; i<pTab->nCol; i++){
107417      int iRegStore = regRowid+1+i;
107418      if( i==pTab->iPKey ){
107419        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
107420        ** Whenever this column is read, the rowid will be substituted
107421        ** in its place.  Hence, fill this column with a NULL to avoid
107422        ** taking up data space with information that will never be used.
107423        ** As there may be shallow copies of this value, make it a soft-NULL */
107424        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
107425        continue;
107426      }
107427      if( pColumn==0 ){
107428        if( IsHiddenColumn(&pTab->aCol[i]) ){
107429          j = -1;
107430          nHidden++;
107431        }else{
107432          j = i - nHidden;
107433        }
107434      }else{
107435        for(j=0; j<pColumn->nId; j++){
107436          if( pColumn->a[j].idx==i ) break;
107437        }
107438      }
107439      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
107440        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
107441      }else if( useTempTable ){
107442        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
107443      }else if( pSelect ){
107444        if( regFromSelect!=regData ){
107445          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
107446        }
107447      }else{
107448        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
107449      }
107450    }
107451
107452    /* Generate code to check constraints and generate index keys and
107453    ** do the insertion.
107454    */
107455#ifndef SQLITE_OMIT_VIRTUALTABLE
107456    if( IsVirtual(pTab) ){
107457      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
107458      sqlite3VtabMakeWritable(pParse, pTab);
107459      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
107460      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
107461      sqlite3MayAbort(pParse);
107462    }else
107463#endif
107464    {
107465      int isReplace;    /* Set to true if constraints may cause a replace */
107466      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
107467          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
107468      );
107469      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
107470      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
107471                               regIns, aRegIdx, 0, appendFlag, isReplace==0);
107472    }
107473  }
107474
107475  /* Update the count of rows that are inserted
107476  */
107477  if( (db->flags & SQLITE_CountRows)!=0 ){
107478    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
107479  }
107480
107481  if( pTrigger ){
107482    /* Code AFTER triggers */
107483    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
107484        pTab, regData-2-pTab->nCol, onError, endOfLoop);
107485  }
107486
107487  /* The bottom of the main insertion loop, if the data source
107488  ** is a SELECT statement.
107489  */
107490  sqlite3VdbeResolveLabel(v, endOfLoop);
107491  if( useTempTable ){
107492    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
107493    sqlite3VdbeJumpHere(v, addrInsTop);
107494    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
107495  }else if( pSelect ){
107496    sqlite3VdbeGoto(v, addrCont);
107497    sqlite3VdbeJumpHere(v, addrInsTop);
107498  }
107499
107500  if( !IsVirtual(pTab) && !isView ){
107501    /* Close all tables opened */
107502    if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
107503    for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
107504      sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
107505    }
107506  }
107507
107508insert_end:
107509  /* Update the sqlite_sequence table by storing the content of the
107510  ** maximum rowid counter values recorded while inserting into
107511  ** autoincrement tables.
107512  */
107513  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
107514    sqlite3AutoincrementEnd(pParse);
107515  }
107516
107517  /*
107518  ** Return the number of rows inserted. If this routine is
107519  ** generating code because of a call to sqlite3NestedParse(), do not
107520  ** invoke the callback function.
107521  */
107522  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
107523    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
107524    sqlite3VdbeSetNumCols(v, 1);
107525    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
107526  }
107527
107528insert_cleanup:
107529  sqlite3SrcListDelete(db, pTabList);
107530  sqlite3ExprListDelete(db, pList);
107531  sqlite3SelectDelete(db, pSelect);
107532  sqlite3IdListDelete(db, pColumn);
107533  sqlite3DbFree(db, aRegIdx);
107534}
107535
107536/* Make sure "isView" and other macros defined above are undefined. Otherwise
107537** they may interfere with compilation of other functions in this file
107538** (or in another file, if this file becomes part of the amalgamation).  */
107539#ifdef isView
107540 #undef isView
107541#endif
107542#ifdef pTrigger
107543 #undef pTrigger
107544#endif
107545#ifdef tmask
107546 #undef tmask
107547#endif
107548
107549/*
107550** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
107551*/
107552#define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
107553#define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
107554
107555/* This is the Walker callback from checkConstraintUnchanged().  Set
107556** bit 0x01 of pWalker->eCode if
107557** pWalker->eCode to 0 if this expression node references any of the
107558** columns that are being modifed by an UPDATE statement.
107559*/
107560static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
107561  if( pExpr->op==TK_COLUMN ){
107562    assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
107563    if( pExpr->iColumn>=0 ){
107564      if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
107565        pWalker->eCode |= CKCNSTRNT_COLUMN;
107566      }
107567    }else{
107568      pWalker->eCode |= CKCNSTRNT_ROWID;
107569    }
107570  }
107571  return WRC_Continue;
107572}
107573
107574/*
107575** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
107576** only columns that are modified by the UPDATE are those for which
107577** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
107578**
107579** Return true if CHECK constraint pExpr does not use any of the
107580** changing columns (or the rowid if it is changing).  In other words,
107581** return true if this CHECK constraint can be skipped when validating
107582** the new row in the UPDATE statement.
107583*/
107584static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
107585  Walker w;
107586  memset(&w, 0, sizeof(w));
107587  w.eCode = 0;
107588  w.xExprCallback = checkConstraintExprNode;
107589  w.u.aiCol = aiChng;
107590  sqlite3WalkExpr(&w, pExpr);
107591  if( !chngRowid ){
107592    testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
107593    w.eCode &= ~CKCNSTRNT_ROWID;
107594  }
107595  testcase( w.eCode==0 );
107596  testcase( w.eCode==CKCNSTRNT_COLUMN );
107597  testcase( w.eCode==CKCNSTRNT_ROWID );
107598  testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
107599  return !w.eCode;
107600}
107601
107602/*
107603** Generate code to do constraint checks prior to an INSERT or an UPDATE
107604** on table pTab.
107605**
107606** The regNewData parameter is the first register in a range that contains
107607** the data to be inserted or the data after the update.  There will be
107608** pTab->nCol+1 registers in this range.  The first register (the one
107609** that regNewData points to) will contain the new rowid, or NULL in the
107610** case of a WITHOUT ROWID table.  The second register in the range will
107611** contain the content of the first table column.  The third register will
107612** contain the content of the second table column.  And so forth.
107613**
107614** The regOldData parameter is similar to regNewData except that it contains
107615** the data prior to an UPDATE rather than afterwards.  regOldData is zero
107616** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
107617** checking regOldData for zero.
107618**
107619** For an UPDATE, the pkChng boolean is true if the true primary key (the
107620** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
107621** might be modified by the UPDATE.  If pkChng is false, then the key of
107622** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
107623**
107624** For an INSERT, the pkChng boolean indicates whether or not the rowid
107625** was explicitly specified as part of the INSERT statement.  If pkChng
107626** is zero, it means that the either rowid is computed automatically or
107627** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
107628** pkChng will only be true if the INSERT statement provides an integer
107629** value for either the rowid column or its INTEGER PRIMARY KEY alias.
107630**
107631** The code generated by this routine will store new index entries into
107632** registers identified by aRegIdx[].  No index entry is created for
107633** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
107634** the same as the order of indices on the linked list of indices
107635** at pTab->pIndex.
107636**
107637** The caller must have already opened writeable cursors on the main
107638** table and all applicable indices (that is to say, all indices for which
107639** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
107640** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
107641** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
107642** for the first index in the pTab->pIndex list.  Cursors for other indices
107643** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
107644**
107645** This routine also generates code to check constraints.  NOT NULL,
107646** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
107647** then the appropriate action is performed.  There are five possible
107648** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
107649**
107650**  Constraint type  Action       What Happens
107651**  ---------------  ----------   ----------------------------------------
107652**  any              ROLLBACK     The current transaction is rolled back and
107653**                                sqlite3_step() returns immediately with a
107654**                                return code of SQLITE_CONSTRAINT.
107655**
107656**  any              ABORT        Back out changes from the current command
107657**                                only (do not do a complete rollback) then
107658**                                cause sqlite3_step() to return immediately
107659**                                with SQLITE_CONSTRAINT.
107660**
107661**  any              FAIL         Sqlite3_step() returns immediately with a
107662**                                return code of SQLITE_CONSTRAINT.  The
107663**                                transaction is not rolled back and any
107664**                                changes to prior rows are retained.
107665**
107666**  any              IGNORE       The attempt in insert or update the current
107667**                                row is skipped, without throwing an error.
107668**                                Processing continues with the next row.
107669**                                (There is an immediate jump to ignoreDest.)
107670**
107671**  NOT NULL         REPLACE      The NULL value is replace by the default
107672**                                value for that column.  If the default value
107673**                                is NULL, the action is the same as ABORT.
107674**
107675**  UNIQUE           REPLACE      The other row that conflicts with the row
107676**                                being inserted is removed.
107677**
107678**  CHECK            REPLACE      Illegal.  The results in an exception.
107679**
107680** Which action to take is determined by the overrideError parameter.
107681** Or if overrideError==OE_Default, then the pParse->onError parameter
107682** is used.  Or if pParse->onError==OE_Default then the onError value
107683** for the constraint is used.
107684*/
107685SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
107686  Parse *pParse,       /* The parser context */
107687  Table *pTab,         /* The table being inserted or updated */
107688  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
107689  int iDataCur,        /* Canonical data cursor (main table or PK index) */
107690  int iIdxCur,         /* First index cursor */
107691  int regNewData,      /* First register in a range holding values to insert */
107692  int regOldData,      /* Previous content.  0 for INSERTs */
107693  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
107694  u8 overrideError,    /* Override onError to this if not OE_Default */
107695  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
107696  int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
107697  int *aiChng          /* column i is unchanged if aiChng[i]<0 */
107698){
107699  Vdbe *v;             /* VDBE under constrution */
107700  Index *pIdx;         /* Pointer to one of the indices */
107701  Index *pPk = 0;      /* The PRIMARY KEY index */
107702  sqlite3 *db;         /* Database connection */
107703  int i;               /* loop counter */
107704  int ix;              /* Index loop counter */
107705  int nCol;            /* Number of columns */
107706  int onError;         /* Conflict resolution strategy */
107707  int addr1;           /* Address of jump instruction */
107708  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
107709  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
107710  int ipkTop = 0;      /* Top of the rowid change constraint check */
107711  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
107712  u8 isUpdate;         /* True if this is an UPDATE operation */
107713  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
107714  int regRowid = -1;   /* Register holding ROWID value */
107715
107716  isUpdate = regOldData!=0;
107717  db = pParse->db;
107718  v = sqlite3GetVdbe(pParse);
107719  assert( v!=0 );
107720  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
107721  nCol = pTab->nCol;
107722
107723  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
107724  ** normal rowid tables.  nPkField is the number of key fields in the
107725  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
107726  ** number of fields in the true primary key of the table. */
107727  if( HasRowid(pTab) ){
107728    pPk = 0;
107729    nPkField = 1;
107730  }else{
107731    pPk = sqlite3PrimaryKeyIndex(pTab);
107732    nPkField = pPk->nKeyCol;
107733  }
107734
107735  /* Record that this module has started */
107736  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
107737                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
107738
107739  /* Test all NOT NULL constraints.
107740  */
107741  for(i=0; i<nCol; i++){
107742    if( i==pTab->iPKey ){
107743      continue;        /* ROWID is never NULL */
107744    }
107745    if( aiChng && aiChng[i]<0 ){
107746      /* Don't bother checking for NOT NULL on columns that do not change */
107747      continue;
107748    }
107749    onError = pTab->aCol[i].notNull;
107750    if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
107751    if( overrideError!=OE_Default ){
107752      onError = overrideError;
107753    }else if( onError==OE_Default ){
107754      onError = OE_Abort;
107755    }
107756    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
107757      onError = OE_Abort;
107758    }
107759    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
107760        || onError==OE_Ignore || onError==OE_Replace );
107761    switch( onError ){
107762      case OE_Abort:
107763        sqlite3MayAbort(pParse);
107764        /* Fall through */
107765      case OE_Rollback:
107766      case OE_Fail: {
107767        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
107768                                    pTab->aCol[i].zName);
107769        sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
107770                          regNewData+1+i, zMsg, P4_DYNAMIC);
107771        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
107772        VdbeCoverage(v);
107773        break;
107774      }
107775      case OE_Ignore: {
107776        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
107777        VdbeCoverage(v);
107778        break;
107779      }
107780      default: {
107781        assert( onError==OE_Replace );
107782        addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
107783           VdbeCoverage(v);
107784        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
107785        sqlite3VdbeJumpHere(v, addr1);
107786        break;
107787      }
107788    }
107789  }
107790
107791  /* Test all CHECK constraints
107792  */
107793#ifndef SQLITE_OMIT_CHECK
107794  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
107795    ExprList *pCheck = pTab->pCheck;
107796    pParse->ckBase = regNewData+1;
107797    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
107798    for(i=0; i<pCheck->nExpr; i++){
107799      int allOk;
107800      Expr *pExpr = pCheck->a[i].pExpr;
107801      if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
107802      allOk = sqlite3VdbeMakeLabel(v);
107803      sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
107804      if( onError==OE_Ignore ){
107805        sqlite3VdbeGoto(v, ignoreDest);
107806      }else{
107807        char *zName = pCheck->a[i].zName;
107808        if( zName==0 ) zName = pTab->zName;
107809        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
107810        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
107811                              onError, zName, P4_TRANSIENT,
107812                              P5_ConstraintCheck);
107813      }
107814      sqlite3VdbeResolveLabel(v, allOk);
107815    }
107816  }
107817#endif /* !defined(SQLITE_OMIT_CHECK) */
107818
107819  /* If rowid is changing, make sure the new rowid does not previously
107820  ** exist in the table.
107821  */
107822  if( pkChng && pPk==0 ){
107823    int addrRowidOk = sqlite3VdbeMakeLabel(v);
107824
107825    /* Figure out what action to take in case of a rowid collision */
107826    onError = pTab->keyConf;
107827    if( overrideError!=OE_Default ){
107828      onError = overrideError;
107829    }else if( onError==OE_Default ){
107830      onError = OE_Abort;
107831    }
107832
107833    if( isUpdate ){
107834      /* pkChng!=0 does not mean that the rowid has change, only that
107835      ** it might have changed.  Skip the conflict logic below if the rowid
107836      ** is unchanged. */
107837      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
107838      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
107839      VdbeCoverage(v);
107840    }
107841
107842    /* If the response to a rowid conflict is REPLACE but the response
107843    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
107844    ** to defer the running of the rowid conflict checking until after
107845    ** the UNIQUE constraints have run.
107846    */
107847    if( onError==OE_Replace && overrideError!=OE_Replace ){
107848      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107849        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
107850          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
107851          break;
107852        }
107853      }
107854    }
107855
107856    /* Check to see if the new rowid already exists in the table.  Skip
107857    ** the following conflict logic if it does not. */
107858    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
107859    VdbeCoverage(v);
107860
107861    /* Generate code that deals with a rowid collision */
107862    switch( onError ){
107863      default: {
107864        onError = OE_Abort;
107865        /* Fall thru into the next case */
107866      }
107867      case OE_Rollback:
107868      case OE_Abort:
107869      case OE_Fail: {
107870        sqlite3RowidConstraint(pParse, onError, pTab);
107871        break;
107872      }
107873      case OE_Replace: {
107874        /* If there are DELETE triggers on this table and the
107875        ** recursive-triggers flag is set, call GenerateRowDelete() to
107876        ** remove the conflicting row from the table. This will fire
107877        ** the triggers and remove both the table and index b-tree entries.
107878        **
107879        ** Otherwise, if there are no triggers or the recursive-triggers
107880        ** flag is not set, but the table has one or more indexes, call
107881        ** GenerateRowIndexDelete(). This removes the index b-tree entries
107882        ** only. The table b-tree entry will be replaced by the new entry
107883        ** when it is inserted.
107884        **
107885        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
107886        ** also invoke MultiWrite() to indicate that this VDBE may require
107887        ** statement rollback (if the statement is aborted after the delete
107888        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
107889        ** but being more selective here allows statements like:
107890        **
107891        **   REPLACE INTO t(rowid) VALUES($newrowid)
107892        **
107893        ** to run without a statement journal if there are no indexes on the
107894        ** table.
107895        */
107896        Trigger *pTrigger = 0;
107897        if( db->flags&SQLITE_RecTriggers ){
107898          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
107899        }
107900        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
107901          sqlite3MultiWrite(pParse);
107902          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
107903                                   regNewData, 1, 0, OE_Replace, 1, -1);
107904        }else{
107905#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
107906          if( HasRowid(pTab) ){
107907            /* This OP_Delete opcode fires the pre-update-hook only. It does
107908            ** not modify the b-tree. It is more efficient to let the coming
107909            ** OP_Insert replace the existing entry than it is to delete the
107910            ** existing entry and then insert a new one. */
107911            sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
107912            sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107913          }
107914#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
107915          if( pTab->pIndex ){
107916            sqlite3MultiWrite(pParse);
107917            sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
107918          }
107919        }
107920        seenReplace = 1;
107921        break;
107922      }
107923      case OE_Ignore: {
107924        /*assert( seenReplace==0 );*/
107925        sqlite3VdbeGoto(v, ignoreDest);
107926        break;
107927      }
107928    }
107929    sqlite3VdbeResolveLabel(v, addrRowidOk);
107930    if( ipkTop ){
107931      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
107932      sqlite3VdbeJumpHere(v, ipkTop);
107933    }
107934  }
107935
107936  /* Test all UNIQUE constraints by creating entries for each UNIQUE
107937  ** index and making sure that duplicate entries do not already exist.
107938  ** Compute the revised record entries for indices as we go.
107939  **
107940  ** This loop also handles the case of the PRIMARY KEY index for a
107941  ** WITHOUT ROWID table.
107942  */
107943  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
107944    int regIdx;          /* Range of registers hold conent for pIdx */
107945    int regR;            /* Range of registers holding conflicting PK */
107946    int iThisCur;        /* Cursor for this UNIQUE index */
107947    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
107948
107949    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
107950    if( bAffinityDone==0 ){
107951      sqlite3TableAffinity(v, pTab, regNewData+1);
107952      bAffinityDone = 1;
107953    }
107954    iThisCur = iIdxCur+ix;
107955    addrUniqueOk = sqlite3VdbeMakeLabel(v);
107956
107957    /* Skip partial indices for which the WHERE clause is not true */
107958    if( pIdx->pPartIdxWhere ){
107959      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
107960      pParse->ckBase = regNewData+1;
107961      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
107962                            SQLITE_JUMPIFNULL);
107963      pParse->ckBase = 0;
107964    }
107965
107966    /* Create a record for this index entry as it should appear after
107967    ** the insert or update.  Store that record in the aRegIdx[ix] register
107968    */
107969    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
107970    for(i=0; i<pIdx->nColumn; i++){
107971      int iField = pIdx->aiColumn[i];
107972      int x;
107973      if( iField==XN_EXPR ){
107974        pParse->ckBase = regNewData+1;
107975        sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
107976        pParse->ckBase = 0;
107977        VdbeComment((v, "%s column %d", pIdx->zName, i));
107978      }else{
107979        if( iField==XN_ROWID || iField==pTab->iPKey ){
107980          if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
107981          x = regNewData;
107982          regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
107983        }else{
107984          x = iField + regNewData + 1;
107985        }
107986        sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
107987        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
107988      }
107989    }
107990    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
107991    VdbeComment((v, "for %s", pIdx->zName));
107992    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
107993
107994    /* In an UPDATE operation, if this index is the PRIMARY KEY index
107995    ** of a WITHOUT ROWID table and there has been no change the
107996    ** primary key, then no collision is possible.  The collision detection
107997    ** logic below can all be skipped. */
107998    if( isUpdate && pPk==pIdx && pkChng==0 ){
107999      sqlite3VdbeResolveLabel(v, addrUniqueOk);
108000      continue;
108001    }
108002
108003    /* Find out what action to take in case there is a uniqueness conflict */
108004    onError = pIdx->onError;
108005    if( onError==OE_None ){
108006      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108007      sqlite3VdbeResolveLabel(v, addrUniqueOk);
108008      continue;  /* pIdx is not a UNIQUE index */
108009    }
108010    if( overrideError!=OE_Default ){
108011      onError = overrideError;
108012    }else if( onError==OE_Default ){
108013      onError = OE_Abort;
108014    }
108015
108016    /* Check to see if the new index entry will be unique */
108017    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
108018                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
108019
108020    /* Generate code to handle collisions */
108021    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
108022    if( isUpdate || onError==OE_Replace ){
108023      if( HasRowid(pTab) ){
108024        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
108025        /* Conflict only if the rowid of the existing index entry
108026        ** is different from old-rowid */
108027        if( isUpdate ){
108028          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
108029          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108030          VdbeCoverage(v);
108031        }
108032      }else{
108033        int x;
108034        /* Extract the PRIMARY KEY from the end of the index entry and
108035        ** store it in registers regR..regR+nPk-1 */
108036        if( pIdx!=pPk ){
108037          for(i=0; i<pPk->nKeyCol; i++){
108038            assert( pPk->aiColumn[i]>=0 );
108039            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
108040            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
108041            VdbeComment((v, "%s.%s", pTab->zName,
108042                         pTab->aCol[pPk->aiColumn[i]].zName));
108043          }
108044        }
108045        if( isUpdate ){
108046          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
108047          ** table, only conflict if the new PRIMARY KEY values are actually
108048          ** different from the old.
108049          **
108050          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
108051          ** of the matched index row are different from the original PRIMARY
108052          ** KEY values of this row before the update.  */
108053          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
108054          int op = OP_Ne;
108055          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
108056
108057          for(i=0; i<pPk->nKeyCol; i++){
108058            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
108059            x = pPk->aiColumn[i];
108060            assert( x>=0 );
108061            if( i==(pPk->nKeyCol-1) ){
108062              addrJump = addrUniqueOk;
108063              op = OP_Eq;
108064            }
108065            sqlite3VdbeAddOp4(v, op,
108066                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
108067            );
108068            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108069            VdbeCoverageIf(v, op==OP_Eq);
108070            VdbeCoverageIf(v, op==OP_Ne);
108071          }
108072        }
108073      }
108074    }
108075
108076    /* Generate code that executes if the new index entry is not unique */
108077    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108078        || onError==OE_Ignore || onError==OE_Replace );
108079    switch( onError ){
108080      case OE_Rollback:
108081      case OE_Abort:
108082      case OE_Fail: {
108083        sqlite3UniqueConstraint(pParse, onError, pIdx);
108084        break;
108085      }
108086      case OE_Ignore: {
108087        sqlite3VdbeGoto(v, ignoreDest);
108088        break;
108089      }
108090      default: {
108091        Trigger *pTrigger = 0;
108092        assert( onError==OE_Replace );
108093        sqlite3MultiWrite(pParse);
108094        if( db->flags&SQLITE_RecTriggers ){
108095          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
108096        }
108097        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
108098            regR, nPkField, 0, OE_Replace,
108099            (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
108100        seenReplace = 1;
108101        break;
108102      }
108103    }
108104    sqlite3VdbeResolveLabel(v, addrUniqueOk);
108105    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108106    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
108107  }
108108  if( ipkTop ){
108109    sqlite3VdbeGoto(v, ipkTop+1);
108110    sqlite3VdbeJumpHere(v, ipkBottom);
108111  }
108112
108113  *pbMayReplace = seenReplace;
108114  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
108115}
108116
108117/*
108118** This routine generates code to finish the INSERT or UPDATE operation
108119** that was started by a prior call to sqlite3GenerateConstraintChecks.
108120** A consecutive range of registers starting at regNewData contains the
108121** rowid and the content to be inserted.
108122**
108123** The arguments to this routine should be the same as the first six
108124** arguments to sqlite3GenerateConstraintChecks.
108125*/
108126SQLITE_PRIVATE void sqlite3CompleteInsertion(
108127  Parse *pParse,      /* The parser context */
108128  Table *pTab,        /* the table into which we are inserting */
108129  int iDataCur,       /* Cursor of the canonical data source */
108130  int iIdxCur,        /* First index cursor */
108131  int regNewData,     /* Range of content */
108132  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
108133  int isUpdate,       /* True for UPDATE, False for INSERT */
108134  int appendBias,     /* True if this is likely to be an append */
108135  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
108136){
108137  Vdbe *v;            /* Prepared statements under construction */
108138  Index *pIdx;        /* An index being inserted or updated */
108139  u8 pik_flags;       /* flag values passed to the btree insert */
108140  int regData;        /* Content registers (after the rowid) */
108141  int regRec;         /* Register holding assembled record for the table */
108142  int i;              /* Loop counter */
108143  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
108144
108145  v = sqlite3GetVdbe(pParse);
108146  assert( v!=0 );
108147  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
108148  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
108149    if( aRegIdx[i]==0 ) continue;
108150    bAffinityDone = 1;
108151    if( pIdx->pPartIdxWhere ){
108152      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
108153      VdbeCoverage(v);
108154    }
108155    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
108156    pik_flags = 0;
108157    if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
108158    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
108159      assert( pParse->nested==0 );
108160      pik_flags |= OPFLAG_NCHANGE;
108161    }
108162    sqlite3VdbeChangeP5(v, pik_flags);
108163  }
108164  if( !HasRowid(pTab) ) return;
108165  regData = regNewData + 1;
108166  regRec = sqlite3GetTempReg(pParse);
108167  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
108168  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
108169  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
108170  if( pParse->nested ){
108171    pik_flags = 0;
108172  }else{
108173    pik_flags = OPFLAG_NCHANGE;
108174    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
108175  }
108176  if( appendBias ){
108177    pik_flags |= OPFLAG_APPEND;
108178  }
108179  if( useSeekResult ){
108180    pik_flags |= OPFLAG_USESEEKRESULT;
108181  }
108182  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
108183  if( !pParse->nested ){
108184    sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
108185  }
108186  sqlite3VdbeChangeP5(v, pik_flags);
108187}
108188
108189/*
108190** Allocate cursors for the pTab table and all its indices and generate
108191** code to open and initialized those cursors.
108192**
108193** The cursor for the object that contains the complete data (normally
108194** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
108195** ROWID table) is returned in *piDataCur.  The first index cursor is
108196** returned in *piIdxCur.  The number of indices is returned.
108197**
108198** Use iBase as the first cursor (either the *piDataCur for rowid tables
108199** or the first index for WITHOUT ROWID tables) if it is non-negative.
108200** If iBase is negative, then allocate the next available cursor.
108201**
108202** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
108203** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
108204** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
108205** pTab->pIndex list.
108206**
108207** If pTab is a virtual table, then this routine is a no-op and the
108208** *piDataCur and *piIdxCur values are left uninitialized.
108209*/
108210SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
108211  Parse *pParse,   /* Parsing context */
108212  Table *pTab,     /* Table to be opened */
108213  int op,          /* OP_OpenRead or OP_OpenWrite */
108214  u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
108215  int iBase,       /* Use this for the table cursor, if there is one */
108216  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
108217  int *piDataCur,  /* Write the database source cursor number here */
108218  int *piIdxCur    /* Write the first index cursor number here */
108219){
108220  int i;
108221  int iDb;
108222  int iDataCur;
108223  Index *pIdx;
108224  Vdbe *v;
108225
108226  assert( op==OP_OpenRead || op==OP_OpenWrite );
108227  assert( op==OP_OpenWrite || p5==0 );
108228  if( IsVirtual(pTab) ){
108229    /* This routine is a no-op for virtual tables. Leave the output
108230    ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
108231    ** can detect if they are used by mistake in the caller. */
108232    return 0;
108233  }
108234  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
108235  v = sqlite3GetVdbe(pParse);
108236  assert( v!=0 );
108237  if( iBase<0 ) iBase = pParse->nTab;
108238  iDataCur = iBase++;
108239  if( piDataCur ) *piDataCur = iDataCur;
108240  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
108241    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
108242  }else{
108243    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
108244  }
108245  if( piIdxCur ) *piIdxCur = iBase;
108246  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
108247    int iIdxCur = iBase++;
108248    assert( pIdx->pSchema==pTab->pSchema );
108249    if( aToOpen==0 || aToOpen[i+1] ){
108250      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
108251      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
108252      VdbeComment((v, "%s", pIdx->zName));
108253    }
108254    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
108255      if( piDataCur ) *piDataCur = iIdxCur;
108256    }else{
108257      sqlite3VdbeChangeP5(v, p5);
108258    }
108259  }
108260  if( iBase>pParse->nTab ) pParse->nTab = iBase;
108261  return i;
108262}
108263
108264
108265#ifdef SQLITE_TEST
108266/*
108267** The following global variable is incremented whenever the
108268** transfer optimization is used.  This is used for testing
108269** purposes only - to make sure the transfer optimization really
108270** is happening when it is supposed to.
108271*/
108272SQLITE_API int sqlite3_xferopt_count;
108273#endif /* SQLITE_TEST */
108274
108275
108276#ifndef SQLITE_OMIT_XFER_OPT
108277/*
108278** Check to see if index pSrc is compatible as a source of data
108279** for index pDest in an insert transfer optimization.  The rules
108280** for a compatible index:
108281**
108282**    *   The index is over the same set of columns
108283**    *   The same DESC and ASC markings occurs on all columns
108284**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
108285**    *   The same collating sequence on each column
108286**    *   The index has the exact same WHERE clause
108287*/
108288static int xferCompatibleIndex(Index *pDest, Index *pSrc){
108289  int i;
108290  assert( pDest && pSrc );
108291  assert( pDest->pTable!=pSrc->pTable );
108292  if( pDest->nKeyCol!=pSrc->nKeyCol ){
108293    return 0;   /* Different number of columns */
108294  }
108295  if( pDest->onError!=pSrc->onError ){
108296    return 0;   /* Different conflict resolution strategies */
108297  }
108298  for(i=0; i<pSrc->nKeyCol; i++){
108299    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
108300      return 0;   /* Different columns indexed */
108301    }
108302    if( pSrc->aiColumn[i]==XN_EXPR ){
108303      assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
108304      if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
108305                             pDest->aColExpr->a[i].pExpr, -1)!=0 ){
108306        return 0;   /* Different expressions in the index */
108307      }
108308    }
108309    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
108310      return 0;   /* Different sort orders */
108311    }
108312    if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
108313      return 0;   /* Different collating sequences */
108314    }
108315  }
108316  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
108317    return 0;     /* Different WHERE clauses */
108318  }
108319
108320  /* If no test above fails then the indices must be compatible */
108321  return 1;
108322}
108323
108324/*
108325** Attempt the transfer optimization on INSERTs of the form
108326**
108327**     INSERT INTO tab1 SELECT * FROM tab2;
108328**
108329** The xfer optimization transfers raw records from tab2 over to tab1.
108330** Columns are not decoded and reassembled, which greatly improves
108331** performance.  Raw index records are transferred in the same way.
108332**
108333** The xfer optimization is only attempted if tab1 and tab2 are compatible.
108334** There are lots of rules for determining compatibility - see comments
108335** embedded in the code for details.
108336**
108337** This routine returns TRUE if the optimization is guaranteed to be used.
108338** Sometimes the xfer optimization will only work if the destination table
108339** is empty - a factor that can only be determined at run-time.  In that
108340** case, this routine generates code for the xfer optimization but also
108341** does a test to see if the destination table is empty and jumps over the
108342** xfer optimization code if the test fails.  In that case, this routine
108343** returns FALSE so that the caller will know to go ahead and generate
108344** an unoptimized transfer.  This routine also returns FALSE if there
108345** is no chance that the xfer optimization can be applied.
108346**
108347** This optimization is particularly useful at making VACUUM run faster.
108348*/
108349static int xferOptimization(
108350  Parse *pParse,        /* Parser context */
108351  Table *pDest,         /* The table we are inserting into */
108352  Select *pSelect,      /* A SELECT statement to use as the data source */
108353  int onError,          /* How to handle constraint errors */
108354  int iDbDest           /* The database of pDest */
108355){
108356  sqlite3 *db = pParse->db;
108357  ExprList *pEList;                /* The result set of the SELECT */
108358  Table *pSrc;                     /* The table in the FROM clause of SELECT */
108359  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
108360  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
108361  int i;                           /* Loop counter */
108362  int iDbSrc;                      /* The database of pSrc */
108363  int iSrc, iDest;                 /* Cursors from source and destination */
108364  int addr1, addr2;                /* Loop addresses */
108365  int emptyDestTest = 0;           /* Address of test for empty pDest */
108366  int emptySrcTest = 0;            /* Address of test for empty pSrc */
108367  Vdbe *v;                         /* The VDBE we are building */
108368  int regAutoinc;                  /* Memory register used by AUTOINC */
108369  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
108370  int regData, regRowid;           /* Registers holding data and rowid */
108371
108372  if( pSelect==0 ){
108373    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
108374  }
108375  if( pParse->pWith || pSelect->pWith ){
108376    /* Do not attempt to process this query if there are an WITH clauses
108377    ** attached to it. Proceeding may generate a false "no such table: xxx"
108378    ** error if pSelect reads from a CTE named "xxx".  */
108379    return 0;
108380  }
108381  if( sqlite3TriggerList(pParse, pDest) ){
108382    return 0;   /* tab1 must not have triggers */
108383  }
108384#ifndef SQLITE_OMIT_VIRTUALTABLE
108385  if( pDest->tabFlags & TF_Virtual ){
108386    return 0;   /* tab1 must not be a virtual table */
108387  }
108388#endif
108389  if( onError==OE_Default ){
108390    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
108391    if( onError==OE_Default ) onError = OE_Abort;
108392  }
108393  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
108394  if( pSelect->pSrc->nSrc!=1 ){
108395    return 0;   /* FROM clause must have exactly one term */
108396  }
108397  if( pSelect->pSrc->a[0].pSelect ){
108398    return 0;   /* FROM clause cannot contain a subquery */
108399  }
108400  if( pSelect->pWhere ){
108401    return 0;   /* SELECT may not have a WHERE clause */
108402  }
108403  if( pSelect->pOrderBy ){
108404    return 0;   /* SELECT may not have an ORDER BY clause */
108405  }
108406  /* Do not need to test for a HAVING clause.  If HAVING is present but
108407  ** there is no ORDER BY, we will get an error. */
108408  if( pSelect->pGroupBy ){
108409    return 0;   /* SELECT may not have a GROUP BY clause */
108410  }
108411  if( pSelect->pLimit ){
108412    return 0;   /* SELECT may not have a LIMIT clause */
108413  }
108414  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
108415  if( pSelect->pPrior ){
108416    return 0;   /* SELECT may not be a compound query */
108417  }
108418  if( pSelect->selFlags & SF_Distinct ){
108419    return 0;   /* SELECT may not be DISTINCT */
108420  }
108421  pEList = pSelect->pEList;
108422  assert( pEList!=0 );
108423  if( pEList->nExpr!=1 ){
108424    return 0;   /* The result set must have exactly one column */
108425  }
108426  assert( pEList->a[0].pExpr );
108427  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
108428    return 0;   /* The result set must be the special operator "*" */
108429  }
108430
108431  /* At this point we have established that the statement is of the
108432  ** correct syntactic form to participate in this optimization.  Now
108433  ** we have to check the semantics.
108434  */
108435  pItem = pSelect->pSrc->a;
108436  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
108437  if( pSrc==0 ){
108438    return 0;   /* FROM clause does not contain a real table */
108439  }
108440  if( pSrc==pDest ){
108441    return 0;   /* tab1 and tab2 may not be the same table */
108442  }
108443  if( HasRowid(pDest)!=HasRowid(pSrc) ){
108444    return 0;   /* source and destination must both be WITHOUT ROWID or not */
108445  }
108446#ifndef SQLITE_OMIT_VIRTUALTABLE
108447  if( pSrc->tabFlags & TF_Virtual ){
108448    return 0;   /* tab2 must not be a virtual table */
108449  }
108450#endif
108451  if( pSrc->pSelect ){
108452    return 0;   /* tab2 may not be a view */
108453  }
108454  if( pDest->nCol!=pSrc->nCol ){
108455    return 0;   /* Number of columns must be the same in tab1 and tab2 */
108456  }
108457  if( pDest->iPKey!=pSrc->iPKey ){
108458    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
108459  }
108460  for(i=0; i<pDest->nCol; i++){
108461    Column *pDestCol = &pDest->aCol[i];
108462    Column *pSrcCol = &pSrc->aCol[i];
108463#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
108464    if( (db->flags & SQLITE_Vacuum)==0
108465     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
108466    ){
108467      return 0;    /* Neither table may have __hidden__ columns */
108468    }
108469#endif
108470    if( pDestCol->affinity!=pSrcCol->affinity ){
108471      return 0;    /* Affinity must be the same on all columns */
108472    }
108473    if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
108474      return 0;    /* Collating sequence must be the same on all columns */
108475    }
108476    if( pDestCol->notNull && !pSrcCol->notNull ){
108477      return 0;    /* tab2 must be NOT NULL if tab1 is */
108478    }
108479    /* Default values for second and subsequent columns need to match. */
108480    if( i>0 ){
108481      assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
108482      assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
108483      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
108484       || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
108485                                       pSrcCol->pDflt->u.zToken)!=0)
108486      ){
108487        return 0;    /* Default values must be the same for all columns */
108488      }
108489    }
108490  }
108491  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
108492    if( IsUniqueIndex(pDestIdx) ){
108493      destHasUniqueIdx = 1;
108494    }
108495    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
108496      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
108497    }
108498    if( pSrcIdx==0 ){
108499      return 0;    /* pDestIdx has no corresponding index in pSrc */
108500    }
108501  }
108502#ifndef SQLITE_OMIT_CHECK
108503  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
108504    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
108505  }
108506#endif
108507#ifndef SQLITE_OMIT_FOREIGN_KEY
108508  /* Disallow the transfer optimization if the destination table constains
108509  ** any foreign key constraints.  This is more restrictive than necessary.
108510  ** But the main beneficiary of the transfer optimization is the VACUUM
108511  ** command, and the VACUUM command disables foreign key constraints.  So
108512  ** the extra complication to make this rule less restrictive is probably
108513  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
108514  */
108515  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
108516    return 0;
108517  }
108518#endif
108519  if( (db->flags & SQLITE_CountRows)!=0 ){
108520    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
108521  }
108522
108523  /* If we get this far, it means that the xfer optimization is at
108524  ** least a possibility, though it might only work if the destination
108525  ** table (tab1) is initially empty.
108526  */
108527#ifdef SQLITE_TEST
108528  sqlite3_xferopt_count++;
108529#endif
108530  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
108531  v = sqlite3GetVdbe(pParse);
108532  sqlite3CodeVerifySchema(pParse, iDbSrc);
108533  iSrc = pParse->nTab++;
108534  iDest = pParse->nTab++;
108535  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
108536  regData = sqlite3GetTempReg(pParse);
108537  regRowid = sqlite3GetTempReg(pParse);
108538  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
108539  assert( HasRowid(pDest) || destHasUniqueIdx );
108540  if( (db->flags & SQLITE_Vacuum)==0 && (
108541      (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
108542   || destHasUniqueIdx                              /* (2) */
108543   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
108544  )){
108545    /* In some circumstances, we are able to run the xfer optimization
108546    ** only if the destination table is initially empty. Unless the
108547    ** SQLITE_Vacuum flag is set, this block generates code to make
108548    ** that determination. If SQLITE_Vacuum is set, then the destination
108549    ** table is always empty.
108550    **
108551    ** Conditions under which the destination must be empty:
108552    **
108553    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
108554    **     (If the destination is not initially empty, the rowid fields
108555    **     of index entries might need to change.)
108556    **
108557    ** (2) The destination has a unique index.  (The xfer optimization
108558    **     is unable to test uniqueness.)
108559    **
108560    ** (3) onError is something other than OE_Abort and OE_Rollback.
108561    */
108562    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
108563    emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
108564    sqlite3VdbeJumpHere(v, addr1);
108565  }
108566  if( HasRowid(pSrc) ){
108567    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
108568    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
108569    if( pDest->iPKey>=0 ){
108570      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
108571      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
108572      VdbeCoverage(v);
108573      sqlite3RowidConstraint(pParse, onError, pDest);
108574      sqlite3VdbeJumpHere(v, addr2);
108575      autoIncStep(pParse, regAutoinc, regRowid);
108576    }else if( pDest->pIndex==0 ){
108577      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
108578    }else{
108579      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
108580      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
108581    }
108582    sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
108583    sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
108584                      (char*)pDest, P4_TABLE);
108585    sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
108586    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
108587    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
108588    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108589  }else{
108590    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
108591    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
108592  }
108593  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
108594    u8 idxInsFlags = 0;
108595    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
108596      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
108597    }
108598    assert( pSrcIdx );
108599    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
108600    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
108601    VdbeComment((v, "%s", pSrcIdx->zName));
108602    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
108603    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
108604    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
108605    VdbeComment((v, "%s", pDestIdx->zName));
108606    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
108607    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
108608    if( db->flags & SQLITE_Vacuum ){
108609      /* This INSERT command is part of a VACUUM operation, which guarantees
108610      ** that the destination table is empty. If all indexed columns use
108611      ** collation sequence BINARY, then it can also be assumed that the
108612      ** index will be populated by inserting keys in strictly sorted
108613      ** order. In this case, instead of seeking within the b-tree as part
108614      ** of every OP_IdxInsert opcode, an OP_Last is added before the
108615      ** OP_IdxInsert to seek to the point within the b-tree where each key
108616      ** should be inserted. This is faster.
108617      **
108618      ** If any of the indexed columns use a collation sequence other than
108619      ** BINARY, this optimization is disabled. This is because the user
108620      ** might change the definition of a collation sequence and then run
108621      ** a VACUUM command. In that case keys may not be written in strictly
108622      ** sorted order.  */
108623      for(i=0; i<pSrcIdx->nColumn; i++){
108624        const char *zColl = pSrcIdx->azColl[i];
108625        assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
108626                    || sqlite3StrBINARY==zColl );
108627        if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
108628      }
108629      if( i==pSrcIdx->nColumn ){
108630        idxInsFlags = OPFLAG_USESEEKRESULT;
108631        sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
108632      }
108633    }
108634    if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
108635      idxInsFlags |= OPFLAG_NCHANGE;
108636    }
108637    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
108638    sqlite3VdbeChangeP5(v, idxInsFlags);
108639    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
108640    sqlite3VdbeJumpHere(v, addr1);
108641    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
108642    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108643  }
108644  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
108645  sqlite3ReleaseTempReg(pParse, regRowid);
108646  sqlite3ReleaseTempReg(pParse, regData);
108647  if( emptyDestTest ){
108648    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
108649    sqlite3VdbeJumpHere(v, emptyDestTest);
108650    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108651    return 0;
108652  }else{
108653    return 1;
108654  }
108655}
108656#endif /* SQLITE_OMIT_XFER_OPT */
108657
108658/************** End of insert.c **********************************************/
108659/************** Begin file legacy.c ******************************************/
108660/*
108661** 2001 September 15
108662**
108663** The author disclaims copyright to this source code.  In place of
108664** a legal notice, here is a blessing:
108665**
108666**    May you do good and not evil.
108667**    May you find forgiveness for yourself and forgive others.
108668**    May you share freely, never taking more than you give.
108669**
108670*************************************************************************
108671** Main file for the SQLite library.  The routines in this file
108672** implement the programmer interface to the library.  Routines in
108673** other files are for internal use by SQLite and should not be
108674** accessed by users of the library.
108675*/
108676
108677/* #include "sqliteInt.h" */
108678
108679/*
108680** Execute SQL code.  Return one of the SQLITE_ success/failure
108681** codes.  Also write an error message into memory obtained from
108682** malloc() and make *pzErrMsg point to that message.
108683**
108684** If the SQL is a query, then for each row in the query result
108685** the xCallback() function is called.  pArg becomes the first
108686** argument to xCallback().  If xCallback=NULL then no callback
108687** is invoked, even for queries.
108688*/
108689SQLITE_API int SQLITE_STDCALL sqlite3_exec(
108690  sqlite3 *db,                /* The database on which the SQL executes */
108691  const char *zSql,           /* The SQL to be executed */
108692  sqlite3_callback xCallback, /* Invoke this callback routine */
108693  void *pArg,                 /* First argument to xCallback() */
108694  char **pzErrMsg             /* Write error messages here */
108695){
108696  int rc = SQLITE_OK;         /* Return code */
108697  const char *zLeftover;      /* Tail of unprocessed SQL */
108698  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
108699  char **azCols = 0;          /* Names of result columns */
108700  int callbackIsInit;         /* True if callback data is initialized */
108701
108702  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
108703  if( zSql==0 ) zSql = "";
108704
108705  sqlite3_mutex_enter(db->mutex);
108706  sqlite3Error(db, SQLITE_OK);
108707  while( rc==SQLITE_OK && zSql[0] ){
108708    int nCol;
108709    char **azVals = 0;
108710
108711    pStmt = 0;
108712    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
108713    assert( rc==SQLITE_OK || pStmt==0 );
108714    if( rc!=SQLITE_OK ){
108715      continue;
108716    }
108717    if( !pStmt ){
108718      /* this happens for a comment or white-space */
108719      zSql = zLeftover;
108720      continue;
108721    }
108722
108723    callbackIsInit = 0;
108724    nCol = sqlite3_column_count(pStmt);
108725
108726    while( 1 ){
108727      int i;
108728      rc = sqlite3_step(pStmt);
108729
108730      /* Invoke the callback function if required */
108731      if( xCallback && (SQLITE_ROW==rc ||
108732          (SQLITE_DONE==rc && !callbackIsInit
108733                           && db->flags&SQLITE_NullCallback)) ){
108734        if( !callbackIsInit ){
108735          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
108736          if( azCols==0 ){
108737            goto exec_out;
108738          }
108739          for(i=0; i<nCol; i++){
108740            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
108741            /* sqlite3VdbeSetColName() installs column names as UTF8
108742            ** strings so there is no way for sqlite3_column_name() to fail. */
108743            assert( azCols[i]!=0 );
108744          }
108745          callbackIsInit = 1;
108746        }
108747        if( rc==SQLITE_ROW ){
108748          azVals = &azCols[nCol];
108749          for(i=0; i<nCol; i++){
108750            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
108751            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
108752              sqlite3OomFault(db);
108753              goto exec_out;
108754            }
108755          }
108756        }
108757        if( xCallback(pArg, nCol, azVals, azCols) ){
108758          /* EVIDENCE-OF: R-38229-40159 If the callback function to
108759          ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
108760          ** return SQLITE_ABORT. */
108761          rc = SQLITE_ABORT;
108762          sqlite3VdbeFinalize((Vdbe *)pStmt);
108763          pStmt = 0;
108764          sqlite3Error(db, SQLITE_ABORT);
108765          goto exec_out;
108766        }
108767      }
108768
108769      if( rc!=SQLITE_ROW ){
108770        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
108771        pStmt = 0;
108772        zSql = zLeftover;
108773        while( sqlite3Isspace(zSql[0]) ) zSql++;
108774        break;
108775      }
108776    }
108777
108778    sqlite3DbFree(db, azCols);
108779    azCols = 0;
108780  }
108781
108782exec_out:
108783  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
108784  sqlite3DbFree(db, azCols);
108785
108786  rc = sqlite3ApiExit(db, rc);
108787  if( rc!=SQLITE_OK && pzErrMsg ){
108788    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
108789    *pzErrMsg = sqlite3Malloc(nErrMsg);
108790    if( *pzErrMsg ){
108791      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
108792    }else{
108793      rc = SQLITE_NOMEM_BKPT;
108794      sqlite3Error(db, SQLITE_NOMEM);
108795    }
108796  }else if( pzErrMsg ){
108797    *pzErrMsg = 0;
108798  }
108799
108800  assert( (rc&db->errMask)==rc );
108801  sqlite3_mutex_leave(db->mutex);
108802  return rc;
108803}
108804
108805/************** End of legacy.c **********************************************/
108806/************** Begin file loadext.c *****************************************/
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 file contains code used to dynamically load extensions into
108819** the SQLite library.
108820*/
108821
108822#ifndef SQLITE_CORE
108823  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
108824#endif
108825/************** Include sqlite3ext.h in the middle of loadext.c **************/
108826/************** Begin file sqlite3ext.h **************************************/
108827/*
108828** 2006 June 7
108829**
108830** The author disclaims copyright to this source code.  In place of
108831** a legal notice, here is a blessing:
108832**
108833**    May you do good and not evil.
108834**    May you find forgiveness for yourself and forgive others.
108835**    May you share freely, never taking more than you give.
108836**
108837*************************************************************************
108838** This header file defines the SQLite interface for use by
108839** shared libraries that want to be imported as extensions into
108840** an SQLite instance.  Shared libraries that intend to be loaded
108841** as extensions by SQLite should #include this file instead of
108842** sqlite3.h.
108843*/
108844#ifndef SQLITE3EXT_H
108845#define SQLITE3EXT_H
108846/* #include "sqlite3.h" */
108847
108848/*
108849** The following structure holds pointers to all of the SQLite API
108850** routines.
108851**
108852** WARNING:  In order to maintain backwards compatibility, add new
108853** interfaces to the end of this structure only.  If you insert new
108854** interfaces in the middle of this structure, then older different
108855** versions of SQLite will not be able to load each other's shared
108856** libraries!
108857*/
108858struct sqlite3_api_routines {
108859  void * (*aggregate_context)(sqlite3_context*,int nBytes);
108860  int  (*aggregate_count)(sqlite3_context*);
108861  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
108862  int  (*bind_double)(sqlite3_stmt*,int,double);
108863  int  (*bind_int)(sqlite3_stmt*,int,int);
108864  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
108865  int  (*bind_null)(sqlite3_stmt*,int);
108866  int  (*bind_parameter_count)(sqlite3_stmt*);
108867  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
108868  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
108869  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
108870  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
108871  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
108872  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
108873  int  (*busy_timeout)(sqlite3*,int ms);
108874  int  (*changes)(sqlite3*);
108875  int  (*close)(sqlite3*);
108876  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
108877                           int eTextRep,const char*));
108878  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
108879                             int eTextRep,const void*));
108880  const void * (*column_blob)(sqlite3_stmt*,int iCol);
108881  int  (*column_bytes)(sqlite3_stmt*,int iCol);
108882  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
108883  int  (*column_count)(sqlite3_stmt*pStmt);
108884  const char * (*column_database_name)(sqlite3_stmt*,int);
108885  const void * (*column_database_name16)(sqlite3_stmt*,int);
108886  const char * (*column_decltype)(sqlite3_stmt*,int i);
108887  const void * (*column_decltype16)(sqlite3_stmt*,int);
108888  double  (*column_double)(sqlite3_stmt*,int iCol);
108889  int  (*column_int)(sqlite3_stmt*,int iCol);
108890  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
108891  const char * (*column_name)(sqlite3_stmt*,int);
108892  const void * (*column_name16)(sqlite3_stmt*,int);
108893  const char * (*column_origin_name)(sqlite3_stmt*,int);
108894  const void * (*column_origin_name16)(sqlite3_stmt*,int);
108895  const char * (*column_table_name)(sqlite3_stmt*,int);
108896  const void * (*column_table_name16)(sqlite3_stmt*,int);
108897  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
108898  const void * (*column_text16)(sqlite3_stmt*,int iCol);
108899  int  (*column_type)(sqlite3_stmt*,int iCol);
108900  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
108901  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
108902  int  (*complete)(const char*sql);
108903  int  (*complete16)(const void*sql);
108904  int  (*create_collation)(sqlite3*,const char*,int,void*,
108905                           int(*)(void*,int,const void*,int,const void*));
108906  int  (*create_collation16)(sqlite3*,const void*,int,void*,
108907                             int(*)(void*,int,const void*,int,const void*));
108908  int  (*create_function)(sqlite3*,const char*,int,int,void*,
108909                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108910                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108911                          void (*xFinal)(sqlite3_context*));
108912  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
108913                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108914                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108915                            void (*xFinal)(sqlite3_context*));
108916  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
108917  int  (*data_count)(sqlite3_stmt*pStmt);
108918  sqlite3 * (*db_handle)(sqlite3_stmt*);
108919  int (*declare_vtab)(sqlite3*,const char*);
108920  int  (*enable_shared_cache)(int);
108921  int  (*errcode)(sqlite3*db);
108922  const char * (*errmsg)(sqlite3*);
108923  const void * (*errmsg16)(sqlite3*);
108924  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
108925  int  (*expired)(sqlite3_stmt*);
108926  int  (*finalize)(sqlite3_stmt*pStmt);
108927  void  (*free)(void*);
108928  void  (*free_table)(char**result);
108929  int  (*get_autocommit)(sqlite3*);
108930  void * (*get_auxdata)(sqlite3_context*,int);
108931  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
108932  int  (*global_recover)(void);
108933  void  (*interruptx)(sqlite3*);
108934  sqlite_int64  (*last_insert_rowid)(sqlite3*);
108935  const char * (*libversion)(void);
108936  int  (*libversion_number)(void);
108937  void *(*malloc)(int);
108938  char * (*mprintf)(const char*,...);
108939  int  (*open)(const char*,sqlite3**);
108940  int  (*open16)(const void*,sqlite3**);
108941  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108942  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108943  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
108944  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
108945  void *(*realloc)(void*,int);
108946  int  (*reset)(sqlite3_stmt*pStmt);
108947  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
108948  void  (*result_double)(sqlite3_context*,double);
108949  void  (*result_error)(sqlite3_context*,const char*,int);
108950  void  (*result_error16)(sqlite3_context*,const void*,int);
108951  void  (*result_int)(sqlite3_context*,int);
108952  void  (*result_int64)(sqlite3_context*,sqlite_int64);
108953  void  (*result_null)(sqlite3_context*);
108954  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
108955  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
108956  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
108957  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
108958  void  (*result_value)(sqlite3_context*,sqlite3_value*);
108959  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
108960  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
108961                         const char*,const char*),void*);
108962  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
108963  char * (*snprintf)(int,char*,const char*,...);
108964  int  (*step)(sqlite3_stmt*);
108965  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
108966                                char const**,char const**,int*,int*,int*);
108967  void  (*thread_cleanup)(void);
108968  int  (*total_changes)(sqlite3*);
108969  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
108970  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
108971  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
108972                                         sqlite_int64),void*);
108973  void * (*user_data)(sqlite3_context*);
108974  const void * (*value_blob)(sqlite3_value*);
108975  int  (*value_bytes)(sqlite3_value*);
108976  int  (*value_bytes16)(sqlite3_value*);
108977  double  (*value_double)(sqlite3_value*);
108978  int  (*value_int)(sqlite3_value*);
108979  sqlite_int64  (*value_int64)(sqlite3_value*);
108980  int  (*value_numeric_type)(sqlite3_value*);
108981  const unsigned char * (*value_text)(sqlite3_value*);
108982  const void * (*value_text16)(sqlite3_value*);
108983  const void * (*value_text16be)(sqlite3_value*);
108984  const void * (*value_text16le)(sqlite3_value*);
108985  int  (*value_type)(sqlite3_value*);
108986  char *(*vmprintf)(const char*,va_list);
108987  /* Added ??? */
108988  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
108989  /* Added by 3.3.13 */
108990  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108991  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108992  int (*clear_bindings)(sqlite3_stmt*);
108993  /* Added by 3.4.1 */
108994  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
108995                          void (*xDestroy)(void *));
108996  /* Added by 3.5.0 */
108997  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
108998  int (*blob_bytes)(sqlite3_blob*);
108999  int (*blob_close)(sqlite3_blob*);
109000  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
109001                   int,sqlite3_blob**);
109002  int (*blob_read)(sqlite3_blob*,void*,int,int);
109003  int (*blob_write)(sqlite3_blob*,const void*,int,int);
109004  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
109005                             int(*)(void*,int,const void*,int,const void*),
109006                             void(*)(void*));
109007  int (*file_control)(sqlite3*,const char*,int,void*);
109008  sqlite3_int64 (*memory_highwater)(int);
109009  sqlite3_int64 (*memory_used)(void);
109010  sqlite3_mutex *(*mutex_alloc)(int);
109011  void (*mutex_enter)(sqlite3_mutex*);
109012  void (*mutex_free)(sqlite3_mutex*);
109013  void (*mutex_leave)(sqlite3_mutex*);
109014  int (*mutex_try)(sqlite3_mutex*);
109015  int (*open_v2)(const char*,sqlite3**,int,const char*);
109016  int (*release_memory)(int);
109017  void (*result_error_nomem)(sqlite3_context*);
109018  void (*result_error_toobig)(sqlite3_context*);
109019  int (*sleep)(int);
109020  void (*soft_heap_limit)(int);
109021  sqlite3_vfs *(*vfs_find)(const char*);
109022  int (*vfs_register)(sqlite3_vfs*,int);
109023  int (*vfs_unregister)(sqlite3_vfs*);
109024  int (*xthreadsafe)(void);
109025  void (*result_zeroblob)(sqlite3_context*,int);
109026  void (*result_error_code)(sqlite3_context*,int);
109027  int (*test_control)(int, ...);
109028  void (*randomness)(int,void*);
109029  sqlite3 *(*context_db_handle)(sqlite3_context*);
109030  int (*extended_result_codes)(sqlite3*,int);
109031  int (*limit)(sqlite3*,int,int);
109032  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
109033  const char *(*sql)(sqlite3_stmt*);
109034  int (*status)(int,int*,int*,int);
109035  int (*backup_finish)(sqlite3_backup*);
109036  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
109037  int (*backup_pagecount)(sqlite3_backup*);
109038  int (*backup_remaining)(sqlite3_backup*);
109039  int (*backup_step)(sqlite3_backup*,int);
109040  const char *(*compileoption_get)(int);
109041  int (*compileoption_used)(const char*);
109042  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
109043                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109044                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109045                            void (*xFinal)(sqlite3_context*),
109046                            void(*xDestroy)(void*));
109047  int (*db_config)(sqlite3*,int,...);
109048  sqlite3_mutex *(*db_mutex)(sqlite3*);
109049  int (*db_status)(sqlite3*,int,int*,int*,int);
109050  int (*extended_errcode)(sqlite3*);
109051  void (*log)(int,const char*,...);
109052  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
109053  const char *(*sourceid)(void);
109054  int (*stmt_status)(sqlite3_stmt*,int,int);
109055  int (*strnicmp)(const char*,const char*,int);
109056  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
109057  int (*wal_autocheckpoint)(sqlite3*,int);
109058  int (*wal_checkpoint)(sqlite3*,const char*);
109059  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
109060  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
109061  int (*vtab_config)(sqlite3*,int op,...);
109062  int (*vtab_on_conflict)(sqlite3*);
109063  /* Version 3.7.16 and later */
109064  int (*close_v2)(sqlite3*);
109065  const char *(*db_filename)(sqlite3*,const char*);
109066  int (*db_readonly)(sqlite3*,const char*);
109067  int (*db_release_memory)(sqlite3*);
109068  const char *(*errstr)(int);
109069  int (*stmt_busy)(sqlite3_stmt*);
109070  int (*stmt_readonly)(sqlite3_stmt*);
109071  int (*stricmp)(const char*,const char*);
109072  int (*uri_boolean)(const char*,const char*,int);
109073  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
109074  const char *(*uri_parameter)(const char*,const char*);
109075  char *(*vsnprintf)(int,char*,const char*,va_list);
109076  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
109077  /* Version 3.8.7 and later */
109078  int (*auto_extension)(void(*)(void));
109079  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
109080                     void(*)(void*));
109081  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
109082                      void(*)(void*),unsigned char);
109083  int (*cancel_auto_extension)(void(*)(void));
109084  int (*load_extension)(sqlite3*,const char*,const char*,char**);
109085  void *(*malloc64)(sqlite3_uint64);
109086  sqlite3_uint64 (*msize)(void*);
109087  void *(*realloc64)(void*,sqlite3_uint64);
109088  void (*reset_auto_extension)(void);
109089  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
109090                        void(*)(void*));
109091  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
109092                         void(*)(void*), unsigned char);
109093  int (*strglob)(const char*,const char*);
109094  /* Version 3.8.11 and later */
109095  sqlite3_value *(*value_dup)(const sqlite3_value*);
109096  void (*value_free)(sqlite3_value*);
109097  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
109098  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
109099  /* Version 3.9.0 and later */
109100  unsigned int (*value_subtype)(sqlite3_value*);
109101  void (*result_subtype)(sqlite3_context*,unsigned int);
109102  /* Version 3.10.0 and later */
109103  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
109104  int (*strlike)(const char*,const char*,unsigned int);
109105  int (*db_cacheflush)(sqlite3*);
109106  /* Version 3.12.0 and later */
109107  int (*system_errno)(sqlite3*);
109108  /* Version 3.14.0 and later */
109109  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
109110  char *(*expanded_sql)(sqlite3_stmt*);
109111};
109112
109113/*
109114** This is the function signature used for all extension entry points.  It
109115** is also defined in the file "loadext.c".
109116*/
109117typedef int (*sqlite3_loadext_entry)(
109118  sqlite3 *db,                       /* Handle to the database. */
109119  char **pzErrMsg,                   /* Used to set error string on failure. */
109120  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
109121);
109122
109123/*
109124** The following macros redefine the API routines so that they are
109125** redirected through the global sqlite3_api structure.
109126**
109127** This header file is also used by the loadext.c source file
109128** (part of the main SQLite library - not an extension) so that
109129** it can get access to the sqlite3_api_routines structure
109130** definition.  But the main library does not want to redefine
109131** the API.  So the redefinition macros are only valid if the
109132** SQLITE_CORE macros is undefined.
109133*/
109134#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
109135#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
109136#ifndef SQLITE_OMIT_DEPRECATED
109137#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
109138#endif
109139#define sqlite3_bind_blob              sqlite3_api->bind_blob
109140#define sqlite3_bind_double            sqlite3_api->bind_double
109141#define sqlite3_bind_int               sqlite3_api->bind_int
109142#define sqlite3_bind_int64             sqlite3_api->bind_int64
109143#define sqlite3_bind_null              sqlite3_api->bind_null
109144#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
109145#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
109146#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
109147#define sqlite3_bind_text              sqlite3_api->bind_text
109148#define sqlite3_bind_text16            sqlite3_api->bind_text16
109149#define sqlite3_bind_value             sqlite3_api->bind_value
109150#define sqlite3_busy_handler           sqlite3_api->busy_handler
109151#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
109152#define sqlite3_changes                sqlite3_api->changes
109153#define sqlite3_close                  sqlite3_api->close
109154#define sqlite3_collation_needed       sqlite3_api->collation_needed
109155#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
109156#define sqlite3_column_blob            sqlite3_api->column_blob
109157#define sqlite3_column_bytes           sqlite3_api->column_bytes
109158#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
109159#define sqlite3_column_count           sqlite3_api->column_count
109160#define sqlite3_column_database_name   sqlite3_api->column_database_name
109161#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
109162#define sqlite3_column_decltype        sqlite3_api->column_decltype
109163#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
109164#define sqlite3_column_double          sqlite3_api->column_double
109165#define sqlite3_column_int             sqlite3_api->column_int
109166#define sqlite3_column_int64           sqlite3_api->column_int64
109167#define sqlite3_column_name            sqlite3_api->column_name
109168#define sqlite3_column_name16          sqlite3_api->column_name16
109169#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
109170#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
109171#define sqlite3_column_table_name      sqlite3_api->column_table_name
109172#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
109173#define sqlite3_column_text            sqlite3_api->column_text
109174#define sqlite3_column_text16          sqlite3_api->column_text16
109175#define sqlite3_column_type            sqlite3_api->column_type
109176#define sqlite3_column_value           sqlite3_api->column_value
109177#define sqlite3_commit_hook            sqlite3_api->commit_hook
109178#define sqlite3_complete               sqlite3_api->complete
109179#define sqlite3_complete16             sqlite3_api->complete16
109180#define sqlite3_create_collation       sqlite3_api->create_collation
109181#define sqlite3_create_collation16     sqlite3_api->create_collation16
109182#define sqlite3_create_function        sqlite3_api->create_function
109183#define sqlite3_create_function16      sqlite3_api->create_function16
109184#define sqlite3_create_module          sqlite3_api->create_module
109185#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
109186#define sqlite3_data_count             sqlite3_api->data_count
109187#define sqlite3_db_handle              sqlite3_api->db_handle
109188#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
109189#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
109190#define sqlite3_errcode                sqlite3_api->errcode
109191#define sqlite3_errmsg                 sqlite3_api->errmsg
109192#define sqlite3_errmsg16               sqlite3_api->errmsg16
109193#define sqlite3_exec                   sqlite3_api->exec
109194#ifndef SQLITE_OMIT_DEPRECATED
109195#define sqlite3_expired                sqlite3_api->expired
109196#endif
109197#define sqlite3_finalize               sqlite3_api->finalize
109198#define sqlite3_free                   sqlite3_api->free
109199#define sqlite3_free_table             sqlite3_api->free_table
109200#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
109201#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
109202#define sqlite3_get_table              sqlite3_api->get_table
109203#ifndef SQLITE_OMIT_DEPRECATED
109204#define sqlite3_global_recover         sqlite3_api->global_recover
109205#endif
109206#define sqlite3_interrupt              sqlite3_api->interruptx
109207#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
109208#define sqlite3_libversion             sqlite3_api->libversion
109209#define sqlite3_libversion_number      sqlite3_api->libversion_number
109210#define sqlite3_malloc                 sqlite3_api->malloc
109211#define sqlite3_mprintf                sqlite3_api->mprintf
109212#define sqlite3_open                   sqlite3_api->open
109213#define sqlite3_open16                 sqlite3_api->open16
109214#define sqlite3_prepare                sqlite3_api->prepare
109215#define sqlite3_prepare16              sqlite3_api->prepare16
109216#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
109217#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
109218#define sqlite3_profile                sqlite3_api->profile
109219#define sqlite3_progress_handler       sqlite3_api->progress_handler
109220#define sqlite3_realloc                sqlite3_api->realloc
109221#define sqlite3_reset                  sqlite3_api->reset
109222#define sqlite3_result_blob            sqlite3_api->result_blob
109223#define sqlite3_result_double          sqlite3_api->result_double
109224#define sqlite3_result_error           sqlite3_api->result_error
109225#define sqlite3_result_error16         sqlite3_api->result_error16
109226#define sqlite3_result_int             sqlite3_api->result_int
109227#define sqlite3_result_int64           sqlite3_api->result_int64
109228#define sqlite3_result_null            sqlite3_api->result_null
109229#define sqlite3_result_text            sqlite3_api->result_text
109230#define sqlite3_result_text16          sqlite3_api->result_text16
109231#define sqlite3_result_text16be        sqlite3_api->result_text16be
109232#define sqlite3_result_text16le        sqlite3_api->result_text16le
109233#define sqlite3_result_value           sqlite3_api->result_value
109234#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
109235#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
109236#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
109237#define sqlite3_snprintf               sqlite3_api->snprintf
109238#define sqlite3_step                   sqlite3_api->step
109239#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
109240#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
109241#define sqlite3_total_changes          sqlite3_api->total_changes
109242#define sqlite3_trace                  sqlite3_api->trace
109243#ifndef SQLITE_OMIT_DEPRECATED
109244#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
109245#endif
109246#define sqlite3_update_hook            sqlite3_api->update_hook
109247#define sqlite3_user_data              sqlite3_api->user_data
109248#define sqlite3_value_blob             sqlite3_api->value_blob
109249#define sqlite3_value_bytes            sqlite3_api->value_bytes
109250#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
109251#define sqlite3_value_double           sqlite3_api->value_double
109252#define sqlite3_value_int              sqlite3_api->value_int
109253#define sqlite3_value_int64            sqlite3_api->value_int64
109254#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
109255#define sqlite3_value_text             sqlite3_api->value_text
109256#define sqlite3_value_text16           sqlite3_api->value_text16
109257#define sqlite3_value_text16be         sqlite3_api->value_text16be
109258#define sqlite3_value_text16le         sqlite3_api->value_text16le
109259#define sqlite3_value_type             sqlite3_api->value_type
109260#define sqlite3_vmprintf               sqlite3_api->vmprintf
109261#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
109262#define sqlite3_overload_function      sqlite3_api->overload_function
109263#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
109264#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
109265#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
109266#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
109267#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
109268#define sqlite3_blob_close             sqlite3_api->blob_close
109269#define sqlite3_blob_open              sqlite3_api->blob_open
109270#define sqlite3_blob_read              sqlite3_api->blob_read
109271#define sqlite3_blob_write             sqlite3_api->blob_write
109272#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
109273#define sqlite3_file_control           sqlite3_api->file_control
109274#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
109275#define sqlite3_memory_used            sqlite3_api->memory_used
109276#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
109277#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
109278#define sqlite3_mutex_free             sqlite3_api->mutex_free
109279#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
109280#define sqlite3_mutex_try              sqlite3_api->mutex_try
109281#define sqlite3_open_v2                sqlite3_api->open_v2
109282#define sqlite3_release_memory         sqlite3_api->release_memory
109283#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
109284#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
109285#define sqlite3_sleep                  sqlite3_api->sleep
109286#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
109287#define sqlite3_vfs_find               sqlite3_api->vfs_find
109288#define sqlite3_vfs_register           sqlite3_api->vfs_register
109289#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
109290#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
109291#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
109292#define sqlite3_result_error_code      sqlite3_api->result_error_code
109293#define sqlite3_test_control           sqlite3_api->test_control
109294#define sqlite3_randomness             sqlite3_api->randomness
109295#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
109296#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
109297#define sqlite3_limit                  sqlite3_api->limit
109298#define sqlite3_next_stmt              sqlite3_api->next_stmt
109299#define sqlite3_sql                    sqlite3_api->sql
109300#define sqlite3_status                 sqlite3_api->status
109301#define sqlite3_backup_finish          sqlite3_api->backup_finish
109302#define sqlite3_backup_init            sqlite3_api->backup_init
109303#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
109304#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
109305#define sqlite3_backup_step            sqlite3_api->backup_step
109306#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
109307#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
109308#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
109309#define sqlite3_db_config              sqlite3_api->db_config
109310#define sqlite3_db_mutex               sqlite3_api->db_mutex
109311#define sqlite3_db_status              sqlite3_api->db_status
109312#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
109313#define sqlite3_log                    sqlite3_api->log
109314#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
109315#define sqlite3_sourceid               sqlite3_api->sourceid
109316#define sqlite3_stmt_status            sqlite3_api->stmt_status
109317#define sqlite3_strnicmp               sqlite3_api->strnicmp
109318#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
109319#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
109320#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
109321#define sqlite3_wal_hook               sqlite3_api->wal_hook
109322#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
109323#define sqlite3_vtab_config            sqlite3_api->vtab_config
109324#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
109325/* Version 3.7.16 and later */
109326#define sqlite3_close_v2               sqlite3_api->close_v2
109327#define sqlite3_db_filename            sqlite3_api->db_filename
109328#define sqlite3_db_readonly            sqlite3_api->db_readonly
109329#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
109330#define sqlite3_errstr                 sqlite3_api->errstr
109331#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
109332#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
109333#define sqlite3_stricmp                sqlite3_api->stricmp
109334#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
109335#define sqlite3_uri_int64              sqlite3_api->uri_int64
109336#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
109337#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
109338#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
109339/* Version 3.8.7 and later */
109340#define sqlite3_auto_extension         sqlite3_api->auto_extension
109341#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
109342#define sqlite3_bind_text64            sqlite3_api->bind_text64
109343#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
109344#define sqlite3_load_extension         sqlite3_api->load_extension
109345#define sqlite3_malloc64               sqlite3_api->malloc64
109346#define sqlite3_msize                  sqlite3_api->msize
109347#define sqlite3_realloc64              sqlite3_api->realloc64
109348#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
109349#define sqlite3_result_blob64          sqlite3_api->result_blob64
109350#define sqlite3_result_text64          sqlite3_api->result_text64
109351#define sqlite3_strglob                sqlite3_api->strglob
109352/* Version 3.8.11 and later */
109353#define sqlite3_value_dup              sqlite3_api->value_dup
109354#define sqlite3_value_free             sqlite3_api->value_free
109355#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
109356#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
109357/* Version 3.9.0 and later */
109358#define sqlite3_value_subtype          sqlite3_api->value_subtype
109359#define sqlite3_result_subtype         sqlite3_api->result_subtype
109360/* Version 3.10.0 and later */
109361#define sqlite3_status64               sqlite3_api->status64
109362#define sqlite3_strlike                sqlite3_api->strlike
109363#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
109364/* Version 3.12.0 and later */
109365#define sqlite3_system_errno           sqlite3_api->system_errno
109366/* Version 3.14.0 and later */
109367#define sqlite3_trace_v2               sqlite3_api->trace_v2
109368#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
109369#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
109370
109371#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
109372  /* This case when the file really is being compiled as a loadable
109373  ** extension */
109374# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
109375# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
109376# define SQLITE_EXTENSION_INIT3     \
109377    extern const sqlite3_api_routines *sqlite3_api;
109378#else
109379  /* This case when the file is being statically linked into the
109380  ** application */
109381# define SQLITE_EXTENSION_INIT1     /*no-op*/
109382# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
109383# define SQLITE_EXTENSION_INIT3     /*no-op*/
109384#endif
109385
109386#endif /* SQLITE3EXT_H */
109387
109388/************** End of sqlite3ext.h ******************************************/
109389/************** Continuing where we left off in loadext.c ********************/
109390/* #include "sqliteInt.h" */
109391/* #include <string.h> */
109392
109393#ifndef SQLITE_OMIT_LOAD_EXTENSION
109394/*
109395** Some API routines are omitted when various features are
109396** excluded from a build of SQLite.  Substitute a NULL pointer
109397** for any missing APIs.
109398*/
109399#ifndef SQLITE_ENABLE_COLUMN_METADATA
109400# define sqlite3_column_database_name   0
109401# define sqlite3_column_database_name16 0
109402# define sqlite3_column_table_name      0
109403# define sqlite3_column_table_name16    0
109404# define sqlite3_column_origin_name     0
109405# define sqlite3_column_origin_name16   0
109406#endif
109407
109408#ifdef SQLITE_OMIT_AUTHORIZATION
109409# define sqlite3_set_authorizer         0
109410#endif
109411
109412#ifdef SQLITE_OMIT_UTF16
109413# define sqlite3_bind_text16            0
109414# define sqlite3_collation_needed16     0
109415# define sqlite3_column_decltype16      0
109416# define sqlite3_column_name16          0
109417# define sqlite3_column_text16          0
109418# define sqlite3_complete16             0
109419# define sqlite3_create_collation16     0
109420# define sqlite3_create_function16      0
109421# define sqlite3_errmsg16               0
109422# define sqlite3_open16                 0
109423# define sqlite3_prepare16              0
109424# define sqlite3_prepare16_v2           0
109425# define sqlite3_result_error16         0
109426# define sqlite3_result_text16          0
109427# define sqlite3_result_text16be        0
109428# define sqlite3_result_text16le        0
109429# define sqlite3_value_text16           0
109430# define sqlite3_value_text16be         0
109431# define sqlite3_value_text16le         0
109432# define sqlite3_column_database_name16 0
109433# define sqlite3_column_table_name16    0
109434# define sqlite3_column_origin_name16   0
109435#endif
109436
109437#ifdef SQLITE_OMIT_COMPLETE
109438# define sqlite3_complete 0
109439# define sqlite3_complete16 0
109440#endif
109441
109442#ifdef SQLITE_OMIT_DECLTYPE
109443# define sqlite3_column_decltype16      0
109444# define sqlite3_column_decltype        0
109445#endif
109446
109447#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
109448# define sqlite3_progress_handler 0
109449#endif
109450
109451#ifdef SQLITE_OMIT_VIRTUALTABLE
109452# define sqlite3_create_module 0
109453# define sqlite3_create_module_v2 0
109454# define sqlite3_declare_vtab 0
109455# define sqlite3_vtab_config 0
109456# define sqlite3_vtab_on_conflict 0
109457#endif
109458
109459#ifdef SQLITE_OMIT_SHARED_CACHE
109460# define sqlite3_enable_shared_cache 0
109461#endif
109462
109463#if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
109464# define sqlite3_profile       0
109465# define sqlite3_trace         0
109466#endif
109467
109468#ifdef SQLITE_OMIT_GET_TABLE
109469# define sqlite3_free_table    0
109470# define sqlite3_get_table     0
109471#endif
109472
109473#ifdef SQLITE_OMIT_INCRBLOB
109474#define sqlite3_bind_zeroblob  0
109475#define sqlite3_blob_bytes     0
109476#define sqlite3_blob_close     0
109477#define sqlite3_blob_open      0
109478#define sqlite3_blob_read      0
109479#define sqlite3_blob_write     0
109480#define sqlite3_blob_reopen    0
109481#endif
109482
109483#if defined(SQLITE_OMIT_TRACE)
109484# define sqlite3_trace_v2      0
109485#endif
109486
109487/*
109488** The following structure contains pointers to all SQLite API routines.
109489** A pointer to this structure is passed into extensions when they are
109490** loaded so that the extension can make calls back into the SQLite
109491** library.
109492**
109493** When adding new APIs, add them to the bottom of this structure
109494** in order to preserve backwards compatibility.
109495**
109496** Extensions that use newer APIs should first call the
109497** sqlite3_libversion_number() to make sure that the API they
109498** intend to use is supported by the library.  Extensions should
109499** also check to make sure that the pointer to the function is
109500** not NULL before calling it.
109501*/
109502static const sqlite3_api_routines sqlite3Apis = {
109503  sqlite3_aggregate_context,
109504#ifndef SQLITE_OMIT_DEPRECATED
109505  sqlite3_aggregate_count,
109506#else
109507  0,
109508#endif
109509  sqlite3_bind_blob,
109510  sqlite3_bind_double,
109511  sqlite3_bind_int,
109512  sqlite3_bind_int64,
109513  sqlite3_bind_null,
109514  sqlite3_bind_parameter_count,
109515  sqlite3_bind_parameter_index,
109516  sqlite3_bind_parameter_name,
109517  sqlite3_bind_text,
109518  sqlite3_bind_text16,
109519  sqlite3_bind_value,
109520  sqlite3_busy_handler,
109521  sqlite3_busy_timeout,
109522  sqlite3_changes,
109523  sqlite3_close,
109524  sqlite3_collation_needed,
109525  sqlite3_collation_needed16,
109526  sqlite3_column_blob,
109527  sqlite3_column_bytes,
109528  sqlite3_column_bytes16,
109529  sqlite3_column_count,
109530  sqlite3_column_database_name,
109531  sqlite3_column_database_name16,
109532  sqlite3_column_decltype,
109533  sqlite3_column_decltype16,
109534  sqlite3_column_double,
109535  sqlite3_column_int,
109536  sqlite3_column_int64,
109537  sqlite3_column_name,
109538  sqlite3_column_name16,
109539  sqlite3_column_origin_name,
109540  sqlite3_column_origin_name16,
109541  sqlite3_column_table_name,
109542  sqlite3_column_table_name16,
109543  sqlite3_column_text,
109544  sqlite3_column_text16,
109545  sqlite3_column_type,
109546  sqlite3_column_value,
109547  sqlite3_commit_hook,
109548  sqlite3_complete,
109549  sqlite3_complete16,
109550  sqlite3_create_collation,
109551  sqlite3_create_collation16,
109552  sqlite3_create_function,
109553  sqlite3_create_function16,
109554  sqlite3_create_module,
109555  sqlite3_data_count,
109556  sqlite3_db_handle,
109557  sqlite3_declare_vtab,
109558  sqlite3_enable_shared_cache,
109559  sqlite3_errcode,
109560  sqlite3_errmsg,
109561  sqlite3_errmsg16,
109562  sqlite3_exec,
109563#ifndef SQLITE_OMIT_DEPRECATED
109564  sqlite3_expired,
109565#else
109566  0,
109567#endif
109568  sqlite3_finalize,
109569  sqlite3_free,
109570  sqlite3_free_table,
109571  sqlite3_get_autocommit,
109572  sqlite3_get_auxdata,
109573  sqlite3_get_table,
109574  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
109575  sqlite3_interrupt,
109576  sqlite3_last_insert_rowid,
109577  sqlite3_libversion,
109578  sqlite3_libversion_number,
109579  sqlite3_malloc,
109580  sqlite3_mprintf,
109581  sqlite3_open,
109582  sqlite3_open16,
109583  sqlite3_prepare,
109584  sqlite3_prepare16,
109585  sqlite3_profile,
109586  sqlite3_progress_handler,
109587  sqlite3_realloc,
109588  sqlite3_reset,
109589  sqlite3_result_blob,
109590  sqlite3_result_double,
109591  sqlite3_result_error,
109592  sqlite3_result_error16,
109593  sqlite3_result_int,
109594  sqlite3_result_int64,
109595  sqlite3_result_null,
109596  sqlite3_result_text,
109597  sqlite3_result_text16,
109598  sqlite3_result_text16be,
109599  sqlite3_result_text16le,
109600  sqlite3_result_value,
109601  sqlite3_rollback_hook,
109602  sqlite3_set_authorizer,
109603  sqlite3_set_auxdata,
109604  sqlite3_snprintf,
109605  sqlite3_step,
109606  sqlite3_table_column_metadata,
109607#ifndef SQLITE_OMIT_DEPRECATED
109608  sqlite3_thread_cleanup,
109609#else
109610  0,
109611#endif
109612  sqlite3_total_changes,
109613  sqlite3_trace,
109614#ifndef SQLITE_OMIT_DEPRECATED
109615  sqlite3_transfer_bindings,
109616#else
109617  0,
109618#endif
109619  sqlite3_update_hook,
109620  sqlite3_user_data,
109621  sqlite3_value_blob,
109622  sqlite3_value_bytes,
109623  sqlite3_value_bytes16,
109624  sqlite3_value_double,
109625  sqlite3_value_int,
109626  sqlite3_value_int64,
109627  sqlite3_value_numeric_type,
109628  sqlite3_value_text,
109629  sqlite3_value_text16,
109630  sqlite3_value_text16be,
109631  sqlite3_value_text16le,
109632  sqlite3_value_type,
109633  sqlite3_vmprintf,
109634  /*
109635  ** The original API set ends here.  All extensions can call any
109636  ** of the APIs above provided that the pointer is not NULL.  But
109637  ** before calling APIs that follow, extension should check the
109638  ** sqlite3_libversion_number() to make sure they are dealing with
109639  ** a library that is new enough to support that API.
109640  *************************************************************************
109641  */
109642  sqlite3_overload_function,
109643
109644  /*
109645  ** Added after 3.3.13
109646  */
109647  sqlite3_prepare_v2,
109648  sqlite3_prepare16_v2,
109649  sqlite3_clear_bindings,
109650
109651  /*
109652  ** Added for 3.4.1
109653  */
109654  sqlite3_create_module_v2,
109655
109656  /*
109657  ** Added for 3.5.0
109658  */
109659  sqlite3_bind_zeroblob,
109660  sqlite3_blob_bytes,
109661  sqlite3_blob_close,
109662  sqlite3_blob_open,
109663  sqlite3_blob_read,
109664  sqlite3_blob_write,
109665  sqlite3_create_collation_v2,
109666  sqlite3_file_control,
109667  sqlite3_memory_highwater,
109668  sqlite3_memory_used,
109669#ifdef SQLITE_MUTEX_OMIT
109670  0,
109671  0,
109672  0,
109673  0,
109674  0,
109675#else
109676  sqlite3_mutex_alloc,
109677  sqlite3_mutex_enter,
109678  sqlite3_mutex_free,
109679  sqlite3_mutex_leave,
109680  sqlite3_mutex_try,
109681#endif
109682  sqlite3_open_v2,
109683  sqlite3_release_memory,
109684  sqlite3_result_error_nomem,
109685  sqlite3_result_error_toobig,
109686  sqlite3_sleep,
109687  sqlite3_soft_heap_limit,
109688  sqlite3_vfs_find,
109689  sqlite3_vfs_register,
109690  sqlite3_vfs_unregister,
109691
109692  /*
109693  ** Added for 3.5.8
109694  */
109695  sqlite3_threadsafe,
109696  sqlite3_result_zeroblob,
109697  sqlite3_result_error_code,
109698  sqlite3_test_control,
109699  sqlite3_randomness,
109700  sqlite3_context_db_handle,
109701
109702  /*
109703  ** Added for 3.6.0
109704  */
109705  sqlite3_extended_result_codes,
109706  sqlite3_limit,
109707  sqlite3_next_stmt,
109708  sqlite3_sql,
109709  sqlite3_status,
109710
109711  /*
109712  ** Added for 3.7.4
109713  */
109714  sqlite3_backup_finish,
109715  sqlite3_backup_init,
109716  sqlite3_backup_pagecount,
109717  sqlite3_backup_remaining,
109718  sqlite3_backup_step,
109719#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
109720  sqlite3_compileoption_get,
109721  sqlite3_compileoption_used,
109722#else
109723  0,
109724  0,
109725#endif
109726  sqlite3_create_function_v2,
109727  sqlite3_db_config,
109728  sqlite3_db_mutex,
109729  sqlite3_db_status,
109730  sqlite3_extended_errcode,
109731  sqlite3_log,
109732  sqlite3_soft_heap_limit64,
109733  sqlite3_sourceid,
109734  sqlite3_stmt_status,
109735  sqlite3_strnicmp,
109736#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109737  sqlite3_unlock_notify,
109738#else
109739  0,
109740#endif
109741#ifndef SQLITE_OMIT_WAL
109742  sqlite3_wal_autocheckpoint,
109743  sqlite3_wal_checkpoint,
109744  sqlite3_wal_hook,
109745#else
109746  0,
109747  0,
109748  0,
109749#endif
109750  sqlite3_blob_reopen,
109751  sqlite3_vtab_config,
109752  sqlite3_vtab_on_conflict,
109753  sqlite3_close_v2,
109754  sqlite3_db_filename,
109755  sqlite3_db_readonly,
109756  sqlite3_db_release_memory,
109757  sqlite3_errstr,
109758  sqlite3_stmt_busy,
109759  sqlite3_stmt_readonly,
109760  sqlite3_stricmp,
109761  sqlite3_uri_boolean,
109762  sqlite3_uri_int64,
109763  sqlite3_uri_parameter,
109764  sqlite3_vsnprintf,
109765  sqlite3_wal_checkpoint_v2,
109766  /* Version 3.8.7 and later */
109767  sqlite3_auto_extension,
109768  sqlite3_bind_blob64,
109769  sqlite3_bind_text64,
109770  sqlite3_cancel_auto_extension,
109771  sqlite3_load_extension,
109772  sqlite3_malloc64,
109773  sqlite3_msize,
109774  sqlite3_realloc64,
109775  sqlite3_reset_auto_extension,
109776  sqlite3_result_blob64,
109777  sqlite3_result_text64,
109778  sqlite3_strglob,
109779  /* Version 3.8.11 and later */
109780  (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
109781  sqlite3_value_free,
109782  sqlite3_result_zeroblob64,
109783  sqlite3_bind_zeroblob64,
109784  /* Version 3.9.0 and later */
109785  sqlite3_value_subtype,
109786  sqlite3_result_subtype,
109787  /* Version 3.10.0 and later */
109788  sqlite3_status64,
109789  sqlite3_strlike,
109790  sqlite3_db_cacheflush,
109791  /* Version 3.12.0 and later */
109792  sqlite3_system_errno,
109793  /* Version 3.14.0 and later */
109794  sqlite3_trace_v2,
109795  sqlite3_expanded_sql
109796};
109797
109798/*
109799** Attempt to load an SQLite extension library contained in the file
109800** zFile.  The entry point is zProc.  zProc may be 0 in which case a
109801** default entry point name (sqlite3_extension_init) is used.  Use
109802** of the default name is recommended.
109803**
109804** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
109805**
109806** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
109807** error message text.  The calling function should free this memory
109808** by calling sqlite3DbFree(db, ).
109809*/
109810static int sqlite3LoadExtension(
109811  sqlite3 *db,          /* Load the extension into this database connection */
109812  const char *zFile,    /* Name of the shared library containing extension */
109813  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
109814  char **pzErrMsg       /* Put error message here if not 0 */
109815){
109816  sqlite3_vfs *pVfs = db->pVfs;
109817  void *handle;
109818  sqlite3_loadext_entry xInit;
109819  char *zErrmsg = 0;
109820  const char *zEntry;
109821  char *zAltEntry = 0;
109822  void **aHandle;
109823  u64 nMsg = 300 + sqlite3Strlen30(zFile);
109824  int ii;
109825  int rc;
109826
109827  /* Shared library endings to try if zFile cannot be loaded as written */
109828  static const char *azEndings[] = {
109829#if SQLITE_OS_WIN
109830     "dll"
109831#elif defined(__APPLE__)
109832     "dylib"
109833#else
109834     "so"
109835#endif
109836  };
109837
109838
109839  if( pzErrMsg ) *pzErrMsg = 0;
109840
109841  /* Ticket #1863.  To avoid a creating security problems for older
109842  ** applications that relink against newer versions of SQLite, the
109843  ** ability to run load_extension is turned off by default.  One
109844  ** must call either sqlite3_enable_load_extension(db) or
109845  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
109846  ** to turn on extension loading.
109847  */
109848  if( (db->flags & SQLITE_LoadExtension)==0 ){
109849    if( pzErrMsg ){
109850      *pzErrMsg = sqlite3_mprintf("not authorized");
109851    }
109852    return SQLITE_ERROR;
109853  }
109854
109855  zEntry = zProc ? zProc : "sqlite3_extension_init";
109856
109857  handle = sqlite3OsDlOpen(pVfs, zFile);
109858#if SQLITE_OS_UNIX || SQLITE_OS_WIN
109859  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
109860    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
109861    if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
109862    handle = sqlite3OsDlOpen(pVfs, zAltFile);
109863    sqlite3_free(zAltFile);
109864  }
109865#endif
109866  if( handle==0 ){
109867    if( pzErrMsg ){
109868      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109869      if( zErrmsg ){
109870        sqlite3_snprintf(nMsg, zErrmsg,
109871            "unable to open shared library [%s]", zFile);
109872        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109873      }
109874    }
109875    return SQLITE_ERROR;
109876  }
109877  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
109878
109879  /* If no entry point was specified and the default legacy
109880  ** entry point name "sqlite3_extension_init" was not found, then
109881  ** construct an entry point name "sqlite3_X_init" where the X is
109882  ** replaced by the lowercase value of every ASCII alphabetic
109883  ** character in the filename after the last "/" upto the first ".",
109884  ** and eliding the first three characters if they are "lib".
109885  ** Examples:
109886  **
109887  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
109888  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
109889  */
109890  if( xInit==0 && zProc==0 ){
109891    int iFile, iEntry, c;
109892    int ncFile = sqlite3Strlen30(zFile);
109893    zAltEntry = sqlite3_malloc64(ncFile+30);
109894    if( zAltEntry==0 ){
109895      sqlite3OsDlClose(pVfs, handle);
109896      return SQLITE_NOMEM_BKPT;
109897    }
109898    memcpy(zAltEntry, "sqlite3_", 8);
109899    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
109900    iFile++;
109901    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
109902    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
109903      if( sqlite3Isalpha(c) ){
109904        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
109905      }
109906    }
109907    memcpy(zAltEntry+iEntry, "_init", 6);
109908    zEntry = zAltEntry;
109909    xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
109910  }
109911  if( xInit==0 ){
109912    if( pzErrMsg ){
109913      nMsg += sqlite3Strlen30(zEntry);
109914      *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109915      if( zErrmsg ){
109916        sqlite3_snprintf(nMsg, zErrmsg,
109917            "no entry point [%s] in shared library [%s]", zEntry, zFile);
109918        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109919      }
109920    }
109921    sqlite3OsDlClose(pVfs, handle);
109922    sqlite3_free(zAltEntry);
109923    return SQLITE_ERROR;
109924  }
109925  sqlite3_free(zAltEntry);
109926  rc = xInit(db, &zErrmsg, &sqlite3Apis);
109927  if( rc ){
109928    if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
109929    if( pzErrMsg ){
109930      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
109931    }
109932    sqlite3_free(zErrmsg);
109933    sqlite3OsDlClose(pVfs, handle);
109934    return SQLITE_ERROR;
109935  }
109936
109937  /* Append the new shared library handle to the db->aExtension array. */
109938  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
109939  if( aHandle==0 ){
109940    return SQLITE_NOMEM_BKPT;
109941  }
109942  if( db->nExtension>0 ){
109943    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
109944  }
109945  sqlite3DbFree(db, db->aExtension);
109946  db->aExtension = aHandle;
109947
109948  db->aExtension[db->nExtension++] = handle;
109949  return SQLITE_OK;
109950}
109951SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
109952  sqlite3 *db,          /* Load the extension into this database connection */
109953  const char *zFile,    /* Name of the shared library containing extension */
109954  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
109955  char **pzErrMsg       /* Put error message here if not 0 */
109956){
109957  int rc;
109958  sqlite3_mutex_enter(db->mutex);
109959  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
109960  rc = sqlite3ApiExit(db, rc);
109961  sqlite3_mutex_leave(db->mutex);
109962  return rc;
109963}
109964
109965/*
109966** Call this routine when the database connection is closing in order
109967** to clean up loaded extensions
109968*/
109969SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
109970  int i;
109971  assert( sqlite3_mutex_held(db->mutex) );
109972  for(i=0; i<db->nExtension; i++){
109973    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
109974  }
109975  sqlite3DbFree(db, db->aExtension);
109976}
109977
109978/*
109979** Enable or disable extension loading.  Extension loading is disabled by
109980** default so as not to open security holes in older applications.
109981*/
109982SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
109983  sqlite3_mutex_enter(db->mutex);
109984  if( onoff ){
109985    db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
109986  }else{
109987    db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
109988  }
109989  sqlite3_mutex_leave(db->mutex);
109990  return SQLITE_OK;
109991}
109992
109993#endif /* SQLITE_OMIT_LOAD_EXTENSION */
109994
109995/*
109996** The auto-extension code added regardless of whether or not extension
109997** loading is supported.  We need a dummy sqlite3Apis pointer for that
109998** code if regular extension loading is not available.  This is that
109999** dummy pointer.
110000*/
110001#ifdef SQLITE_OMIT_LOAD_EXTENSION
110002static const sqlite3_api_routines sqlite3Apis = { 0 };
110003#endif
110004
110005
110006/*
110007** The following object holds the list of automatically loaded
110008** extensions.
110009**
110010** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
110011** mutex must be held while accessing this list.
110012*/
110013typedef struct sqlite3AutoExtList sqlite3AutoExtList;
110014static SQLITE_WSD struct sqlite3AutoExtList {
110015  u32 nExt;              /* Number of entries in aExt[] */
110016  void (**aExt)(void);   /* Pointers to the extension init functions */
110017} sqlite3Autoext = { 0, 0 };
110018
110019/* The "wsdAutoext" macro will resolve to the autoextension
110020** state vector.  If writable static data is unsupported on the target,
110021** we have to locate the state vector at run-time.  In the more common
110022** case where writable static data is supported, wsdStat can refer directly
110023** to the "sqlite3Autoext" state vector declared above.
110024*/
110025#ifdef SQLITE_OMIT_WSD
110026# define wsdAutoextInit \
110027  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
110028# define wsdAutoext x[0]
110029#else
110030# define wsdAutoextInit
110031# define wsdAutoext sqlite3Autoext
110032#endif
110033
110034
110035/*
110036** Register a statically linked extension that is automatically
110037** loaded by every new database connection.
110038*/
110039SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(
110040  void (*xInit)(void)
110041){
110042  int rc = SQLITE_OK;
110043#ifndef SQLITE_OMIT_AUTOINIT
110044  rc = sqlite3_initialize();
110045  if( rc ){
110046    return rc;
110047  }else
110048#endif
110049  {
110050    u32 i;
110051#if SQLITE_THREADSAFE
110052    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110053#endif
110054    wsdAutoextInit;
110055    sqlite3_mutex_enter(mutex);
110056    for(i=0; i<wsdAutoext.nExt; i++){
110057      if( wsdAutoext.aExt[i]==xInit ) break;
110058    }
110059    if( i==wsdAutoext.nExt ){
110060      u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
110061      void (**aNew)(void);
110062      aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
110063      if( aNew==0 ){
110064        rc = SQLITE_NOMEM_BKPT;
110065      }else{
110066        wsdAutoext.aExt = aNew;
110067        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
110068        wsdAutoext.nExt++;
110069      }
110070    }
110071    sqlite3_mutex_leave(mutex);
110072    assert( (rc&0xff)==rc );
110073    return rc;
110074  }
110075}
110076
110077/*
110078** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
110079** set of routines that is invoked for each new database connection, if it
110080** is currently on the list.  If xInit is not on the list, then this
110081** routine is a no-op.
110082**
110083** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
110084** was not on the list.
110085*/
110086SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(
110087  void (*xInit)(void)
110088){
110089#if SQLITE_THREADSAFE
110090  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110091#endif
110092  int i;
110093  int n = 0;
110094  wsdAutoextInit;
110095  sqlite3_mutex_enter(mutex);
110096  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
110097    if( wsdAutoext.aExt[i]==xInit ){
110098      wsdAutoext.nExt--;
110099      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
110100      n++;
110101      break;
110102    }
110103  }
110104  sqlite3_mutex_leave(mutex);
110105  return n;
110106}
110107
110108/*
110109** Reset the automatic extension loading mechanism.
110110*/
110111SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
110112#ifndef SQLITE_OMIT_AUTOINIT
110113  if( sqlite3_initialize()==SQLITE_OK )
110114#endif
110115  {
110116#if SQLITE_THREADSAFE
110117    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110118#endif
110119    wsdAutoextInit;
110120    sqlite3_mutex_enter(mutex);
110121    sqlite3_free(wsdAutoext.aExt);
110122    wsdAutoext.aExt = 0;
110123    wsdAutoext.nExt = 0;
110124    sqlite3_mutex_leave(mutex);
110125  }
110126}
110127
110128/*
110129** Load all automatic extensions.
110130**
110131** If anything goes wrong, set an error in the database connection.
110132*/
110133SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
110134  u32 i;
110135  int go = 1;
110136  int rc;
110137  sqlite3_loadext_entry xInit;
110138
110139  wsdAutoextInit;
110140  if( wsdAutoext.nExt==0 ){
110141    /* Common case: early out without every having to acquire a mutex */
110142    return;
110143  }
110144  for(i=0; go; i++){
110145    char *zErrmsg;
110146#if SQLITE_THREADSAFE
110147    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110148#endif
110149    sqlite3_mutex_enter(mutex);
110150    if( i>=wsdAutoext.nExt ){
110151      xInit = 0;
110152      go = 0;
110153    }else{
110154      xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
110155    }
110156    sqlite3_mutex_leave(mutex);
110157    zErrmsg = 0;
110158    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
110159      sqlite3ErrorWithMsg(db, rc,
110160            "automatic extension loading failed: %s", zErrmsg);
110161      go = 0;
110162    }
110163    sqlite3_free(zErrmsg);
110164  }
110165}
110166
110167/************** End of loadext.c *********************************************/
110168/************** Begin file pragma.c ******************************************/
110169/*
110170** 2003 April 6
110171**
110172** The author disclaims copyright to this source code.  In place of
110173** a legal notice, here is a blessing:
110174**
110175**    May you do good and not evil.
110176**    May you find forgiveness for yourself and forgive others.
110177**    May you share freely, never taking more than you give.
110178**
110179*************************************************************************
110180** This file contains code used to implement the PRAGMA command.
110181*/
110182/* #include "sqliteInt.h" */
110183
110184#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
110185#  if defined(__APPLE__)
110186#    define SQLITE_ENABLE_LOCKING_STYLE 1
110187#  else
110188#    define SQLITE_ENABLE_LOCKING_STYLE 0
110189#  endif
110190#endif
110191
110192/***************************************************************************
110193** The "pragma.h" include file is an automatically generated file that
110194** that includes the PragType_XXXX macro definitions and the aPragmaName[]
110195** object.  This ensures that the aPragmaName[] table is arranged in
110196** lexicographical order to facility a binary search of the pragma name.
110197** Do not edit pragma.h directly.  Edit and rerun the script in at
110198** ../tool/mkpragmatab.tcl. */
110199/************** Include pragma.h in the middle of pragma.c *******************/
110200/************** Begin file pragma.h ******************************************/
110201/* DO NOT EDIT!
110202** This file is automatically generated by the script at
110203** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
110204** that script and rerun it.
110205*/
110206#define PragTyp_HEADER_VALUE                   0
110207#define PragTyp_AUTO_VACUUM                    1
110208#define PragTyp_FLAG                           2
110209#define PragTyp_BUSY_TIMEOUT                   3
110210#define PragTyp_CACHE_SIZE                     4
110211#define PragTyp_CACHE_SPILL                    5
110212#define PragTyp_CASE_SENSITIVE_LIKE            6
110213#define PragTyp_COLLATION_LIST                 7
110214#define PragTyp_COMPILE_OPTIONS                8
110215#define PragTyp_DATA_STORE_DIRECTORY           9
110216#define PragTyp_DATABASE_LIST                 10
110217#define PragTyp_DEFAULT_CACHE_SIZE            11
110218#define PragTyp_ENCODING                      12
110219#define PragTyp_FOREIGN_KEY_CHECK             13
110220#define PragTyp_FOREIGN_KEY_LIST              14
110221#define PragTyp_INCREMENTAL_VACUUM            15
110222#define PragTyp_INDEX_INFO                    16
110223#define PragTyp_INDEX_LIST                    17
110224#define PragTyp_INTEGRITY_CHECK               18
110225#define PragTyp_JOURNAL_MODE                  19
110226#define PragTyp_JOURNAL_SIZE_LIMIT            20
110227#define PragTyp_LOCK_PROXY_FILE               21
110228#define PragTyp_LOCKING_MODE                  22
110229#define PragTyp_PAGE_COUNT                    23
110230#define PragTyp_MMAP_SIZE                     24
110231#define PragTyp_PAGE_SIZE                     25
110232#define PragTyp_SECURE_DELETE                 26
110233#define PragTyp_SHRINK_MEMORY                 27
110234#define PragTyp_SOFT_HEAP_LIMIT               28
110235#define PragTyp_STATS                         29
110236#define PragTyp_SYNCHRONOUS                   30
110237#define PragTyp_TABLE_INFO                    31
110238#define PragTyp_TEMP_STORE                    32
110239#define PragTyp_TEMP_STORE_DIRECTORY          33
110240#define PragTyp_THREADS                       34
110241#define PragTyp_WAL_AUTOCHECKPOINT            35
110242#define PragTyp_WAL_CHECKPOINT                36
110243#define PragTyp_ACTIVATE_EXTENSIONS           37
110244#define PragTyp_HEXKEY                        38
110245#define PragTyp_KEY                           39
110246#define PragTyp_REKEY                         40
110247#define PragTyp_LOCK_STATUS                   41
110248#define PragTyp_PARSER_TRACE                  42
110249#define PragFlag_NeedSchema           0x01
110250#define PragFlag_ReadOnly             0x02
110251static const struct sPragmaNames {
110252  const char *const zName;  /* Name of pragma */
110253  u8 ePragTyp;              /* PragTyp_XXX value */
110254  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
110255  u32 iArg;                 /* Extra argument */
110256} aPragmaNames[] = {
110257#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
110258  { /* zName:     */ "activate_extensions",
110259    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
110260    /* ePragFlag: */ 0,
110261    /* iArg:      */ 0 },
110262#endif
110263#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110264  { /* zName:     */ "application_id",
110265    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110266    /* ePragFlag: */ 0,
110267    /* iArg:      */ BTREE_APPLICATION_ID },
110268#endif
110269#if !defined(SQLITE_OMIT_AUTOVACUUM)
110270  { /* zName:     */ "auto_vacuum",
110271    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
110272    /* ePragFlag: */ PragFlag_NeedSchema,
110273    /* iArg:      */ 0 },
110274#endif
110275#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110276#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
110277  { /* zName:     */ "automatic_index",
110278    /* ePragTyp:  */ PragTyp_FLAG,
110279    /* ePragFlag: */ 0,
110280    /* iArg:      */ SQLITE_AutoIndex },
110281#endif
110282#endif
110283  { /* zName:     */ "busy_timeout",
110284    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
110285    /* ePragFlag: */ 0,
110286    /* iArg:      */ 0 },
110287#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110288  { /* zName:     */ "cache_size",
110289    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
110290    /* ePragFlag: */ PragFlag_NeedSchema,
110291    /* iArg:      */ 0 },
110292#endif
110293#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110294  { /* zName:     */ "cache_spill",
110295    /* ePragTyp:  */ PragTyp_CACHE_SPILL,
110296    /* ePragFlag: */ 0,
110297    /* iArg:      */ 0 },
110298#endif
110299  { /* zName:     */ "case_sensitive_like",
110300    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
110301    /* ePragFlag: */ 0,
110302    /* iArg:      */ 0 },
110303  { /* zName:     */ "cell_size_check",
110304    /* ePragTyp:  */ PragTyp_FLAG,
110305    /* ePragFlag: */ 0,
110306    /* iArg:      */ SQLITE_CellSizeCk },
110307#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110308  { /* zName:     */ "checkpoint_fullfsync",
110309    /* ePragTyp:  */ PragTyp_FLAG,
110310    /* ePragFlag: */ 0,
110311    /* iArg:      */ SQLITE_CkptFullFSync },
110312#endif
110313#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110314  { /* zName:     */ "collation_list",
110315    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
110316    /* ePragFlag: */ 0,
110317    /* iArg:      */ 0 },
110318#endif
110319#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
110320  { /* zName:     */ "compile_options",
110321    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
110322    /* ePragFlag: */ 0,
110323    /* iArg:      */ 0 },
110324#endif
110325#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110326  { /* zName:     */ "count_changes",
110327    /* ePragTyp:  */ PragTyp_FLAG,
110328    /* ePragFlag: */ 0,
110329    /* iArg:      */ SQLITE_CountRows },
110330#endif
110331#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
110332  { /* zName:     */ "data_store_directory",
110333    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
110334    /* ePragFlag: */ 0,
110335    /* iArg:      */ 0 },
110336#endif
110337#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110338  { /* zName:     */ "data_version",
110339    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110340    /* ePragFlag: */ PragFlag_ReadOnly,
110341    /* iArg:      */ BTREE_DATA_VERSION },
110342#endif
110343#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110344  { /* zName:     */ "database_list",
110345    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
110346    /* ePragFlag: */ PragFlag_NeedSchema,
110347    /* iArg:      */ 0 },
110348#endif
110349#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
110350  { /* zName:     */ "default_cache_size",
110351    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
110352    /* ePragFlag: */ PragFlag_NeedSchema,
110353    /* iArg:      */ 0 },
110354#endif
110355#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110356#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110357  { /* zName:     */ "defer_foreign_keys",
110358    /* ePragTyp:  */ PragTyp_FLAG,
110359    /* ePragFlag: */ 0,
110360    /* iArg:      */ SQLITE_DeferFKs },
110361#endif
110362#endif
110363#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110364  { /* zName:     */ "empty_result_callbacks",
110365    /* ePragTyp:  */ PragTyp_FLAG,
110366    /* ePragFlag: */ 0,
110367    /* iArg:      */ SQLITE_NullCallback },
110368#endif
110369#if !defined(SQLITE_OMIT_UTF16)
110370  { /* zName:     */ "encoding",
110371    /* ePragTyp:  */ PragTyp_ENCODING,
110372    /* ePragFlag: */ 0,
110373    /* iArg:      */ 0 },
110374#endif
110375#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110376  { /* zName:     */ "foreign_key_check",
110377    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
110378    /* ePragFlag: */ PragFlag_NeedSchema,
110379    /* iArg:      */ 0 },
110380#endif
110381#if !defined(SQLITE_OMIT_FOREIGN_KEY)
110382  { /* zName:     */ "foreign_key_list",
110383    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
110384    /* ePragFlag: */ PragFlag_NeedSchema,
110385    /* iArg:      */ 0 },
110386#endif
110387#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110388#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110389  { /* zName:     */ "foreign_keys",
110390    /* ePragTyp:  */ PragTyp_FLAG,
110391    /* ePragFlag: */ 0,
110392    /* iArg:      */ SQLITE_ForeignKeys },
110393#endif
110394#endif
110395#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110396  { /* zName:     */ "freelist_count",
110397    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110398    /* ePragFlag: */ PragFlag_ReadOnly,
110399    /* iArg:      */ BTREE_FREE_PAGE_COUNT },
110400#endif
110401#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110402  { /* zName:     */ "full_column_names",
110403    /* ePragTyp:  */ PragTyp_FLAG,
110404    /* ePragFlag: */ 0,
110405    /* iArg:      */ SQLITE_FullColNames },
110406  { /* zName:     */ "fullfsync",
110407    /* ePragTyp:  */ PragTyp_FLAG,
110408    /* ePragFlag: */ 0,
110409    /* iArg:      */ SQLITE_FullFSync },
110410#endif
110411#if defined(SQLITE_HAS_CODEC)
110412  { /* zName:     */ "hexkey",
110413    /* ePragTyp:  */ PragTyp_HEXKEY,
110414    /* ePragFlag: */ 0,
110415    /* iArg:      */ 0 },
110416  { /* zName:     */ "hexrekey",
110417    /* ePragTyp:  */ PragTyp_HEXKEY,
110418    /* ePragFlag: */ 0,
110419    /* iArg:      */ 0 },
110420#endif
110421#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110422#if !defined(SQLITE_OMIT_CHECK)
110423  { /* zName:     */ "ignore_check_constraints",
110424    /* ePragTyp:  */ PragTyp_FLAG,
110425    /* ePragFlag: */ 0,
110426    /* iArg:      */ SQLITE_IgnoreChecks },
110427#endif
110428#endif
110429#if !defined(SQLITE_OMIT_AUTOVACUUM)
110430  { /* zName:     */ "incremental_vacuum",
110431    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
110432    /* ePragFlag: */ PragFlag_NeedSchema,
110433    /* iArg:      */ 0 },
110434#endif
110435#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110436  { /* zName:     */ "index_info",
110437    /* ePragTyp:  */ PragTyp_INDEX_INFO,
110438    /* ePragFlag: */ PragFlag_NeedSchema,
110439    /* iArg:      */ 0 },
110440  { /* zName:     */ "index_list",
110441    /* ePragTyp:  */ PragTyp_INDEX_LIST,
110442    /* ePragFlag: */ PragFlag_NeedSchema,
110443    /* iArg:      */ 0 },
110444  { /* zName:     */ "index_xinfo",
110445    /* ePragTyp:  */ PragTyp_INDEX_INFO,
110446    /* ePragFlag: */ PragFlag_NeedSchema,
110447    /* iArg:      */ 1 },
110448#endif
110449#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
110450  { /* zName:     */ "integrity_check",
110451    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
110452    /* ePragFlag: */ PragFlag_NeedSchema,
110453    /* iArg:      */ 0 },
110454#endif
110455#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110456  { /* zName:     */ "journal_mode",
110457    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
110458    /* ePragFlag: */ PragFlag_NeedSchema,
110459    /* iArg:      */ 0 },
110460  { /* zName:     */ "journal_size_limit",
110461    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
110462    /* ePragFlag: */ 0,
110463    /* iArg:      */ 0 },
110464#endif
110465#if defined(SQLITE_HAS_CODEC)
110466  { /* zName:     */ "key",
110467    /* ePragTyp:  */ PragTyp_KEY,
110468    /* ePragFlag: */ 0,
110469    /* iArg:      */ 0 },
110470#endif
110471#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110472  { /* zName:     */ "legacy_file_format",
110473    /* ePragTyp:  */ PragTyp_FLAG,
110474    /* ePragFlag: */ 0,
110475    /* iArg:      */ SQLITE_LegacyFileFmt },
110476#endif
110477#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
110478  { /* zName:     */ "lock_proxy_file",
110479    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
110480    /* ePragFlag: */ 0,
110481    /* iArg:      */ 0 },
110482#endif
110483#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
110484  { /* zName:     */ "lock_status",
110485    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
110486    /* ePragFlag: */ 0,
110487    /* iArg:      */ 0 },
110488#endif
110489#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110490  { /* zName:     */ "locking_mode",
110491    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
110492    /* ePragFlag: */ 0,
110493    /* iArg:      */ 0 },
110494  { /* zName:     */ "max_page_count",
110495    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
110496    /* ePragFlag: */ PragFlag_NeedSchema,
110497    /* iArg:      */ 0 },
110498  { /* zName:     */ "mmap_size",
110499    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
110500    /* ePragFlag: */ 0,
110501    /* iArg:      */ 0 },
110502  { /* zName:     */ "page_count",
110503    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
110504    /* ePragFlag: */ PragFlag_NeedSchema,
110505    /* iArg:      */ 0 },
110506  { /* zName:     */ "page_size",
110507    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
110508    /* ePragFlag: */ 0,
110509    /* iArg:      */ 0 },
110510#endif
110511#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
110512  { /* zName:     */ "parser_trace",
110513    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
110514    /* ePragFlag: */ 0,
110515    /* iArg:      */ 0 },
110516#endif
110517#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110518  { /* zName:     */ "query_only",
110519    /* ePragTyp:  */ PragTyp_FLAG,
110520    /* ePragFlag: */ 0,
110521    /* iArg:      */ SQLITE_QueryOnly },
110522#endif
110523#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
110524  { /* zName:     */ "quick_check",
110525    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
110526    /* ePragFlag: */ PragFlag_NeedSchema,
110527    /* iArg:      */ 0 },
110528#endif
110529#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110530  { /* zName:     */ "read_uncommitted",
110531    /* ePragTyp:  */ PragTyp_FLAG,
110532    /* ePragFlag: */ 0,
110533    /* iArg:      */ SQLITE_ReadUncommitted },
110534  { /* zName:     */ "recursive_triggers",
110535    /* ePragTyp:  */ PragTyp_FLAG,
110536    /* ePragFlag: */ 0,
110537    /* iArg:      */ SQLITE_RecTriggers },
110538#endif
110539#if defined(SQLITE_HAS_CODEC)
110540  { /* zName:     */ "rekey",
110541    /* ePragTyp:  */ PragTyp_REKEY,
110542    /* ePragFlag: */ 0,
110543    /* iArg:      */ 0 },
110544#endif
110545#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110546  { /* zName:     */ "reverse_unordered_selects",
110547    /* ePragTyp:  */ PragTyp_FLAG,
110548    /* ePragFlag: */ 0,
110549    /* iArg:      */ SQLITE_ReverseOrder },
110550#endif
110551#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110552  { /* zName:     */ "schema_version",
110553    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110554    /* ePragFlag: */ 0,
110555    /* iArg:      */ BTREE_SCHEMA_VERSION },
110556#endif
110557#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110558  { /* zName:     */ "secure_delete",
110559    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
110560    /* ePragFlag: */ 0,
110561    /* iArg:      */ 0 },
110562#endif
110563#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110564  { /* zName:     */ "short_column_names",
110565    /* ePragTyp:  */ PragTyp_FLAG,
110566    /* ePragFlag: */ 0,
110567    /* iArg:      */ SQLITE_ShortColNames },
110568#endif
110569  { /* zName:     */ "shrink_memory",
110570    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
110571    /* ePragFlag: */ 0,
110572    /* iArg:      */ 0 },
110573  { /* zName:     */ "soft_heap_limit",
110574    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
110575    /* ePragFlag: */ 0,
110576    /* iArg:      */ 0 },
110577#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110578#if defined(SQLITE_DEBUG)
110579  { /* zName:     */ "sql_trace",
110580    /* ePragTyp:  */ PragTyp_FLAG,
110581    /* ePragFlag: */ 0,
110582    /* iArg:      */ SQLITE_SqlTrace },
110583#endif
110584#endif
110585#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110586  { /* zName:     */ "stats",
110587    /* ePragTyp:  */ PragTyp_STATS,
110588    /* ePragFlag: */ PragFlag_NeedSchema,
110589    /* iArg:      */ 0 },
110590#endif
110591#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110592  { /* zName:     */ "synchronous",
110593    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
110594    /* ePragFlag: */ PragFlag_NeedSchema,
110595    /* iArg:      */ 0 },
110596#endif
110597#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110598  { /* zName:     */ "table_info",
110599    /* ePragTyp:  */ PragTyp_TABLE_INFO,
110600    /* ePragFlag: */ PragFlag_NeedSchema,
110601    /* iArg:      */ 0 },
110602#endif
110603#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110604  { /* zName:     */ "temp_store",
110605    /* ePragTyp:  */ PragTyp_TEMP_STORE,
110606    /* ePragFlag: */ 0,
110607    /* iArg:      */ 0 },
110608  { /* zName:     */ "temp_store_directory",
110609    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
110610    /* ePragFlag: */ 0,
110611    /* iArg:      */ 0 },
110612#endif
110613  { /* zName:     */ "threads",
110614    /* ePragTyp:  */ PragTyp_THREADS,
110615    /* ePragFlag: */ 0,
110616    /* iArg:      */ 0 },
110617#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110618  { /* zName:     */ "user_version",
110619    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110620    /* ePragFlag: */ 0,
110621    /* iArg:      */ BTREE_USER_VERSION },
110622#endif
110623#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110624#if defined(SQLITE_DEBUG)
110625  { /* zName:     */ "vdbe_addoptrace",
110626    /* ePragTyp:  */ PragTyp_FLAG,
110627    /* ePragFlag: */ 0,
110628    /* iArg:      */ SQLITE_VdbeAddopTrace },
110629  { /* zName:     */ "vdbe_debug",
110630    /* ePragTyp:  */ PragTyp_FLAG,
110631    /* ePragFlag: */ 0,
110632    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
110633  { /* zName:     */ "vdbe_eqp",
110634    /* ePragTyp:  */ PragTyp_FLAG,
110635    /* ePragFlag: */ 0,
110636    /* iArg:      */ SQLITE_VdbeEQP },
110637  { /* zName:     */ "vdbe_listing",
110638    /* ePragTyp:  */ PragTyp_FLAG,
110639    /* ePragFlag: */ 0,
110640    /* iArg:      */ SQLITE_VdbeListing },
110641  { /* zName:     */ "vdbe_trace",
110642    /* ePragTyp:  */ PragTyp_FLAG,
110643    /* ePragFlag: */ 0,
110644    /* iArg:      */ SQLITE_VdbeTrace },
110645#endif
110646#endif
110647#if !defined(SQLITE_OMIT_WAL)
110648  { /* zName:     */ "wal_autocheckpoint",
110649    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
110650    /* ePragFlag: */ 0,
110651    /* iArg:      */ 0 },
110652  { /* zName:     */ "wal_checkpoint",
110653    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
110654    /* ePragFlag: */ PragFlag_NeedSchema,
110655    /* iArg:      */ 0 },
110656#endif
110657#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110658  { /* zName:     */ "writable_schema",
110659    /* ePragTyp:  */ PragTyp_FLAG,
110660    /* ePragFlag: */ 0,
110661    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
110662#endif
110663};
110664/* Number of pragmas: 60 on by default, 73 total. */
110665
110666/************** End of pragma.h **********************************************/
110667/************** Continuing where we left off in pragma.c *********************/
110668
110669/*
110670** Interpret the given string as a safety level.  Return 0 for OFF,
110671** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
110672** unrecognized string argument.  The FULL and EXTRA option is disallowed
110673** if the omitFull parameter it 1.
110674**
110675** Note that the values returned are one less that the values that
110676** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
110677** to support legacy SQL code.  The safety level used to be boolean
110678** and older scripts may have used numbers 0 for OFF and 1 for ON.
110679*/
110680static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
110681                             /* 123456789 123456789 123 */
110682  static const char zText[] = "onoffalseyestruextrafull";
110683  static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
110684  static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
110685  static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
110686                            /* on no off false yes true extra full */
110687  int i, n;
110688  if( sqlite3Isdigit(*z) ){
110689    return (u8)sqlite3Atoi(z);
110690  }
110691  n = sqlite3Strlen30(z);
110692  for(i=0; i<ArraySize(iLength); i++){
110693    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
110694     && (!omitFull || iValue[i]<=1)
110695    ){
110696      return iValue[i];
110697    }
110698  }
110699  return dflt;
110700}
110701
110702/*
110703** Interpret the given string as a boolean value.
110704*/
110705SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
110706  return getSafetyLevel(z,1,dflt)!=0;
110707}
110708
110709/* The sqlite3GetBoolean() function is used by other modules but the
110710** remainder of this file is specific to PRAGMA processing.  So omit
110711** the rest of the file if PRAGMAs are omitted from the build.
110712*/
110713#if !defined(SQLITE_OMIT_PRAGMA)
110714
110715/*
110716** Interpret the given string as a locking mode value.
110717*/
110718static int getLockingMode(const char *z){
110719  if( z ){
110720    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
110721    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
110722  }
110723  return PAGER_LOCKINGMODE_QUERY;
110724}
110725
110726#ifndef SQLITE_OMIT_AUTOVACUUM
110727/*
110728** Interpret the given string as an auto-vacuum mode value.
110729**
110730** The following strings, "none", "full" and "incremental" are
110731** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
110732*/
110733static int getAutoVacuum(const char *z){
110734  int i;
110735  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
110736  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
110737  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
110738  i = sqlite3Atoi(z);
110739  return (u8)((i>=0&&i<=2)?i:0);
110740}
110741#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
110742
110743#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110744/*
110745** Interpret the given string as a temp db location. Return 1 for file
110746** backed temporary databases, 2 for the Red-Black tree in memory database
110747** and 0 to use the compile-time default.
110748*/
110749static int getTempStore(const char *z){
110750  if( z[0]>='0' && z[0]<='2' ){
110751    return z[0] - '0';
110752  }else if( sqlite3StrICmp(z, "file")==0 ){
110753    return 1;
110754  }else if( sqlite3StrICmp(z, "memory")==0 ){
110755    return 2;
110756  }else{
110757    return 0;
110758  }
110759}
110760#endif /* SQLITE_PAGER_PRAGMAS */
110761
110762#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110763/*
110764** Invalidate temp storage, either when the temp storage is changed
110765** from default, or when 'file' and the temp_store_directory has changed
110766*/
110767static int invalidateTempStorage(Parse *pParse){
110768  sqlite3 *db = pParse->db;
110769  if( db->aDb[1].pBt!=0 ){
110770    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
110771      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
110772        "from within a transaction");
110773      return SQLITE_ERROR;
110774    }
110775    sqlite3BtreeClose(db->aDb[1].pBt);
110776    db->aDb[1].pBt = 0;
110777    sqlite3ResetAllSchemasOfConnection(db);
110778  }
110779  return SQLITE_OK;
110780}
110781#endif /* SQLITE_PAGER_PRAGMAS */
110782
110783#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110784/*
110785** If the TEMP database is open, close it and mark the database schema
110786** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
110787** or DEFAULT_TEMP_STORE pragmas.
110788*/
110789static int changeTempStorage(Parse *pParse, const char *zStorageType){
110790  int ts = getTempStore(zStorageType);
110791  sqlite3 *db = pParse->db;
110792  if( db->temp_store==ts ) return SQLITE_OK;
110793  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
110794    return SQLITE_ERROR;
110795  }
110796  db->temp_store = (u8)ts;
110797  return SQLITE_OK;
110798}
110799#endif /* SQLITE_PAGER_PRAGMAS */
110800
110801/*
110802** Set the names of the first N columns to the values in azCol[]
110803*/
110804static void setAllColumnNames(
110805  Vdbe *v,               /* The query under construction */
110806  int N,                 /* Number of columns */
110807  const char **azCol     /* Names of columns */
110808){
110809  int i;
110810  sqlite3VdbeSetNumCols(v, N);
110811  for(i=0; i<N; i++){
110812    sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
110813  }
110814}
110815static void setOneColumnName(Vdbe *v, const char *z){
110816  setAllColumnNames(v, 1, &z);
110817}
110818
110819/*
110820** Generate code to return a single integer value.
110821*/
110822static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
110823  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
110824  setOneColumnName(v, zLabel);
110825  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110826}
110827
110828/*
110829** Generate code to return a single text value.
110830*/
110831static void returnSingleText(
110832  Vdbe *v,                /* Prepared statement under construction */
110833  const char *zLabel,     /* Name of the result column */
110834  const char *zValue      /* Value to be returned */
110835){
110836  if( zValue ){
110837    sqlite3VdbeLoadString(v, 1, (const char*)zValue);
110838    setOneColumnName(v, zLabel);
110839    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110840  }
110841}
110842
110843
110844/*
110845** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
110846** set these values for all pagers.
110847*/
110848#ifndef SQLITE_OMIT_PAGER_PRAGMAS
110849static void setAllPagerFlags(sqlite3 *db){
110850  if( db->autoCommit ){
110851    Db *pDb = db->aDb;
110852    int n = db->nDb;
110853    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
110854    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
110855    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
110856    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
110857             ==  PAGER_FLAGS_MASK );
110858    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
110859    while( (n--) > 0 ){
110860      if( pDb->pBt ){
110861        sqlite3BtreeSetPagerFlags(pDb->pBt,
110862                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
110863      }
110864      pDb++;
110865    }
110866  }
110867}
110868#else
110869# define setAllPagerFlags(X)  /* no-op */
110870#endif
110871
110872
110873/*
110874** Return a human-readable name for a constraint resolution action.
110875*/
110876#ifndef SQLITE_OMIT_FOREIGN_KEY
110877static const char *actionName(u8 action){
110878  const char *zName;
110879  switch( action ){
110880    case OE_SetNull:  zName = "SET NULL";        break;
110881    case OE_SetDflt:  zName = "SET DEFAULT";     break;
110882    case OE_Cascade:  zName = "CASCADE";         break;
110883    case OE_Restrict: zName = "RESTRICT";        break;
110884    default:          zName = "NO ACTION";
110885                      assert( action==OE_None ); break;
110886  }
110887  return zName;
110888}
110889#endif
110890
110891
110892/*
110893** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
110894** defined in pager.h. This function returns the associated lowercase
110895** journal-mode name.
110896*/
110897SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
110898  static char * const azModeName[] = {
110899    "delete", "persist", "off", "truncate", "memory"
110900#ifndef SQLITE_OMIT_WAL
110901     , "wal"
110902#endif
110903  };
110904  assert( PAGER_JOURNALMODE_DELETE==0 );
110905  assert( PAGER_JOURNALMODE_PERSIST==1 );
110906  assert( PAGER_JOURNALMODE_OFF==2 );
110907  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
110908  assert( PAGER_JOURNALMODE_MEMORY==4 );
110909  assert( PAGER_JOURNALMODE_WAL==5 );
110910  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
110911
110912  if( eMode==ArraySize(azModeName) ) return 0;
110913  return azModeName[eMode];
110914}
110915
110916/*
110917** Process a pragma statement.
110918**
110919** Pragmas are of this form:
110920**
110921**      PRAGMA [schema.]id [= value]
110922**
110923** The identifier might also be a string.  The value is a string, and
110924** identifier, or a number.  If minusFlag is true, then the value is
110925** a number that was preceded by a minus sign.
110926**
110927** If the left side is "database.id" then pId1 is the database name
110928** and pId2 is the id.  If the left side is just "id" then pId1 is the
110929** id and pId2 is any empty string.
110930*/
110931SQLITE_PRIVATE void sqlite3Pragma(
110932  Parse *pParse,
110933  Token *pId1,        /* First part of [schema.]id field */
110934  Token *pId2,        /* Second part of [schema.]id field, or NULL */
110935  Token *pValue,      /* Token for <value>, or NULL */
110936  int minusFlag       /* True if a '-' sign preceded <value> */
110937){
110938  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
110939  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
110940  const char *zDb = 0;   /* The database name */
110941  Token *pId;            /* Pointer to <id> token */
110942  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
110943  int iDb;               /* Database index for <database> */
110944  int lwr, upr, mid = 0;       /* Binary search bounds */
110945  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
110946  sqlite3 *db = pParse->db;    /* The database connection */
110947  Db *pDb;                     /* The specific database being pragmaed */
110948  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
110949  const struct sPragmaNames *pPragma;
110950
110951  if( v==0 ) return;
110952  sqlite3VdbeRunOnlyOnce(v);
110953  pParse->nMem = 2;
110954
110955  /* Interpret the [schema.] part of the pragma statement. iDb is the
110956  ** index of the database this pragma is being applied to in db.aDb[]. */
110957  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
110958  if( iDb<0 ) return;
110959  pDb = &db->aDb[iDb];
110960
110961  /* If the temp database has been explicitly named as part of the
110962  ** pragma, make sure it is open.
110963  */
110964  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
110965    return;
110966  }
110967
110968  zLeft = sqlite3NameFromToken(db, pId);
110969  if( !zLeft ) return;
110970  if( minusFlag ){
110971    zRight = sqlite3MPrintf(db, "-%T", pValue);
110972  }else{
110973    zRight = sqlite3NameFromToken(db, pValue);
110974  }
110975
110976  assert( pId2 );
110977  zDb = pId2->n>0 ? pDb->zName : 0;
110978  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
110979    goto pragma_out;
110980  }
110981
110982  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
110983  ** connection.  If it returns SQLITE_OK, then assume that the VFS
110984  ** handled the pragma and generate a no-op prepared statement.
110985  **
110986  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
110987  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
110988  ** object corresponding to the database file to which the pragma
110989  ** statement refers.
110990  **
110991  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
110992  ** file control is an array of pointers to strings (char**) in which the
110993  ** second element of the array is the name of the pragma and the third
110994  ** element is the argument to the pragma or NULL if the pragma has no
110995  ** argument.
110996  */
110997  aFcntl[0] = 0;
110998  aFcntl[1] = zLeft;
110999  aFcntl[2] = zRight;
111000  aFcntl[3] = 0;
111001  db->busyHandler.nBusy = 0;
111002  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
111003  if( rc==SQLITE_OK ){
111004    returnSingleText(v, "result", aFcntl[0]);
111005    sqlite3_free(aFcntl[0]);
111006    goto pragma_out;
111007  }
111008  if( rc!=SQLITE_NOTFOUND ){
111009    if( aFcntl[0] ){
111010      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
111011      sqlite3_free(aFcntl[0]);
111012    }
111013    pParse->nErr++;
111014    pParse->rc = rc;
111015    goto pragma_out;
111016  }
111017
111018  /* Locate the pragma in the lookup table */
111019  lwr = 0;
111020  upr = ArraySize(aPragmaNames)-1;
111021  while( lwr<=upr ){
111022    mid = (lwr+upr)/2;
111023    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
111024    if( rc==0 ) break;
111025    if( rc<0 ){
111026      upr = mid - 1;
111027    }else{
111028      lwr = mid + 1;
111029    }
111030  }
111031  if( lwr>upr ) goto pragma_out;
111032  pPragma = &aPragmaNames[mid];
111033
111034  /* Make sure the database schema is loaded if the pragma requires that */
111035  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
111036    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
111037  }
111038
111039  /* Jump to the appropriate pragma handler */
111040  switch( pPragma->ePragTyp ){
111041
111042#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111043  /*
111044  **  PRAGMA [schema.]default_cache_size
111045  **  PRAGMA [schema.]default_cache_size=N
111046  **
111047  ** The first form reports the current persistent setting for the
111048  ** page cache size.  The value returned is the maximum number of
111049  ** pages in the page cache.  The second form sets both the current
111050  ** page cache size value and the persistent page cache size value
111051  ** stored in the database file.
111052  **
111053  ** Older versions of SQLite would set the default cache size to a
111054  ** negative number to indicate synchronous=OFF.  These days, synchronous
111055  ** is always on by default regardless of the sign of the default cache
111056  ** size.  But continue to take the absolute value of the default cache
111057  ** size of historical compatibility.
111058  */
111059  case PragTyp_DEFAULT_CACHE_SIZE: {
111060    static const int iLn = VDBE_OFFSET_LINENO(2);
111061    static const VdbeOpList getCacheSize[] = {
111062      { OP_Transaction, 0, 0,        0},                         /* 0 */
111063      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
111064      { OP_IfPos,       1, 8,        0},
111065      { OP_Integer,     0, 2,        0},
111066      { OP_Subtract,    1, 2,        1},
111067      { OP_IfPos,       1, 8,        0},
111068      { OP_Integer,     0, 1,        0},                         /* 6 */
111069      { OP_Noop,        0, 0,        0},
111070      { OP_ResultRow,   1, 1,        0},
111071    };
111072    VdbeOp *aOp;
111073    sqlite3VdbeUsesBtree(v, iDb);
111074    if( !zRight ){
111075      setOneColumnName(v, "cache_size");
111076      pParse->nMem += 2;
111077      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
111078      aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
111079      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111080      aOp[0].p1 = iDb;
111081      aOp[1].p1 = iDb;
111082      aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
111083    }else{
111084      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
111085      sqlite3BeginWriteOperation(pParse, 0, iDb);
111086      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
111087      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111088      pDb->pSchema->cache_size = size;
111089      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111090    }
111091    break;
111092  }
111093#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
111094
111095#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111096  /*
111097  **  PRAGMA [schema.]page_size
111098  **  PRAGMA [schema.]page_size=N
111099  **
111100  ** The first form reports the current setting for the
111101  ** database page size in bytes.  The second form sets the
111102  ** database page size value.  The value can only be set if
111103  ** the database has not yet been created.
111104  */
111105  case PragTyp_PAGE_SIZE: {
111106    Btree *pBt = pDb->pBt;
111107    assert( pBt!=0 );
111108    if( !zRight ){
111109      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
111110      returnSingleInt(v, "page_size", size);
111111    }else{
111112      /* Malloc may fail when setting the page-size, as there is an internal
111113      ** buffer that the pager module resizes using sqlite3_realloc().
111114      */
111115      db->nextPagesize = sqlite3Atoi(zRight);
111116      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
111117        sqlite3OomFault(db);
111118      }
111119    }
111120    break;
111121  }
111122
111123  /*
111124  **  PRAGMA [schema.]secure_delete
111125  **  PRAGMA [schema.]secure_delete=ON/OFF
111126  **
111127  ** The first form reports the current setting for the
111128  ** secure_delete flag.  The second form changes the secure_delete
111129  ** flag setting and reports thenew value.
111130  */
111131  case PragTyp_SECURE_DELETE: {
111132    Btree *pBt = pDb->pBt;
111133    int b = -1;
111134    assert( pBt!=0 );
111135    if( zRight ){
111136      b = sqlite3GetBoolean(zRight, 0);
111137    }
111138    if( pId2->n==0 && b>=0 ){
111139      int ii;
111140      for(ii=0; ii<db->nDb; ii++){
111141        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
111142      }
111143    }
111144    b = sqlite3BtreeSecureDelete(pBt, b);
111145    returnSingleInt(v, "secure_delete", b);
111146    break;
111147  }
111148
111149  /*
111150  **  PRAGMA [schema.]max_page_count
111151  **  PRAGMA [schema.]max_page_count=N
111152  **
111153  ** The first form reports the current setting for the
111154  ** maximum number of pages in the database file.  The
111155  ** second form attempts to change this setting.  Both
111156  ** forms return the current setting.
111157  **
111158  ** The absolute value of N is used.  This is undocumented and might
111159  ** change.  The only purpose is to provide an easy way to test
111160  ** the sqlite3AbsInt32() function.
111161  **
111162  **  PRAGMA [schema.]page_count
111163  **
111164  ** Return the number of pages in the specified database.
111165  */
111166  case PragTyp_PAGE_COUNT: {
111167    int iReg;
111168    sqlite3CodeVerifySchema(pParse, iDb);
111169    iReg = ++pParse->nMem;
111170    if( sqlite3Tolower(zLeft[0])=='p' ){
111171      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
111172    }else{
111173      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
111174                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
111175    }
111176    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
111177    sqlite3VdbeSetNumCols(v, 1);
111178    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
111179    break;
111180  }
111181
111182  /*
111183  **  PRAGMA [schema.]locking_mode
111184  **  PRAGMA [schema.]locking_mode = (normal|exclusive)
111185  */
111186  case PragTyp_LOCKING_MODE: {
111187    const char *zRet = "normal";
111188    int eMode = getLockingMode(zRight);
111189
111190    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
111191      /* Simple "PRAGMA locking_mode;" statement. This is a query for
111192      ** the current default locking mode (which may be different to
111193      ** the locking-mode of the main database).
111194      */
111195      eMode = db->dfltLockMode;
111196    }else{
111197      Pager *pPager;
111198      if( pId2->n==0 ){
111199        /* This indicates that no database name was specified as part
111200        ** of the PRAGMA command. In this case the locking-mode must be
111201        ** set on all attached databases, as well as the main db file.
111202        **
111203        ** Also, the sqlite3.dfltLockMode variable is set so that
111204        ** any subsequently attached databases also use the specified
111205        ** locking mode.
111206        */
111207        int ii;
111208        assert(pDb==&db->aDb[0]);
111209        for(ii=2; ii<db->nDb; ii++){
111210          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
111211          sqlite3PagerLockingMode(pPager, eMode);
111212        }
111213        db->dfltLockMode = (u8)eMode;
111214      }
111215      pPager = sqlite3BtreePager(pDb->pBt);
111216      eMode = sqlite3PagerLockingMode(pPager, eMode);
111217    }
111218
111219    assert( eMode==PAGER_LOCKINGMODE_NORMAL
111220            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
111221    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
111222      zRet = "exclusive";
111223    }
111224    returnSingleText(v, "locking_mode", zRet);
111225    break;
111226  }
111227
111228  /*
111229  **  PRAGMA [schema.]journal_mode
111230  **  PRAGMA [schema.]journal_mode =
111231  **                      (delete|persist|off|truncate|memory|wal|off)
111232  */
111233  case PragTyp_JOURNAL_MODE: {
111234    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
111235    int ii;           /* Loop counter */
111236
111237    setOneColumnName(v, "journal_mode");
111238    if( zRight==0 ){
111239      /* If there is no "=MODE" part of the pragma, do a query for the
111240      ** current mode */
111241      eMode = PAGER_JOURNALMODE_QUERY;
111242    }else{
111243      const char *zMode;
111244      int n = sqlite3Strlen30(zRight);
111245      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
111246        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
111247      }
111248      if( !zMode ){
111249        /* If the "=MODE" part does not match any known journal mode,
111250        ** then do a query */
111251        eMode = PAGER_JOURNALMODE_QUERY;
111252      }
111253    }
111254    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
111255      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
111256      iDb = 0;
111257      pId2->n = 1;
111258    }
111259    for(ii=db->nDb-1; ii>=0; ii--){
111260      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
111261        sqlite3VdbeUsesBtree(v, ii);
111262        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
111263      }
111264    }
111265    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111266    break;
111267  }
111268
111269  /*
111270  **  PRAGMA [schema.]journal_size_limit
111271  **  PRAGMA [schema.]journal_size_limit=N
111272  **
111273  ** Get or set the size limit on rollback journal files.
111274  */
111275  case PragTyp_JOURNAL_SIZE_LIMIT: {
111276    Pager *pPager = sqlite3BtreePager(pDb->pBt);
111277    i64 iLimit = -2;
111278    if( zRight ){
111279      sqlite3DecOrHexToI64(zRight, &iLimit);
111280      if( iLimit<-1 ) iLimit = -1;
111281    }
111282    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
111283    returnSingleInt(v, "journal_size_limit", iLimit);
111284    break;
111285  }
111286
111287#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
111288
111289  /*
111290  **  PRAGMA [schema.]auto_vacuum
111291  **  PRAGMA [schema.]auto_vacuum=N
111292  **
111293  ** Get or set the value of the database 'auto-vacuum' parameter.
111294  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
111295  */
111296#ifndef SQLITE_OMIT_AUTOVACUUM
111297  case PragTyp_AUTO_VACUUM: {
111298    Btree *pBt = pDb->pBt;
111299    assert( pBt!=0 );
111300    if( !zRight ){
111301      returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
111302    }else{
111303      int eAuto = getAutoVacuum(zRight);
111304      assert( eAuto>=0 && eAuto<=2 );
111305      db->nextAutovac = (u8)eAuto;
111306      /* Call SetAutoVacuum() to set initialize the internal auto and
111307      ** incr-vacuum flags. This is required in case this connection
111308      ** creates the database file. It is important that it is created
111309      ** as an auto-vacuum capable db.
111310      */
111311      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
111312      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
111313        /* When setting the auto_vacuum mode to either "full" or
111314        ** "incremental", write the value of meta[6] in the database
111315        ** file. Before writing to meta[6], check that meta[3] indicates
111316        ** that this really is an auto-vacuum capable database.
111317        */
111318        static const int iLn = VDBE_OFFSET_LINENO(2);
111319        static const VdbeOpList setMeta6[] = {
111320          { OP_Transaction,    0,         1,                 0},    /* 0 */
111321          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
111322          { OP_If,             1,         0,                 0},    /* 2 */
111323          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
111324          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
111325        };
111326        VdbeOp *aOp;
111327        int iAddr = sqlite3VdbeCurrentAddr(v);
111328        sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
111329        aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
111330        if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111331        aOp[0].p1 = iDb;
111332        aOp[1].p1 = iDb;
111333        aOp[2].p2 = iAddr+4;
111334        aOp[4].p1 = iDb;
111335        aOp[4].p3 = eAuto - 1;
111336        sqlite3VdbeUsesBtree(v, iDb);
111337      }
111338    }
111339    break;
111340  }
111341#endif
111342
111343  /*
111344  **  PRAGMA [schema.]incremental_vacuum(N)
111345  **
111346  ** Do N steps of incremental vacuuming on a database.
111347  */
111348#ifndef SQLITE_OMIT_AUTOVACUUM
111349  case PragTyp_INCREMENTAL_VACUUM: {
111350    int iLimit, addr;
111351    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
111352      iLimit = 0x7fffffff;
111353    }
111354    sqlite3BeginWriteOperation(pParse, 0, iDb);
111355    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
111356    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
111357    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
111358    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
111359    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
111360    sqlite3VdbeJumpHere(v, addr);
111361    break;
111362  }
111363#endif
111364
111365#ifndef SQLITE_OMIT_PAGER_PRAGMAS
111366  /*
111367  **  PRAGMA [schema.]cache_size
111368  **  PRAGMA [schema.]cache_size=N
111369  **
111370  ** The first form reports the current local setting for the
111371  ** page cache size. The second form sets the local
111372  ** page cache size value.  If N is positive then that is the
111373  ** number of pages in the cache.  If N is negative, then the
111374  ** number of pages is adjusted so that the cache uses -N kibibytes
111375  ** of memory.
111376  */
111377  case PragTyp_CACHE_SIZE: {
111378    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111379    if( !zRight ){
111380      returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
111381    }else{
111382      int size = sqlite3Atoi(zRight);
111383      pDb->pSchema->cache_size = size;
111384      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111385    }
111386    break;
111387  }
111388
111389  /*
111390  **  PRAGMA [schema.]cache_spill
111391  **  PRAGMA cache_spill=BOOLEAN
111392  **  PRAGMA [schema.]cache_spill=N
111393  **
111394  ** The first form reports the current local setting for the
111395  ** page cache spill size. The second form turns cache spill on
111396  ** or off.  When turnning cache spill on, the size is set to the
111397  ** current cache_size.  The third form sets a spill size that
111398  ** may be different form the cache size.
111399  ** If N is positive then that is the
111400  ** number of pages in the cache.  If N is negative, then the
111401  ** number of pages is adjusted so that the cache uses -N kibibytes
111402  ** of memory.
111403  **
111404  ** If the number of cache_spill pages is less then the number of
111405  ** cache_size pages, no spilling occurs until the page count exceeds
111406  ** the number of cache_size pages.
111407  **
111408  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
111409  ** not just the schema specified.
111410  */
111411  case PragTyp_CACHE_SPILL: {
111412    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111413    if( !zRight ){
111414      returnSingleInt(v, "cache_spill",
111415         (db->flags & SQLITE_CacheSpill)==0 ? 0 :
111416            sqlite3BtreeSetSpillSize(pDb->pBt,0));
111417    }else{
111418      int size = 1;
111419      if( sqlite3GetInt32(zRight, &size) ){
111420        sqlite3BtreeSetSpillSize(pDb->pBt, size);
111421      }
111422      if( sqlite3GetBoolean(zRight, size!=0) ){
111423        db->flags |= SQLITE_CacheSpill;
111424      }else{
111425        db->flags &= ~SQLITE_CacheSpill;
111426      }
111427      setAllPagerFlags(db);
111428    }
111429    break;
111430  }
111431
111432  /*
111433  **  PRAGMA [schema.]mmap_size(N)
111434  **
111435  ** Used to set mapping size limit. The mapping size limit is
111436  ** used to limit the aggregate size of all memory mapped regions of the
111437  ** database file. If this parameter is set to zero, then memory mapping
111438  ** is not used at all.  If N is negative, then the default memory map
111439  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
111440  ** The parameter N is measured in bytes.
111441  **
111442  ** This value is advisory.  The underlying VFS is free to memory map
111443  ** as little or as much as it wants.  Except, if N is set to 0 then the
111444  ** upper layers will never invoke the xFetch interfaces to the VFS.
111445  */
111446  case PragTyp_MMAP_SIZE: {
111447    sqlite3_int64 sz;
111448#if SQLITE_MAX_MMAP_SIZE>0
111449    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111450    if( zRight ){
111451      int ii;
111452      sqlite3DecOrHexToI64(zRight, &sz);
111453      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
111454      if( pId2->n==0 ) db->szMmap = sz;
111455      for(ii=db->nDb-1; ii>=0; ii--){
111456        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
111457          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
111458        }
111459      }
111460    }
111461    sz = -1;
111462    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
111463#else
111464    sz = 0;
111465    rc = SQLITE_OK;
111466#endif
111467    if( rc==SQLITE_OK ){
111468      returnSingleInt(v, "mmap_size", sz);
111469    }else if( rc!=SQLITE_NOTFOUND ){
111470      pParse->nErr++;
111471      pParse->rc = rc;
111472    }
111473    break;
111474  }
111475
111476  /*
111477  **   PRAGMA temp_store
111478  **   PRAGMA temp_store = "default"|"memory"|"file"
111479  **
111480  ** Return or set the local value of the temp_store flag.  Changing
111481  ** the local value does not make changes to the disk file and the default
111482  ** value will be restored the next time the database is opened.
111483  **
111484  ** Note that it is possible for the library compile-time options to
111485  ** override this setting
111486  */
111487  case PragTyp_TEMP_STORE: {
111488    if( !zRight ){
111489      returnSingleInt(v, "temp_store", db->temp_store);
111490    }else{
111491      changeTempStorage(pParse, zRight);
111492    }
111493    break;
111494  }
111495
111496  /*
111497  **   PRAGMA temp_store_directory
111498  **   PRAGMA temp_store_directory = ""|"directory_name"
111499  **
111500  ** Return or set the local value of the temp_store_directory flag.  Changing
111501  ** the value sets a specific directory to be used for temporary files.
111502  ** Setting to a null string reverts to the default temporary directory search.
111503  ** If temporary directory is changed, then invalidateTempStorage.
111504  **
111505  */
111506  case PragTyp_TEMP_STORE_DIRECTORY: {
111507    if( !zRight ){
111508      returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
111509    }else{
111510#ifndef SQLITE_OMIT_WSD
111511      if( zRight[0] ){
111512        int res;
111513        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
111514        if( rc!=SQLITE_OK || res==0 ){
111515          sqlite3ErrorMsg(pParse, "not a writable directory");
111516          goto pragma_out;
111517        }
111518      }
111519      if( SQLITE_TEMP_STORE==0
111520       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
111521       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
111522      ){
111523        invalidateTempStorage(pParse);
111524      }
111525      sqlite3_free(sqlite3_temp_directory);
111526      if( zRight[0] ){
111527        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
111528      }else{
111529        sqlite3_temp_directory = 0;
111530      }
111531#endif /* SQLITE_OMIT_WSD */
111532    }
111533    break;
111534  }
111535
111536#if SQLITE_OS_WIN
111537  /*
111538  **   PRAGMA data_store_directory
111539  **   PRAGMA data_store_directory = ""|"directory_name"
111540  **
111541  ** Return or set the local value of the data_store_directory flag.  Changing
111542  ** the value sets a specific directory to be used for database files that
111543  ** were specified with a relative pathname.  Setting to a null string reverts
111544  ** to the default database directory, which for database files specified with
111545  ** a relative path will probably be based on the current directory for the
111546  ** process.  Database file specified with an absolute path are not impacted
111547  ** by this setting, regardless of its value.
111548  **
111549  */
111550  case PragTyp_DATA_STORE_DIRECTORY: {
111551    if( !zRight ){
111552      returnSingleText(v, "data_store_directory", sqlite3_data_directory);
111553    }else{
111554#ifndef SQLITE_OMIT_WSD
111555      if( zRight[0] ){
111556        int res;
111557        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
111558        if( rc!=SQLITE_OK || res==0 ){
111559          sqlite3ErrorMsg(pParse, "not a writable directory");
111560          goto pragma_out;
111561        }
111562      }
111563      sqlite3_free(sqlite3_data_directory);
111564      if( zRight[0] ){
111565        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
111566      }else{
111567        sqlite3_data_directory = 0;
111568      }
111569#endif /* SQLITE_OMIT_WSD */
111570    }
111571    break;
111572  }
111573#endif
111574
111575#if SQLITE_ENABLE_LOCKING_STYLE
111576  /*
111577  **   PRAGMA [schema.]lock_proxy_file
111578  **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
111579  **
111580  ** Return or set the value of the lock_proxy_file flag.  Changing
111581  ** the value sets a specific file to be used for database access locks.
111582  **
111583  */
111584  case PragTyp_LOCK_PROXY_FILE: {
111585    if( !zRight ){
111586      Pager *pPager = sqlite3BtreePager(pDb->pBt);
111587      char *proxy_file_path = NULL;
111588      sqlite3_file *pFile = sqlite3PagerFile(pPager);
111589      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
111590                           &proxy_file_path);
111591      returnSingleText(v, "lock_proxy_file", proxy_file_path);
111592    }else{
111593      Pager *pPager = sqlite3BtreePager(pDb->pBt);
111594      sqlite3_file *pFile = sqlite3PagerFile(pPager);
111595      int res;
111596      if( zRight[0] ){
111597        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
111598                                     zRight);
111599      } else {
111600        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
111601                                     NULL);
111602      }
111603      if( res!=SQLITE_OK ){
111604        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
111605        goto pragma_out;
111606      }
111607    }
111608    break;
111609  }
111610#endif /* SQLITE_ENABLE_LOCKING_STYLE */
111611
111612  /*
111613  **   PRAGMA [schema.]synchronous
111614  **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
111615  **
111616  ** Return or set the local value of the synchronous flag.  Changing
111617  ** the local value does not make changes to the disk file and the
111618  ** default value will be restored the next time the database is
111619  ** opened.
111620  */
111621  case PragTyp_SYNCHRONOUS: {
111622    if( !zRight ){
111623      returnSingleInt(v, "synchronous", pDb->safety_level-1);
111624    }else{
111625      if( !db->autoCommit ){
111626        sqlite3ErrorMsg(pParse,
111627            "Safety level may not be changed inside a transaction");
111628      }else{
111629        int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
111630        if( iLevel==0 ) iLevel = 1;
111631        pDb->safety_level = iLevel;
111632        pDb->bSyncSet = 1;
111633        setAllPagerFlags(db);
111634      }
111635    }
111636    break;
111637  }
111638#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
111639
111640#ifndef SQLITE_OMIT_FLAG_PRAGMAS
111641  case PragTyp_FLAG: {
111642    if( zRight==0 ){
111643      returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
111644    }else{
111645      int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
111646      if( db->autoCommit==0 ){
111647        /* Foreign key support may not be enabled or disabled while not
111648        ** in auto-commit mode.  */
111649        mask &= ~(SQLITE_ForeignKeys);
111650      }
111651#if SQLITE_USER_AUTHENTICATION
111652      if( db->auth.authLevel==UAUTH_User ){
111653        /* Do not allow non-admin users to modify the schema arbitrarily */
111654        mask &= ~(SQLITE_WriteSchema);
111655      }
111656#endif
111657
111658      if( sqlite3GetBoolean(zRight, 0) ){
111659        db->flags |= mask;
111660      }else{
111661        db->flags &= ~mask;
111662        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
111663      }
111664
111665      /* Many of the flag-pragmas modify the code generated by the SQL
111666      ** compiler (eg. count_changes). So add an opcode to expire all
111667      ** compiled SQL statements after modifying a pragma value.
111668      */
111669      sqlite3VdbeAddOp0(v, OP_Expire);
111670      setAllPagerFlags(db);
111671    }
111672    break;
111673  }
111674#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
111675
111676#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
111677  /*
111678  **   PRAGMA table_info(<table>)
111679  **
111680  ** Return a single row for each column of the named table. The columns of
111681  ** the returned data set are:
111682  **
111683  ** cid:        Column id (numbered from left to right, starting at 0)
111684  ** name:       Column name
111685  ** type:       Column declaration type.
111686  ** notnull:    True if 'NOT NULL' is part of column declaration
111687  ** dflt_value: The default value for the column, if any.
111688  */
111689  case PragTyp_TABLE_INFO: if( zRight ){
111690    Table *pTab;
111691    pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
111692    if( pTab ){
111693      static const char *azCol[] = {
111694         "cid", "name", "type", "notnull", "dflt_value", "pk"
111695      };
111696      int i, k;
111697      int nHidden = 0;
111698      Column *pCol;
111699      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
111700      pParse->nMem = 6;
111701      sqlite3CodeVerifySchema(pParse, iDb);
111702      setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
111703      sqlite3ViewGetColumnNames(pParse, pTab);
111704      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
111705        if( IsHiddenColumn(pCol) ){
111706          nHidden++;
111707          continue;
111708        }
111709        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
111710          k = 0;
111711        }else if( pPk==0 ){
111712          k = 1;
111713        }else{
111714          for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
111715        }
111716        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
111717        sqlite3VdbeMultiLoad(v, 1, "issisi",
111718               i-nHidden,
111719               pCol->zName,
111720               sqlite3ColumnType(pCol,""),
111721               pCol->notNull ? 1 : 0,
111722               pCol->pDflt ? pCol->pDflt->u.zToken : 0,
111723               k);
111724        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
111725      }
111726    }
111727  }
111728  break;
111729
111730  case PragTyp_STATS: {
111731    static const char *azCol[] = { "table", "index", "width", "height" };
111732    Index *pIdx;
111733    HashElem *i;
111734    v = sqlite3GetVdbe(pParse);
111735    pParse->nMem = 4;
111736    sqlite3CodeVerifySchema(pParse, iDb);
111737    setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
111738    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
111739      Table *pTab = sqliteHashData(i);
111740      sqlite3VdbeMultiLoad(v, 1, "ssii",
111741           pTab->zName,
111742           0,
111743           pTab->szTabRow,
111744           pTab->nRowLogEst);
111745      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111746      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111747        sqlite3VdbeMultiLoad(v, 2, "sii",
111748           pIdx->zName,
111749           pIdx->szIdxRow,
111750           pIdx->aiRowLogEst[0]);
111751        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111752      }
111753    }
111754  }
111755  break;
111756
111757  case PragTyp_INDEX_INFO: if( zRight ){
111758    Index *pIdx;
111759    Table *pTab;
111760    pIdx = sqlite3FindIndex(db, zRight, zDb);
111761    if( pIdx ){
111762      static const char *azCol[] = {
111763         "seqno", "cid", "name", "desc", "coll", "key"
111764      };
111765      int i;
111766      int mx;
111767      if( pPragma->iArg ){
111768        /* PRAGMA index_xinfo (newer version with more rows and columns) */
111769        mx = pIdx->nColumn;
111770        pParse->nMem = 6;
111771      }else{
111772        /* PRAGMA index_info (legacy version) */
111773        mx = pIdx->nKeyCol;
111774        pParse->nMem = 3;
111775      }
111776      pTab = pIdx->pTable;
111777      sqlite3CodeVerifySchema(pParse, iDb);
111778      assert( pParse->nMem<=ArraySize(azCol) );
111779      setAllColumnNames(v, pParse->nMem, azCol);
111780      for(i=0; i<mx; i++){
111781        i16 cnum = pIdx->aiColumn[i];
111782        sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
111783                             cnum<0 ? 0 : pTab->aCol[cnum].zName);
111784        if( pPragma->iArg ){
111785          sqlite3VdbeMultiLoad(v, 4, "isi",
111786            pIdx->aSortOrder[i],
111787            pIdx->azColl[i],
111788            i<pIdx->nKeyCol);
111789        }
111790        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
111791      }
111792    }
111793  }
111794  break;
111795
111796  case PragTyp_INDEX_LIST: if( zRight ){
111797    Index *pIdx;
111798    Table *pTab;
111799    int i;
111800    pTab = sqlite3FindTable(db, zRight, zDb);
111801    if( pTab ){
111802      static const char *azCol[] = {
111803        "seq", "name", "unique", "origin", "partial"
111804      };
111805      v = sqlite3GetVdbe(pParse);
111806      pParse->nMem = 5;
111807      sqlite3CodeVerifySchema(pParse, iDb);
111808      setAllColumnNames(v, 5, azCol);  assert( 5==ArraySize(azCol) );
111809      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
111810        const char *azOrigin[] = { "c", "u", "pk" };
111811        sqlite3VdbeMultiLoad(v, 1, "isisi",
111812           i,
111813           pIdx->zName,
111814           IsUniqueIndex(pIdx),
111815           azOrigin[pIdx->idxType],
111816           pIdx->pPartIdxWhere!=0);
111817        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
111818      }
111819    }
111820  }
111821  break;
111822
111823  case PragTyp_DATABASE_LIST: {
111824    static const char *azCol[] = { "seq", "name", "file" };
111825    int i;
111826    pParse->nMem = 3;
111827    setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
111828    for(i=0; i<db->nDb; i++){
111829      if( db->aDb[i].pBt==0 ) continue;
111830      assert( db->aDb[i].zName!=0 );
111831      sqlite3VdbeMultiLoad(v, 1, "iss",
111832         i,
111833         db->aDb[i].zName,
111834         sqlite3BtreeGetFilename(db->aDb[i].pBt));
111835      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
111836    }
111837  }
111838  break;
111839
111840  case PragTyp_COLLATION_LIST: {
111841    static const char *azCol[] = { "seq", "name" };
111842    int i = 0;
111843    HashElem *p;
111844    pParse->nMem = 2;
111845    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
111846    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
111847      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
111848      sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
111849      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
111850    }
111851  }
111852  break;
111853#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
111854
111855#ifndef SQLITE_OMIT_FOREIGN_KEY
111856  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
111857    FKey *pFK;
111858    Table *pTab;
111859    pTab = sqlite3FindTable(db, zRight, zDb);
111860    if( pTab ){
111861      v = sqlite3GetVdbe(pParse);
111862      pFK = pTab->pFKey;
111863      if( pFK ){
111864        static const char *azCol[] = {
111865           "id", "seq", "table", "from", "to", "on_update", "on_delete",
111866           "match"
111867        };
111868        int i = 0;
111869        pParse->nMem = 8;
111870        sqlite3CodeVerifySchema(pParse, iDb);
111871        setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
111872        while(pFK){
111873          int j;
111874          for(j=0; j<pFK->nCol; j++){
111875            sqlite3VdbeMultiLoad(v, 1, "iissssss",
111876                   i,
111877                   j,
111878                   pFK->zTo,
111879                   pTab->aCol[pFK->aCol[j].iFrom].zName,
111880                   pFK->aCol[j].zCol,
111881                   actionName(pFK->aAction[1]),  /* ON UPDATE */
111882                   actionName(pFK->aAction[0]),  /* ON DELETE */
111883                   "NONE");
111884            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
111885          }
111886          ++i;
111887          pFK = pFK->pNextFrom;
111888        }
111889      }
111890    }
111891  }
111892  break;
111893#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
111894
111895#ifndef SQLITE_OMIT_FOREIGN_KEY
111896#ifndef SQLITE_OMIT_TRIGGER
111897  case PragTyp_FOREIGN_KEY_CHECK: {
111898    FKey *pFK;             /* A foreign key constraint */
111899    Table *pTab;           /* Child table contain "REFERENCES" keyword */
111900    Table *pParent;        /* Parent table that child points to */
111901    Index *pIdx;           /* Index in the parent table */
111902    int i;                 /* Loop counter:  Foreign key number for pTab */
111903    int j;                 /* Loop counter:  Field of the foreign key */
111904    HashElem *k;           /* Loop counter:  Next table in schema */
111905    int x;                 /* result variable */
111906    int regResult;         /* 3 registers to hold a result row */
111907    int regKey;            /* Register to hold key for checking the FK */
111908    int regRow;            /* Registers to hold a row from pTab */
111909    int addrTop;           /* Top of a loop checking foreign keys */
111910    int addrOk;            /* Jump here if the key is OK */
111911    int *aiCols;           /* child to parent column mapping */
111912    static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
111913
111914    regResult = pParse->nMem+1;
111915    pParse->nMem += 4;
111916    regKey = ++pParse->nMem;
111917    regRow = ++pParse->nMem;
111918    v = sqlite3GetVdbe(pParse);
111919    setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
111920    sqlite3CodeVerifySchema(pParse, iDb);
111921    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
111922    while( k ){
111923      if( zRight ){
111924        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
111925        k = 0;
111926      }else{
111927        pTab = (Table*)sqliteHashData(k);
111928        k = sqliteHashNext(k);
111929      }
111930      if( pTab==0 || pTab->pFKey==0 ) continue;
111931      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
111932      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
111933      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
111934      sqlite3VdbeLoadString(v, regResult, pTab->zName);
111935      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111936        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111937        if( pParent==0 ) continue;
111938        pIdx = 0;
111939        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
111940        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
111941        if( x==0 ){
111942          if( pIdx==0 ){
111943            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
111944          }else{
111945            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
111946            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111947          }
111948        }else{
111949          k = 0;
111950          break;
111951        }
111952      }
111953      assert( pParse->nErr>0 || pFK==0 );
111954      if( pFK ) break;
111955      if( pParse->nTab<i ) pParse->nTab = i;
111956      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
111957      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111958        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111959        pIdx = 0;
111960        aiCols = 0;
111961        if( pParent ){
111962          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
111963          assert( x==0 );
111964        }
111965        addrOk = sqlite3VdbeMakeLabel(v);
111966        if( pParent && pIdx==0 ){
111967          int iKey = pFK->aCol[0].iFrom;
111968          assert( iKey>=0 && iKey<pTab->nCol );
111969          if( iKey!=pTab->iPKey ){
111970            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
111971            sqlite3ColumnDefault(v, pTab, iKey, regRow);
111972            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
111973          }else{
111974            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
111975          }
111976          sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
111977          sqlite3VdbeGoto(v, addrOk);
111978          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
111979        }else{
111980          for(j=0; j<pFK->nCol; j++){
111981            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
111982                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
111983            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
111984          }
111985          if( pParent ){
111986            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
111987                              sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
111988            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
111989            VdbeCoverage(v);
111990          }
111991        }
111992        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
111993        sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
111994        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
111995        sqlite3VdbeResolveLabel(v, addrOk);
111996        sqlite3DbFree(db, aiCols);
111997      }
111998      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
111999      sqlite3VdbeJumpHere(v, addrTop);
112000    }
112001  }
112002  break;
112003#endif /* !defined(SQLITE_OMIT_TRIGGER) */
112004#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
112005
112006#ifndef NDEBUG
112007  case PragTyp_PARSER_TRACE: {
112008    if( zRight ){
112009      if( sqlite3GetBoolean(zRight, 0) ){
112010        sqlite3ParserTrace(stdout, "parser: ");
112011      }else{
112012        sqlite3ParserTrace(0, 0);
112013      }
112014    }
112015  }
112016  break;
112017#endif
112018
112019  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
112020  ** used will be case sensitive or not depending on the RHS.
112021  */
112022  case PragTyp_CASE_SENSITIVE_LIKE: {
112023    if( zRight ){
112024      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
112025    }
112026  }
112027  break;
112028
112029#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
112030# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
112031#endif
112032
112033#ifndef SQLITE_OMIT_INTEGRITY_CHECK
112034  /* Pragma "quick_check" is reduced version of
112035  ** integrity_check designed to detect most database corruption
112036  ** without most of the overhead of a full integrity-check.
112037  */
112038  case PragTyp_INTEGRITY_CHECK: {
112039    int i, j, addr, mxErr;
112040
112041    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
112042
112043    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
112044    ** then iDb is set to the index of the database identified by <db>.
112045    ** In this case, the integrity of database iDb only is verified by
112046    ** the VDBE created below.
112047    **
112048    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
112049    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
112050    ** to -1 here, to indicate that the VDBE should verify the integrity
112051    ** of all attached databases.  */
112052    assert( iDb>=0 );
112053    assert( iDb==0 || pId2->z );
112054    if( pId2->z==0 ) iDb = -1;
112055
112056    /* Initialize the VDBE program */
112057    pParse->nMem = 6;
112058    setOneColumnName(v, "integrity_check");
112059
112060    /* Set the maximum error count */
112061    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112062    if( zRight ){
112063      sqlite3GetInt32(zRight, &mxErr);
112064      if( mxErr<=0 ){
112065        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112066      }
112067    }
112068    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
112069
112070    /* Do an integrity check on each database file */
112071    for(i=0; i<db->nDb; i++){
112072      HashElem *x;
112073      Hash *pTbls;
112074      int *aRoot;
112075      int cnt = 0;
112076      int mxIdx = 0;
112077      int nIdx;
112078
112079      if( OMIT_TEMPDB && i==1 ) continue;
112080      if( iDb>=0 && i!=iDb ) continue;
112081
112082      sqlite3CodeVerifySchema(pParse, i);
112083      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
112084      VdbeCoverage(v);
112085      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112086      sqlite3VdbeJumpHere(v, addr);
112087
112088      /* Do an integrity check of the B-Tree
112089      **
112090      ** Begin by finding the root pages numbers
112091      ** for all tables and indices in the database.
112092      */
112093      assert( sqlite3SchemaMutexHeld(db, i, 0) );
112094      pTbls = &db->aDb[i].pSchema->tblHash;
112095      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
112096        Table *pTab = sqliteHashData(x);
112097        Index *pIdx;
112098        if( HasRowid(pTab) ) cnt++;
112099        for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
112100        if( nIdx>mxIdx ) mxIdx = nIdx;
112101      }
112102      aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
112103      if( aRoot==0 ) break;
112104      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
112105        Table *pTab = sqliteHashData(x);
112106        Index *pIdx;
112107        if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
112108        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
112109          aRoot[cnt++] = pIdx->tnum;
112110        }
112111      }
112112      aRoot[cnt] = 0;
112113
112114      /* Make sure sufficient number of registers have been allocated */
112115      pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
112116
112117      /* Do the b-tree integrity checks */
112118      sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
112119      sqlite3VdbeChangeP5(v, (u8)i);
112120      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
112121      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
112122         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
112123         P4_DYNAMIC);
112124      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
112125      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
112126      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
112127      sqlite3VdbeJumpHere(v, addr);
112128
112129      /* Make sure all the indices are constructed correctly.
112130      */
112131      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
112132        Table *pTab = sqliteHashData(x);
112133        Index *pIdx, *pPk;
112134        Index *pPrior = 0;
112135        int loopTop;
112136        int iDataCur, iIdxCur;
112137        int r1 = -1;
112138
112139        if( pTab->pIndex==0 ) continue;
112140        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
112141        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
112142        VdbeCoverage(v);
112143        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112144        sqlite3VdbeJumpHere(v, addr);
112145        sqlite3ExprCacheClear(pParse);
112146        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
112147                                   1, 0, &iDataCur, &iIdxCur);
112148        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
112149        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112150          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
112151        }
112152        assert( pParse->nMem>=8+j );
112153        assert( sqlite3NoTempsInRange(pParse,1,7+j) );
112154        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
112155        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
112156        /* Verify that all NOT NULL columns really are NOT NULL */
112157        for(j=0; j<pTab->nCol; j++){
112158          char *zErr;
112159          int jmp2, jmp3;
112160          if( j==pTab->iPKey ) continue;
112161          if( pTab->aCol[j].notNull==0 ) continue;
112162          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
112163          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
112164          jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
112165          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112166          zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
112167                              pTab->aCol[j].zName);
112168          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
112169          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
112170          jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
112171          sqlite3VdbeAddOp0(v, OP_Halt);
112172          sqlite3VdbeJumpHere(v, jmp2);
112173          sqlite3VdbeJumpHere(v, jmp3);
112174        }
112175        /* Validate index entries for the current row */
112176        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112177          int jmp2, jmp3, jmp4, jmp5;
112178          int ckUniq = sqlite3VdbeMakeLabel(v);
112179          if( pPk==pIdx ) continue;
112180          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
112181                                       pPrior, r1);
112182          pPrior = pIdx;
112183          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
112184          /* Verify that an index entry exists for the current table row */
112185          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
112186                                      pIdx->nColumn); VdbeCoverage(v);
112187          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112188          sqlite3VdbeLoadString(v, 3, "row ");
112189          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
112190          sqlite3VdbeLoadString(v, 4, " missing from index ");
112191          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
112192          jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
112193          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
112194          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
112195          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
112196          sqlite3VdbeAddOp0(v, OP_Halt);
112197          sqlite3VdbeJumpHere(v, jmp2);
112198          /* For UNIQUE indexes, verify that only one entry exists with the
112199          ** current key.  The entry is unique if (1) any column is NULL
112200          ** or (2) the next entry has a different key */
112201          if( IsUniqueIndex(pIdx) ){
112202            int uniqOk = sqlite3VdbeMakeLabel(v);
112203            int jmp6;
112204            int kk;
112205            for(kk=0; kk<pIdx->nKeyCol; kk++){
112206              int iCol = pIdx->aiColumn[kk];
112207              assert( iCol!=XN_ROWID && iCol<pTab->nCol );
112208              if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
112209              sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
112210              VdbeCoverage(v);
112211            }
112212            jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
112213            sqlite3VdbeGoto(v, uniqOk);
112214            sqlite3VdbeJumpHere(v, jmp6);
112215            sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
112216                                 pIdx->nKeyCol); VdbeCoverage(v);
112217            sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112218            sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
112219            sqlite3VdbeGoto(v, jmp5);
112220            sqlite3VdbeResolveLabel(v, uniqOk);
112221          }
112222          sqlite3VdbeJumpHere(v, jmp4);
112223          sqlite3ResolvePartIdxLabel(pParse, jmp3);
112224        }
112225        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
112226        sqlite3VdbeJumpHere(v, loopTop-1);
112227#ifndef SQLITE_OMIT_BTREECOUNT
112228        sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
112229        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112230          if( pPk==pIdx ) continue;
112231          addr = sqlite3VdbeCurrentAddr(v);
112232          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
112233          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112234          sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
112235          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
112236          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
112237          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
112238          sqlite3VdbeLoadString(v, 3, pIdx->zName);
112239          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
112240          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
112241        }
112242#endif /* SQLITE_OMIT_BTREECOUNT */
112243      }
112244    }
112245    {
112246      static const int iLn = VDBE_OFFSET_LINENO(2);
112247      static const VdbeOpList endCode[] = {
112248        { OP_AddImm,      1, 0,        0},    /* 0 */
112249        { OP_If,          1, 4,        0},    /* 1 */
112250        { OP_String8,     0, 3,        0},    /* 2 */
112251        { OP_ResultRow,   3, 1,        0},    /* 3 */
112252      };
112253      VdbeOp *aOp;
112254
112255      aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
112256      if( aOp ){
112257        aOp[0].p2 = -mxErr;
112258        aOp[2].p4type = P4_STATIC;
112259        aOp[2].p4.z = "ok";
112260      }
112261    }
112262  }
112263  break;
112264#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
112265
112266#ifndef SQLITE_OMIT_UTF16
112267  /*
112268  **   PRAGMA encoding
112269  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
112270  **
112271  ** In its first form, this pragma returns the encoding of the main
112272  ** database. If the database is not initialized, it is initialized now.
112273  **
112274  ** The second form of this pragma is a no-op if the main database file
112275  ** has not already been initialized. In this case it sets the default
112276  ** encoding that will be used for the main database file if a new file
112277  ** is created. If an existing main database file is opened, then the
112278  ** default text encoding for the existing database is used.
112279  **
112280  ** In all cases new databases created using the ATTACH command are
112281  ** created to use the same default text encoding as the main database. If
112282  ** the main database has not been initialized and/or created when ATTACH
112283  ** is executed, this is done before the ATTACH operation.
112284  **
112285  ** In the second form this pragma sets the text encoding to be used in
112286  ** new database files created using this database handle. It is only
112287  ** useful if invoked immediately after the main database i
112288  */
112289  case PragTyp_ENCODING: {
112290    static const struct EncName {
112291      char *zName;
112292      u8 enc;
112293    } encnames[] = {
112294      { "UTF8",     SQLITE_UTF8        },
112295      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
112296      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
112297      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
112298      { "UTF16le",  SQLITE_UTF16LE     },
112299      { "UTF16be",  SQLITE_UTF16BE     },
112300      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
112301      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
112302      { 0, 0 }
112303    };
112304    const struct EncName *pEnc;
112305    if( !zRight ){    /* "PRAGMA encoding" */
112306      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
112307      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
112308      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
112309      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
112310      returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
112311    }else{                        /* "PRAGMA encoding = XXX" */
112312      /* Only change the value of sqlite.enc if the database handle is not
112313      ** initialized. If the main database exists, the new sqlite.enc value
112314      ** will be overwritten when the schema is next loaded. If it does not
112315      ** already exists, it will be created to use the new encoding value.
112316      */
112317      if(
112318        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
112319        DbHasProperty(db, 0, DB_Empty)
112320      ){
112321        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
112322          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
112323            SCHEMA_ENC(db) = ENC(db) =
112324                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
112325            break;
112326          }
112327        }
112328        if( !pEnc->zName ){
112329          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
112330        }
112331      }
112332    }
112333  }
112334  break;
112335#endif /* SQLITE_OMIT_UTF16 */
112336
112337#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
112338  /*
112339  **   PRAGMA [schema.]schema_version
112340  **   PRAGMA [schema.]schema_version = <integer>
112341  **
112342  **   PRAGMA [schema.]user_version
112343  **   PRAGMA [schema.]user_version = <integer>
112344  **
112345  **   PRAGMA [schema.]freelist_count
112346  **
112347  **   PRAGMA [schema.]data_version
112348  **
112349  **   PRAGMA [schema.]application_id
112350  **   PRAGMA [schema.]application_id = <integer>
112351  **
112352  ** The pragma's schema_version and user_version are used to set or get
112353  ** the value of the schema-version and user-version, respectively. Both
112354  ** the schema-version and the user-version are 32-bit signed integers
112355  ** stored in the database header.
112356  **
112357  ** The schema-cookie is usually only manipulated internally by SQLite. It
112358  ** is incremented by SQLite whenever the database schema is modified (by
112359  ** creating or dropping a table or index). The schema version is used by
112360  ** SQLite each time a query is executed to ensure that the internal cache
112361  ** of the schema used when compiling the SQL query matches the schema of
112362  ** the database against which the compiled query is actually executed.
112363  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
112364  ** the schema-version is potentially dangerous and may lead to program
112365  ** crashes or database corruption. Use with caution!
112366  **
112367  ** The user-version is not used internally by SQLite. It may be used by
112368  ** applications for any purpose.
112369  */
112370  case PragTyp_HEADER_VALUE: {
112371    int iCookie = pPragma->iArg;  /* Which cookie to read or write */
112372    sqlite3VdbeUsesBtree(v, iDb);
112373    if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
112374      /* Write the specified cookie value */
112375      static const VdbeOpList setCookie[] = {
112376        { OP_Transaction,    0,  1,  0},    /* 0 */
112377        { OP_SetCookie,      0,  0,  0},    /* 1 */
112378      };
112379      VdbeOp *aOp;
112380      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
112381      aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
112382      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112383      aOp[0].p1 = iDb;
112384      aOp[1].p1 = iDb;
112385      aOp[1].p2 = iCookie;
112386      aOp[1].p3 = sqlite3Atoi(zRight);
112387    }else{
112388      /* Read the specified cookie value */
112389      static const VdbeOpList readCookie[] = {
112390        { OP_Transaction,     0,  0,  0},    /* 0 */
112391        { OP_ReadCookie,      0,  1,  0},    /* 1 */
112392        { OP_ResultRow,       1,  1,  0}
112393      };
112394      VdbeOp *aOp;
112395      sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
112396      aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
112397      if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112398      aOp[0].p1 = iDb;
112399      aOp[1].p1 = iDb;
112400      aOp[1].p3 = iCookie;
112401      sqlite3VdbeSetNumCols(v, 1);
112402      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
112403      sqlite3VdbeReusable(v);
112404    }
112405  }
112406  break;
112407#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
112408
112409#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
112410  /*
112411  **   PRAGMA compile_options
112412  **
112413  ** Return the names of all compile-time options used in this build,
112414  ** one option per row.
112415  */
112416  case PragTyp_COMPILE_OPTIONS: {
112417    int i = 0;
112418    const char *zOpt;
112419    pParse->nMem = 1;
112420    setOneColumnName(v, "compile_option");
112421    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
112422      sqlite3VdbeLoadString(v, 1, zOpt);
112423      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
112424    }
112425    sqlite3VdbeReusable(v);
112426  }
112427  break;
112428#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
112429
112430#ifndef SQLITE_OMIT_WAL
112431  /*
112432  **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
112433  **
112434  ** Checkpoint the database.
112435  */
112436  case PragTyp_WAL_CHECKPOINT: {
112437    static const char *azCol[] = { "busy", "log", "checkpointed" };
112438    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
112439    int eMode = SQLITE_CHECKPOINT_PASSIVE;
112440    if( zRight ){
112441      if( sqlite3StrICmp(zRight, "full")==0 ){
112442        eMode = SQLITE_CHECKPOINT_FULL;
112443      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
112444        eMode = SQLITE_CHECKPOINT_RESTART;
112445      }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
112446        eMode = SQLITE_CHECKPOINT_TRUNCATE;
112447      }
112448    }
112449    setAllColumnNames(v, 3, azCol);  assert( 3==ArraySize(azCol) );
112450    pParse->nMem = 3;
112451    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
112452    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
112453  }
112454  break;
112455
112456  /*
112457  **   PRAGMA wal_autocheckpoint
112458  **   PRAGMA wal_autocheckpoint = N
112459  **
112460  ** Configure a database connection to automatically checkpoint a database
112461  ** after accumulating N frames in the log. Or query for the current value
112462  ** of N.
112463  */
112464  case PragTyp_WAL_AUTOCHECKPOINT: {
112465    if( zRight ){
112466      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
112467    }
112468    returnSingleInt(v, "wal_autocheckpoint",
112469       db->xWalCallback==sqlite3WalDefaultHook ?
112470           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
112471  }
112472  break;
112473#endif
112474
112475  /*
112476  **  PRAGMA shrink_memory
112477  **
112478  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
112479  ** connection on which it is invoked to free up as much memory as it
112480  ** can, by calling sqlite3_db_release_memory().
112481  */
112482  case PragTyp_SHRINK_MEMORY: {
112483    sqlite3_db_release_memory(db);
112484    break;
112485  }
112486
112487  /*
112488  **   PRAGMA busy_timeout
112489  **   PRAGMA busy_timeout = N
112490  **
112491  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
112492  ** if one is set.  If no busy handler or a different busy handler is set
112493  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
112494  ** disables the timeout.
112495  */
112496  /*case PragTyp_BUSY_TIMEOUT*/ default: {
112497    assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
112498    if( zRight ){
112499      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
112500    }
112501    returnSingleInt(v, "timeout",  db->busyTimeout);
112502    break;
112503  }
112504
112505  /*
112506  **   PRAGMA soft_heap_limit
112507  **   PRAGMA soft_heap_limit = N
112508  **
112509  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
112510  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
112511  ** specified and is a non-negative integer.
112512  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
112513  ** returns the same integer that would be returned by the
112514  ** sqlite3_soft_heap_limit64(-1) C-language function.
112515  */
112516  case PragTyp_SOFT_HEAP_LIMIT: {
112517    sqlite3_int64 N;
112518    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
112519      sqlite3_soft_heap_limit64(N);
112520    }
112521    returnSingleInt(v, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
112522    break;
112523  }
112524
112525  /*
112526  **   PRAGMA threads
112527  **   PRAGMA threads = N
112528  **
112529  ** Configure the maximum number of worker threads.  Return the new
112530  ** maximum, which might be less than requested.
112531  */
112532  case PragTyp_THREADS: {
112533    sqlite3_int64 N;
112534    if( zRight
112535     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
112536     && N>=0
112537    ){
112538      sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
112539    }
112540    returnSingleInt(v, "threads",
112541                    sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
112542    break;
112543  }
112544
112545#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
112546  /*
112547  ** Report the current state of file logs for all databases
112548  */
112549  case PragTyp_LOCK_STATUS: {
112550    static const char *const azLockName[] = {
112551      "unlocked", "shared", "reserved", "pending", "exclusive"
112552    };
112553    static const char *azCol[] = { "database", "status" };
112554    int i;
112555    setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
112556    pParse->nMem = 2;
112557    for(i=0; i<db->nDb; i++){
112558      Btree *pBt;
112559      const char *zState = "unknown";
112560      int j;
112561      if( db->aDb[i].zName==0 ) continue;
112562      pBt = db->aDb[i].pBt;
112563      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
112564        zState = "closed";
112565      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
112566                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
112567         zState = azLockName[j];
112568      }
112569      sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
112570      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
112571    }
112572    break;
112573  }
112574#endif
112575
112576#ifdef SQLITE_HAS_CODEC
112577  case PragTyp_KEY: {
112578    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
112579    break;
112580  }
112581  case PragTyp_REKEY: {
112582    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
112583    break;
112584  }
112585  case PragTyp_HEXKEY: {
112586    if( zRight ){
112587      u8 iByte;
112588      int i;
112589      char zKey[40];
112590      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
112591        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
112592        if( (i&1)!=0 ) zKey[i/2] = iByte;
112593      }
112594      if( (zLeft[3] & 0xf)==0xb ){
112595        sqlite3_key_v2(db, zDb, zKey, i/2);
112596      }else{
112597        sqlite3_rekey_v2(db, zDb, zKey, i/2);
112598      }
112599    }
112600    break;
112601  }
112602#endif
112603#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
112604  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
112605#ifdef SQLITE_HAS_CODEC
112606    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
112607      sqlite3_activate_see(&zRight[4]);
112608    }
112609#endif
112610#ifdef SQLITE_ENABLE_CEROD
112611    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
112612      sqlite3_activate_cerod(&zRight[6]);
112613    }
112614#endif
112615  }
112616  break;
112617#endif
112618
112619  } /* End of the PRAGMA switch */
112620
112621pragma_out:
112622  sqlite3DbFree(db, zLeft);
112623  sqlite3DbFree(db, zRight);
112624}
112625
112626#endif /* SQLITE_OMIT_PRAGMA */
112627
112628/************** End of pragma.c **********************************************/
112629/************** Begin file prepare.c *****************************************/
112630/*
112631** 2005 May 25
112632**
112633** The author disclaims copyright to this source code.  In place of
112634** a legal notice, here is a blessing:
112635**
112636**    May you do good and not evil.
112637**    May you find forgiveness for yourself and forgive others.
112638**    May you share freely, never taking more than you give.
112639**
112640*************************************************************************
112641** This file contains the implementation of the sqlite3_prepare()
112642** interface, and routines that contribute to loading the database schema
112643** from disk.
112644*/
112645/* #include "sqliteInt.h" */
112646
112647/*
112648** Fill the InitData structure with an error message that indicates
112649** that the database is corrupt.
112650*/
112651static void corruptSchema(
112652  InitData *pData,     /* Initialization context */
112653  const char *zObj,    /* Object being parsed at the point of error */
112654  const char *zExtra   /* Error information */
112655){
112656  sqlite3 *db = pData->db;
112657  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
112658    char *z;
112659    if( zObj==0 ) zObj = "?";
112660    z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
112661    if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
112662    sqlite3DbFree(db, *pData->pzErrMsg);
112663    *pData->pzErrMsg = z;
112664  }
112665  pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
112666}
112667
112668/*
112669** This is the callback routine for the code that initializes the
112670** database.  See sqlite3Init() below for additional information.
112671** This routine is also called from the OP_ParseSchema opcode of the VDBE.
112672**
112673** Each callback contains the following information:
112674**
112675**     argv[0] = name of thing being created
112676**     argv[1] = root page number for table or index. 0 for trigger or view.
112677**     argv[2] = SQL text for the CREATE statement.
112678**
112679*/
112680SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
112681  InitData *pData = (InitData*)pInit;
112682  sqlite3 *db = pData->db;
112683  int iDb = pData->iDb;
112684
112685  assert( argc==3 );
112686  UNUSED_PARAMETER2(NotUsed, argc);
112687  assert( sqlite3_mutex_held(db->mutex) );
112688  DbClearProperty(db, iDb, DB_Empty);
112689  if( db->mallocFailed ){
112690    corruptSchema(pData, argv[0], 0);
112691    return 1;
112692  }
112693
112694  assert( iDb>=0 && iDb<db->nDb );
112695  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
112696  if( argv[1]==0 ){
112697    corruptSchema(pData, argv[0], 0);
112698  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
112699    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
112700    ** But because db->init.busy is set to 1, no VDBE code is generated
112701    ** or executed.  All the parser does is build the internal data
112702    ** structures that describe the table, index, or view.
112703    */
112704    int rc;
112705    sqlite3_stmt *pStmt;
112706    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
112707
112708    assert( db->init.busy );
112709    db->init.iDb = iDb;
112710    db->init.newTnum = sqlite3Atoi(argv[1]);
112711    db->init.orphanTrigger = 0;
112712    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
112713    rc = db->errCode;
112714    assert( (rc&0xFF)==(rcp&0xFF) );
112715    db->init.iDb = 0;
112716    if( SQLITE_OK!=rc ){
112717      if( db->init.orphanTrigger ){
112718        assert( iDb==1 );
112719      }else{
112720        pData->rc = rc;
112721        if( rc==SQLITE_NOMEM ){
112722          sqlite3OomFault(db);
112723        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
112724          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
112725        }
112726      }
112727    }
112728    sqlite3_finalize(pStmt);
112729  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
112730    corruptSchema(pData, argv[0], 0);
112731  }else{
112732    /* If the SQL column is blank it means this is an index that
112733    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
112734    ** constraint for a CREATE TABLE.  The index should have already
112735    ** been created when we processed the CREATE TABLE.  All we have
112736    ** to do here is record the root page number for that index.
112737    */
112738    Index *pIndex;
112739    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
112740    if( pIndex==0 ){
112741      /* This can occur if there exists an index on a TEMP table which
112742      ** has the same name as another index on a permanent index.  Since
112743      ** the permanent table is hidden by the TEMP table, we can also
112744      ** safely ignore the index on the permanent table.
112745      */
112746      /* Do Nothing */;
112747    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
112748      corruptSchema(pData, argv[0], "invalid rootpage");
112749    }
112750  }
112751  return 0;
112752}
112753
112754/*
112755** Attempt to read the database schema and initialize internal
112756** data structures for a single database file.  The index of the
112757** database file is given by iDb.  iDb==0 is used for the main
112758** database.  iDb==1 should never be used.  iDb>=2 is used for
112759** auxiliary databases.  Return one of the SQLITE_ error codes to
112760** indicate success or failure.
112761*/
112762static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
112763  int rc;
112764  int i;
112765#ifndef SQLITE_OMIT_DEPRECATED
112766  int size;
112767#endif
112768  Db *pDb;
112769  char const *azArg[4];
112770  int meta[5];
112771  InitData initData;
112772  const char *zMasterName;
112773  int openedTransaction = 0;
112774
112775  assert( iDb>=0 && iDb<db->nDb );
112776  assert( db->aDb[iDb].pSchema );
112777  assert( sqlite3_mutex_held(db->mutex) );
112778  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
112779
112780  /* Construct the in-memory representation schema tables (sqlite_master or
112781  ** sqlite_temp_master) by invoking the parser directly.  The appropriate
112782  ** table name will be inserted automatically by the parser so we can just
112783  ** use the abbreviation "x" here.  The parser will also automatically tag
112784  ** the schema table as read-only. */
112785  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
112786  azArg[1] = "1";
112787  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
112788                            "rootpage integer,sql text)";
112789  azArg[3] = 0;
112790  initData.db = db;
112791  initData.iDb = iDb;
112792  initData.rc = SQLITE_OK;
112793  initData.pzErrMsg = pzErrMsg;
112794  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
112795  if( initData.rc ){
112796    rc = initData.rc;
112797    goto error_out;
112798  }
112799
112800  /* Create a cursor to hold the database open
112801  */
112802  pDb = &db->aDb[iDb];
112803  if( pDb->pBt==0 ){
112804    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
112805      DbSetProperty(db, 1, DB_SchemaLoaded);
112806    }
112807    return SQLITE_OK;
112808  }
112809
112810  /* If there is not already a read-only (or read-write) transaction opened
112811  ** on the b-tree database, open one now. If a transaction is opened, it
112812  ** will be closed before this function returns.  */
112813  sqlite3BtreeEnter(pDb->pBt);
112814  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
112815    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
112816    if( rc!=SQLITE_OK ){
112817      sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
112818      goto initone_error_out;
112819    }
112820    openedTransaction = 1;
112821  }
112822
112823  /* Get the database meta information.
112824  **
112825  ** Meta values are as follows:
112826  **    meta[0]   Schema cookie.  Changes with each schema change.
112827  **    meta[1]   File format of schema layer.
112828  **    meta[2]   Size of the page cache.
112829  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
112830  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
112831  **    meta[5]   User version
112832  **    meta[6]   Incremental vacuum mode
112833  **    meta[7]   unused
112834  **    meta[8]   unused
112835  **    meta[9]   unused
112836  **
112837  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
112838  ** the possible values of meta[4].
112839  */
112840  for(i=0; i<ArraySize(meta); i++){
112841    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
112842  }
112843  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
112844
112845  /* If opening a non-empty database, check the text encoding. For the
112846  ** main database, set sqlite3.enc to the encoding of the main database.
112847  ** For an attached db, it is an error if the encoding is not the same
112848  ** as sqlite3.enc.
112849  */
112850  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
112851    if( iDb==0 ){
112852#ifndef SQLITE_OMIT_UTF16
112853      u8 encoding;
112854      /* If opening the main database, set ENC(db). */
112855      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
112856      if( encoding==0 ) encoding = SQLITE_UTF8;
112857      ENC(db) = encoding;
112858#else
112859      ENC(db) = SQLITE_UTF8;
112860#endif
112861    }else{
112862      /* If opening an attached database, the encoding much match ENC(db) */
112863      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
112864        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
112865            " text encoding as main database");
112866        rc = SQLITE_ERROR;
112867        goto initone_error_out;
112868      }
112869    }
112870  }else{
112871    DbSetProperty(db, iDb, DB_Empty);
112872  }
112873  pDb->pSchema->enc = ENC(db);
112874
112875  if( pDb->pSchema->cache_size==0 ){
112876#ifndef SQLITE_OMIT_DEPRECATED
112877    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
112878    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
112879    pDb->pSchema->cache_size = size;
112880#else
112881    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
112882#endif
112883    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
112884  }
112885
112886  /*
112887  ** file_format==1    Version 3.0.0.
112888  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
112889  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
112890  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
112891  */
112892  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
112893  if( pDb->pSchema->file_format==0 ){
112894    pDb->pSchema->file_format = 1;
112895  }
112896  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
112897    sqlite3SetString(pzErrMsg, db, "unsupported file format");
112898    rc = SQLITE_ERROR;
112899    goto initone_error_out;
112900  }
112901
112902  /* Ticket #2804:  When we open a database in the newer file format,
112903  ** clear the legacy_file_format pragma flag so that a VACUUM will
112904  ** not downgrade the database and thus invalidate any descending
112905  ** indices that the user might have created.
112906  */
112907  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
112908    db->flags &= ~SQLITE_LegacyFileFmt;
112909  }
112910
112911  /* Read the schema information out of the schema tables
112912  */
112913  assert( db->init.busy );
112914  {
112915    char *zSql;
112916    zSql = sqlite3MPrintf(db,
112917        "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
112918        db->aDb[iDb].zName, zMasterName);
112919#ifndef SQLITE_OMIT_AUTHORIZATION
112920    {
112921      sqlite3_xauth xAuth;
112922      xAuth = db->xAuth;
112923      db->xAuth = 0;
112924#endif
112925      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
112926#ifndef SQLITE_OMIT_AUTHORIZATION
112927      db->xAuth = xAuth;
112928    }
112929#endif
112930    if( rc==SQLITE_OK ) rc = initData.rc;
112931    sqlite3DbFree(db, zSql);
112932#ifndef SQLITE_OMIT_ANALYZE
112933    if( rc==SQLITE_OK ){
112934      sqlite3AnalysisLoad(db, iDb);
112935    }
112936#endif
112937  }
112938  if( db->mallocFailed ){
112939    rc = SQLITE_NOMEM_BKPT;
112940    sqlite3ResetAllSchemasOfConnection(db);
112941  }
112942  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
112943    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
112944    ** the schema loaded, even if errors occurred. In this situation the
112945    ** current sqlite3_prepare() operation will fail, but the following one
112946    ** will attempt to compile the supplied statement against whatever subset
112947    ** of the schema was loaded before the error occurred. The primary
112948    ** purpose of this is to allow access to the sqlite_master table
112949    ** even when its contents have been corrupted.
112950    */
112951    DbSetProperty(db, iDb, DB_SchemaLoaded);
112952    rc = SQLITE_OK;
112953  }
112954
112955  /* Jump here for an error that occurs after successfully allocating
112956  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
112957  ** before that point, jump to error_out.
112958  */
112959initone_error_out:
112960  if( openedTransaction ){
112961    sqlite3BtreeCommit(pDb->pBt);
112962  }
112963  sqlite3BtreeLeave(pDb->pBt);
112964
112965error_out:
112966  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
112967    sqlite3OomFault(db);
112968  }
112969  return rc;
112970}
112971
112972/*
112973** Initialize all database files - the main database file, the file
112974** used to store temporary tables, and any additional database files
112975** created using ATTACH statements.  Return a success code.  If an
112976** error occurs, write an error message into *pzErrMsg.
112977**
112978** After a database is initialized, the DB_SchemaLoaded bit is set
112979** bit is set in the flags field of the Db structure. If the database
112980** file was of zero-length, then the DB_Empty flag is also set.
112981*/
112982SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
112983  int i, rc;
112984  int commit_internal = !(db->flags&SQLITE_InternChanges);
112985
112986  assert( sqlite3_mutex_held(db->mutex) );
112987  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
112988  assert( db->init.busy==0 );
112989  rc = SQLITE_OK;
112990  db->init.busy = 1;
112991  ENC(db) = SCHEMA_ENC(db);
112992  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
112993    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
112994    rc = sqlite3InitOne(db, i, pzErrMsg);
112995    if( rc ){
112996      sqlite3ResetOneSchema(db, i);
112997    }
112998  }
112999
113000  /* Once all the other databases have been initialized, load the schema
113001  ** for the TEMP database. This is loaded last, as the TEMP database
113002  ** schema may contain references to objects in other databases.
113003  */
113004#ifndef SQLITE_OMIT_TEMPDB
113005  assert( db->nDb>1 );
113006  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
113007    rc = sqlite3InitOne(db, 1, pzErrMsg);
113008    if( rc ){
113009      sqlite3ResetOneSchema(db, 1);
113010    }
113011  }
113012#endif
113013
113014  db->init.busy = 0;
113015  if( rc==SQLITE_OK && commit_internal ){
113016    sqlite3CommitInternalChanges(db);
113017  }
113018
113019  return rc;
113020}
113021
113022/*
113023** This routine is a no-op if the database schema is already initialized.
113024** Otherwise, the schema is loaded. An error code is returned.
113025*/
113026SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
113027  int rc = SQLITE_OK;
113028  sqlite3 *db = pParse->db;
113029  assert( sqlite3_mutex_held(db->mutex) );
113030  if( !db->init.busy ){
113031    rc = sqlite3Init(db, &pParse->zErrMsg);
113032  }
113033  if( rc!=SQLITE_OK ){
113034    pParse->rc = rc;
113035    pParse->nErr++;
113036  }
113037  return rc;
113038}
113039
113040
113041/*
113042** Check schema cookies in all databases.  If any cookie is out
113043** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
113044** make no changes to pParse->rc.
113045*/
113046static void schemaIsValid(Parse *pParse){
113047  sqlite3 *db = pParse->db;
113048  int iDb;
113049  int rc;
113050  int cookie;
113051
113052  assert( pParse->checkSchema );
113053  assert( sqlite3_mutex_held(db->mutex) );
113054  for(iDb=0; iDb<db->nDb; iDb++){
113055    int openedTransaction = 0;         /* True if a transaction is opened */
113056    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
113057    if( pBt==0 ) continue;
113058
113059    /* If there is not already a read-only (or read-write) transaction opened
113060    ** on the b-tree database, open one now. If a transaction is opened, it
113061    ** will be closed immediately after reading the meta-value. */
113062    if( !sqlite3BtreeIsInReadTrans(pBt) ){
113063      rc = sqlite3BtreeBeginTrans(pBt, 0);
113064      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113065        sqlite3OomFault(db);
113066      }
113067      if( rc!=SQLITE_OK ) return;
113068      openedTransaction = 1;
113069    }
113070
113071    /* Read the schema cookie from the database. If it does not match the
113072    ** value stored as part of the in-memory schema representation,
113073    ** set Parse.rc to SQLITE_SCHEMA. */
113074    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
113075    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113076    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
113077      sqlite3ResetOneSchema(db, iDb);
113078      pParse->rc = SQLITE_SCHEMA;
113079    }
113080
113081    /* Close the transaction, if one was opened. */
113082    if( openedTransaction ){
113083      sqlite3BtreeCommit(pBt);
113084    }
113085  }
113086}
113087
113088/*
113089** Convert a schema pointer into the iDb index that indicates
113090** which database file in db->aDb[] the schema refers to.
113091**
113092** If the same database is attached more than once, the first
113093** attached database is returned.
113094*/
113095SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
113096  int i = -1000000;
113097
113098  /* If pSchema is NULL, then return -1000000. This happens when code in
113099  ** expr.c is trying to resolve a reference to a transient table (i.e. one
113100  ** created by a sub-select). In this case the return value of this
113101  ** function should never be used.
113102  **
113103  ** We return -1000000 instead of the more usual -1 simply because using
113104  ** -1000000 as the incorrect index into db->aDb[] is much
113105  ** more likely to cause a segfault than -1 (of course there are assert()
113106  ** statements too, but it never hurts to play the odds).
113107  */
113108  assert( sqlite3_mutex_held(db->mutex) );
113109  if( pSchema ){
113110    for(i=0; ALWAYS(i<db->nDb); i++){
113111      if( db->aDb[i].pSchema==pSchema ){
113112        break;
113113      }
113114    }
113115    assert( i>=0 && i<db->nDb );
113116  }
113117  return i;
113118}
113119
113120/*
113121** Free all memory allocations in the pParse object
113122*/
113123SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
113124  if( pParse ){
113125    sqlite3 *db = pParse->db;
113126    sqlite3DbFree(db, pParse->aLabel);
113127    sqlite3ExprListDelete(db, pParse->pConstExpr);
113128    if( db ){
113129      assert( db->lookaside.bDisable >= pParse->disableLookaside );
113130      db->lookaside.bDisable -= pParse->disableLookaside;
113131    }
113132    pParse->disableLookaside = 0;
113133  }
113134}
113135
113136/*
113137** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
113138*/
113139static int sqlite3Prepare(
113140  sqlite3 *db,              /* Database handle. */
113141  const char *zSql,         /* UTF-8 encoded SQL statement. */
113142  int nBytes,               /* Length of zSql in bytes. */
113143  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
113144  Vdbe *pReprepare,         /* VM being reprepared */
113145  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113146  const char **pzTail       /* OUT: End of parsed string */
113147){
113148  Parse *pParse;            /* Parsing context */
113149  char *zErrMsg = 0;        /* Error message */
113150  int rc = SQLITE_OK;       /* Result code */
113151  int i;                    /* Loop counter */
113152
113153  /* Allocate the parsing context */
113154  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
113155  if( pParse==0 ){
113156    rc = SQLITE_NOMEM_BKPT;
113157    goto end_prepare;
113158  }
113159  pParse->pReprepare = pReprepare;
113160  assert( ppStmt && *ppStmt==0 );
113161  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
113162  assert( sqlite3_mutex_held(db->mutex) );
113163
113164  /* Check to verify that it is possible to get a read lock on all
113165  ** database schemas.  The inability to get a read lock indicates that
113166  ** some other database connection is holding a write-lock, which in
113167  ** turn means that the other connection has made uncommitted changes
113168  ** to the schema.
113169  **
113170  ** Were we to proceed and prepare the statement against the uncommitted
113171  ** schema changes and if those schema changes are subsequently rolled
113172  ** back and different changes are made in their place, then when this
113173  ** prepared statement goes to run the schema cookie would fail to detect
113174  ** the schema change.  Disaster would follow.
113175  **
113176  ** This thread is currently holding mutexes on all Btrees (because
113177  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
113178  ** is not possible for another thread to start a new schema change
113179  ** while this routine is running.  Hence, we do not need to hold
113180  ** locks on the schema, we just need to make sure nobody else is
113181  ** holding them.
113182  **
113183  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
113184  ** but it does *not* override schema lock detection, so this all still
113185  ** works even if READ_UNCOMMITTED is set.
113186  */
113187  for(i=0; i<db->nDb; i++) {
113188    Btree *pBt = db->aDb[i].pBt;
113189    if( pBt ){
113190      assert( sqlite3BtreeHoldsMutex(pBt) );
113191      rc = sqlite3BtreeSchemaLocked(pBt);
113192      if( rc ){
113193        const char *zDb = db->aDb[i].zName;
113194        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
113195        testcase( db->flags & SQLITE_ReadUncommitted );
113196        goto end_prepare;
113197      }
113198    }
113199  }
113200
113201  sqlite3VtabUnlockList(db);
113202
113203  pParse->db = db;
113204  pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
113205  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
113206    char *zSqlCopy;
113207    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
113208    testcase( nBytes==mxLen );
113209    testcase( nBytes==mxLen+1 );
113210    if( nBytes>mxLen ){
113211      sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
113212      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
113213      goto end_prepare;
113214    }
113215    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
113216    if( zSqlCopy ){
113217      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
113218      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
113219      sqlite3DbFree(db, zSqlCopy);
113220    }else{
113221      pParse->zTail = &zSql[nBytes];
113222    }
113223  }else{
113224    sqlite3RunParser(pParse, zSql, &zErrMsg);
113225  }
113226  assert( 0==pParse->nQueryLoop );
113227
113228  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
113229  if( pParse->checkSchema ){
113230    schemaIsValid(pParse);
113231  }
113232  if( db->mallocFailed ){
113233    pParse->rc = SQLITE_NOMEM_BKPT;
113234  }
113235  if( pzTail ){
113236    *pzTail = pParse->zTail;
113237  }
113238  rc = pParse->rc;
113239
113240#ifndef SQLITE_OMIT_EXPLAIN
113241  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
113242    static const char * const azColName[] = {
113243       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
113244       "selectid", "order", "from", "detail"
113245    };
113246    int iFirst, mx;
113247    if( pParse->explain==2 ){
113248      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
113249      iFirst = 8;
113250      mx = 12;
113251    }else{
113252      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
113253      iFirst = 0;
113254      mx = 8;
113255    }
113256    for(i=iFirst; i<mx; i++){
113257      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
113258                            azColName[i], SQLITE_STATIC);
113259    }
113260  }
113261#endif
113262
113263  if( db->init.busy==0 ){
113264    Vdbe *pVdbe = pParse->pVdbe;
113265    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
113266  }
113267  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
113268    sqlite3VdbeFinalize(pParse->pVdbe);
113269    assert(!(*ppStmt));
113270  }else{
113271    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
113272  }
113273
113274  if( zErrMsg ){
113275    sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
113276    sqlite3DbFree(db, zErrMsg);
113277  }else{
113278    sqlite3Error(db, rc);
113279  }
113280
113281  /* Delete any TriggerPrg structures allocated while parsing this statement. */
113282  while( pParse->pTriggerPrg ){
113283    TriggerPrg *pT = pParse->pTriggerPrg;
113284    pParse->pTriggerPrg = pT->pNext;
113285    sqlite3DbFree(db, pT);
113286  }
113287
113288end_prepare:
113289
113290  sqlite3ParserReset(pParse);
113291  sqlite3StackFree(db, pParse);
113292  rc = sqlite3ApiExit(db, rc);
113293  assert( (rc&db->errMask)==rc );
113294  return rc;
113295}
113296static int sqlite3LockAndPrepare(
113297  sqlite3 *db,              /* Database handle. */
113298  const char *zSql,         /* UTF-8 encoded SQL statement. */
113299  int nBytes,               /* Length of zSql in bytes. */
113300  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
113301  Vdbe *pOld,               /* VM being reprepared */
113302  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113303  const char **pzTail       /* OUT: End of parsed string */
113304){
113305  int rc;
113306
113307#ifdef SQLITE_ENABLE_API_ARMOR
113308  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
113309#endif
113310  *ppStmt = 0;
113311  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
113312    return SQLITE_MISUSE_BKPT;
113313  }
113314  sqlite3_mutex_enter(db->mutex);
113315  sqlite3BtreeEnterAll(db);
113316  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
113317  if( rc==SQLITE_SCHEMA ){
113318    sqlite3_finalize(*ppStmt);
113319    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
113320  }
113321  sqlite3BtreeLeaveAll(db);
113322  sqlite3_mutex_leave(db->mutex);
113323  assert( rc==SQLITE_OK || *ppStmt==0 );
113324  return rc;
113325}
113326
113327/*
113328** Rerun the compilation of a statement after a schema change.
113329**
113330** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
113331** if the statement cannot be recompiled because another connection has
113332** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
113333** occurs, return SQLITE_SCHEMA.
113334*/
113335SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
113336  int rc;
113337  sqlite3_stmt *pNew;
113338  const char *zSql;
113339  sqlite3 *db;
113340
113341  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
113342  zSql = sqlite3_sql((sqlite3_stmt *)p);
113343  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
113344  db = sqlite3VdbeDb(p);
113345  assert( sqlite3_mutex_held(db->mutex) );
113346  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
113347  if( rc ){
113348    if( rc==SQLITE_NOMEM ){
113349      sqlite3OomFault(db);
113350    }
113351    assert( pNew==0 );
113352    return rc;
113353  }else{
113354    assert( pNew!=0 );
113355  }
113356  sqlite3VdbeSwap((Vdbe*)pNew, p);
113357  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
113358  sqlite3VdbeResetStepResult((Vdbe*)pNew);
113359  sqlite3VdbeFinalize((Vdbe*)pNew);
113360  return SQLITE_OK;
113361}
113362
113363
113364/*
113365** Two versions of the official API.  Legacy and new use.  In the legacy
113366** version, the original SQL text is not saved in the prepared statement
113367** and so if a schema change occurs, SQLITE_SCHEMA is returned by
113368** sqlite3_step().  In the new version, the original SQL text is retained
113369** and the statement is automatically recompiled if an schema change
113370** occurs.
113371*/
113372SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
113373  sqlite3 *db,              /* Database handle. */
113374  const char *zSql,         /* UTF-8 encoded SQL statement. */
113375  int nBytes,               /* Length of zSql in bytes. */
113376  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113377  const char **pzTail       /* OUT: End of parsed string */
113378){
113379  int rc;
113380  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
113381  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113382  return rc;
113383}
113384SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
113385  sqlite3 *db,              /* Database handle. */
113386  const char *zSql,         /* UTF-8 encoded SQL statement. */
113387  int nBytes,               /* Length of zSql in bytes. */
113388  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113389  const char **pzTail       /* OUT: End of parsed string */
113390){
113391  int rc;
113392  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
113393  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113394  return rc;
113395}
113396
113397
113398#ifndef SQLITE_OMIT_UTF16
113399/*
113400** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
113401*/
113402static int sqlite3Prepare16(
113403  sqlite3 *db,              /* Database handle. */
113404  const void *zSql,         /* UTF-16 encoded SQL statement. */
113405  int nBytes,               /* Length of zSql in bytes. */
113406  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
113407  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113408  const void **pzTail       /* OUT: End of parsed string */
113409){
113410  /* This function currently works by first transforming the UTF-16
113411  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
113412  ** tricky bit is figuring out the pointer to return in *pzTail.
113413  */
113414  char *zSql8;
113415  const char *zTail8 = 0;
113416  int rc = SQLITE_OK;
113417
113418#ifdef SQLITE_ENABLE_API_ARMOR
113419  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
113420#endif
113421  *ppStmt = 0;
113422  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
113423    return SQLITE_MISUSE_BKPT;
113424  }
113425  if( nBytes>=0 ){
113426    int sz;
113427    const char *z = (const char*)zSql;
113428    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
113429    nBytes = sz;
113430  }
113431  sqlite3_mutex_enter(db->mutex);
113432  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
113433  if( zSql8 ){
113434    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
113435  }
113436
113437  if( zTail8 && pzTail ){
113438    /* If sqlite3_prepare returns a tail pointer, we calculate the
113439    ** equivalent pointer into the UTF-16 string by counting the unicode
113440    ** characters between zSql8 and zTail8, and then returning a pointer
113441    ** the same number of characters into the UTF-16 string.
113442    */
113443    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
113444    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
113445  }
113446  sqlite3DbFree(db, zSql8);
113447  rc = sqlite3ApiExit(db, rc);
113448  sqlite3_mutex_leave(db->mutex);
113449  return rc;
113450}
113451
113452/*
113453** Two versions of the official API.  Legacy and new use.  In the legacy
113454** version, the original SQL text is not saved in the prepared statement
113455** and so if a schema change occurs, SQLITE_SCHEMA is returned by
113456** sqlite3_step().  In the new version, the original SQL text is retained
113457** and the statement is automatically recompiled if an schema change
113458** occurs.
113459*/
113460SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
113461  sqlite3 *db,              /* Database handle. */
113462  const void *zSql,         /* UTF-16 encoded SQL statement. */
113463  int nBytes,               /* Length of zSql in bytes. */
113464  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113465  const void **pzTail       /* OUT: End of parsed string */
113466){
113467  int rc;
113468  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
113469  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113470  return rc;
113471}
113472SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
113473  sqlite3 *db,              /* Database handle. */
113474  const void *zSql,         /* UTF-16 encoded SQL statement. */
113475  int nBytes,               /* Length of zSql in bytes. */
113476  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113477  const void **pzTail       /* OUT: End of parsed string */
113478){
113479  int rc;
113480  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
113481  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113482  return rc;
113483}
113484
113485#endif /* SQLITE_OMIT_UTF16 */
113486
113487/************** End of prepare.c *********************************************/
113488/************** Begin file select.c ******************************************/
113489/*
113490** 2001 September 15
113491**
113492** The author disclaims copyright to this source code.  In place of
113493** a legal notice, here is a blessing:
113494**
113495**    May you do good and not evil.
113496**    May you find forgiveness for yourself and forgive others.
113497**    May you share freely, never taking more than you give.
113498**
113499*************************************************************************
113500** This file contains C code routines that are called by the parser
113501** to handle SELECT statements in SQLite.
113502*/
113503/* #include "sqliteInt.h" */
113504
113505/*
113506** Trace output macros
113507*/
113508#if SELECTTRACE_ENABLED
113509/***/ int sqlite3SelectTrace = 0;
113510# define SELECTTRACE(K,P,S,X)  \
113511  if(sqlite3SelectTrace&(K))   \
113512    sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
113513        (S)->zSelName,(S)),\
113514    sqlite3DebugPrintf X
113515#else
113516# define SELECTTRACE(K,P,S,X)
113517#endif
113518
113519
113520/*
113521** An instance of the following object is used to record information about
113522** how to process the DISTINCT keyword, to simplify passing that information
113523** into the selectInnerLoop() routine.
113524*/
113525typedef struct DistinctCtx DistinctCtx;
113526struct DistinctCtx {
113527  u8 isTnct;      /* True if the DISTINCT keyword is present */
113528  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
113529  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
113530  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
113531};
113532
113533/*
113534** An instance of the following object is used to record information about
113535** the ORDER BY (or GROUP BY) clause of query is being coded.
113536*/
113537typedef struct SortCtx SortCtx;
113538struct SortCtx {
113539  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
113540  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
113541  int iECursor;         /* Cursor number for the sorter */
113542  int regReturn;        /* Register holding block-output return address */
113543  int labelBkOut;       /* Start label for the block-output subroutine */
113544  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
113545  int labelDone;        /* Jump here when done, ex: LIMIT reached */
113546  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
113547  u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
113548};
113549#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
113550
113551/*
113552** Delete all the content of a Select structure.  Deallocate the structure
113553** itself only if bFree is true.
113554*/
113555static void clearSelect(sqlite3 *db, Select *p, int bFree){
113556  while( p ){
113557    Select *pPrior = p->pPrior;
113558    sqlite3ExprListDelete(db, p->pEList);
113559    sqlite3SrcListDelete(db, p->pSrc);
113560    sqlite3ExprDelete(db, p->pWhere);
113561    sqlite3ExprListDelete(db, p->pGroupBy);
113562    sqlite3ExprDelete(db, p->pHaving);
113563    sqlite3ExprListDelete(db, p->pOrderBy);
113564    sqlite3ExprDelete(db, p->pLimit);
113565    sqlite3ExprDelete(db, p->pOffset);
113566    if( p->pWith ) sqlite3WithDelete(db, p->pWith);
113567    if( bFree ) sqlite3DbFree(db, p);
113568    p = pPrior;
113569    bFree = 1;
113570  }
113571}
113572
113573/*
113574** Initialize a SelectDest structure.
113575*/
113576SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
113577  pDest->eDest = (u8)eDest;
113578  pDest->iSDParm = iParm;
113579  pDest->affSdst = 0;
113580  pDest->iSdst = 0;
113581  pDest->nSdst = 0;
113582}
113583
113584
113585/*
113586** Allocate a new Select structure and return a pointer to that
113587** structure.
113588*/
113589SQLITE_PRIVATE Select *sqlite3SelectNew(
113590  Parse *pParse,        /* Parsing context */
113591  ExprList *pEList,     /* which columns to include in the result */
113592  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
113593  Expr *pWhere,         /* the WHERE clause */
113594  ExprList *pGroupBy,   /* the GROUP BY clause */
113595  Expr *pHaving,        /* the HAVING clause */
113596  ExprList *pOrderBy,   /* the ORDER BY clause */
113597  u32 selFlags,         /* Flag parameters, such as SF_Distinct */
113598  Expr *pLimit,         /* LIMIT value.  NULL means not used */
113599  Expr *pOffset         /* OFFSET value.  NULL means no offset */
113600){
113601  Select *pNew;
113602  Select standin;
113603  sqlite3 *db = pParse->db;
113604  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
113605  if( pNew==0 ){
113606    assert( db->mallocFailed );
113607    pNew = &standin;
113608  }
113609  if( pEList==0 ){
113610    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
113611  }
113612  pNew->pEList = pEList;
113613  pNew->op = TK_SELECT;
113614  pNew->selFlags = selFlags;
113615  pNew->iLimit = 0;
113616  pNew->iOffset = 0;
113617#if SELECTTRACE_ENABLED
113618  pNew->zSelName[0] = 0;
113619#endif
113620  pNew->addrOpenEphm[0] = -1;
113621  pNew->addrOpenEphm[1] = -1;
113622  pNew->nSelectRow = 0;
113623  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
113624  pNew->pSrc = pSrc;
113625  pNew->pWhere = pWhere;
113626  pNew->pGroupBy = pGroupBy;
113627  pNew->pHaving = pHaving;
113628  pNew->pOrderBy = pOrderBy;
113629  pNew->pPrior = 0;
113630  pNew->pNext = 0;
113631  pNew->pLimit = pLimit;
113632  pNew->pOffset = pOffset;
113633  pNew->pWith = 0;
113634  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
113635  if( db->mallocFailed ) {
113636    clearSelect(db, pNew, pNew!=&standin);
113637    pNew = 0;
113638  }else{
113639    assert( pNew->pSrc!=0 || pParse->nErr>0 );
113640  }
113641  assert( pNew!=&standin );
113642  return pNew;
113643}
113644
113645#if SELECTTRACE_ENABLED
113646/*
113647** Set the name of a Select object
113648*/
113649SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
113650  if( p && zName ){
113651    sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
113652  }
113653}
113654#endif
113655
113656
113657/*
113658** Delete the given Select structure and all of its substructures.
113659*/
113660SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
113661  if( p ) clearSelect(db, p, 1);
113662}
113663
113664/*
113665** Return a pointer to the right-most SELECT statement in a compound.
113666*/
113667static Select *findRightmost(Select *p){
113668  while( p->pNext ) p = p->pNext;
113669  return p;
113670}
113671
113672/*
113673** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
113674** type of join.  Return an integer constant that expresses that type
113675** in terms of the following bit values:
113676**
113677**     JT_INNER
113678**     JT_CROSS
113679**     JT_OUTER
113680**     JT_NATURAL
113681**     JT_LEFT
113682**     JT_RIGHT
113683**
113684** A full outer join is the combination of JT_LEFT and JT_RIGHT.
113685**
113686** If an illegal or unsupported join type is seen, then still return
113687** a join type, but put an error in the pParse structure.
113688*/
113689SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
113690  int jointype = 0;
113691  Token *apAll[3];
113692  Token *p;
113693                             /*   0123456789 123456789 123456789 123 */
113694  static const char zKeyText[] = "naturaleftouterightfullinnercross";
113695  static const struct {
113696    u8 i;        /* Beginning of keyword text in zKeyText[] */
113697    u8 nChar;    /* Length of the keyword in characters */
113698    u8 code;     /* Join type mask */
113699  } aKeyword[] = {
113700    /* natural */ { 0,  7, JT_NATURAL                },
113701    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
113702    /* outer   */ { 10, 5, JT_OUTER                  },
113703    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
113704    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
113705    /* inner   */ { 23, 5, JT_INNER                  },
113706    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
113707  };
113708  int i, j;
113709  apAll[0] = pA;
113710  apAll[1] = pB;
113711  apAll[2] = pC;
113712  for(i=0; i<3 && apAll[i]; i++){
113713    p = apAll[i];
113714    for(j=0; j<ArraySize(aKeyword); j++){
113715      if( p->n==aKeyword[j].nChar
113716          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
113717        jointype |= aKeyword[j].code;
113718        break;
113719      }
113720    }
113721    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
113722    if( j>=ArraySize(aKeyword) ){
113723      jointype |= JT_ERROR;
113724      break;
113725    }
113726  }
113727  if(
113728     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
113729     (jointype & JT_ERROR)!=0
113730  ){
113731    const char *zSp = " ";
113732    assert( pB!=0 );
113733    if( pC==0 ){ zSp++; }
113734    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
113735       "%T %T%s%T", pA, pB, zSp, pC);
113736    jointype = JT_INNER;
113737  }else if( (jointype & JT_OUTER)!=0
113738         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
113739    sqlite3ErrorMsg(pParse,
113740      "RIGHT and FULL OUTER JOINs are not currently supported");
113741    jointype = JT_INNER;
113742  }
113743  return jointype;
113744}
113745
113746/*
113747** Return the index of a column in a table.  Return -1 if the column
113748** is not contained in the table.
113749*/
113750static int columnIndex(Table *pTab, const char *zCol){
113751  int i;
113752  for(i=0; i<pTab->nCol; i++){
113753    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
113754  }
113755  return -1;
113756}
113757
113758/*
113759** Search the first N tables in pSrc, from left to right, looking for a
113760** table that has a column named zCol.
113761**
113762** When found, set *piTab and *piCol to the table index and column index
113763** of the matching column and return TRUE.
113764**
113765** If not found, return FALSE.
113766*/
113767static int tableAndColumnIndex(
113768  SrcList *pSrc,       /* Array of tables to search */
113769  int N,               /* Number of tables in pSrc->a[] to search */
113770  const char *zCol,    /* Name of the column we are looking for */
113771  int *piTab,          /* Write index of pSrc->a[] here */
113772  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
113773){
113774  int i;               /* For looping over tables in pSrc */
113775  int iCol;            /* Index of column matching zCol */
113776
113777  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
113778  for(i=0; i<N; i++){
113779    iCol = columnIndex(pSrc->a[i].pTab, zCol);
113780    if( iCol>=0 ){
113781      if( piTab ){
113782        *piTab = i;
113783        *piCol = iCol;
113784      }
113785      return 1;
113786    }
113787  }
113788  return 0;
113789}
113790
113791/*
113792** This function is used to add terms implied by JOIN syntax to the
113793** WHERE clause expression of a SELECT statement. The new term, which
113794** is ANDed with the existing WHERE clause, is of the form:
113795**
113796**    (tab1.col1 = tab2.col2)
113797**
113798** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
113799** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
113800** column iColRight of tab2.
113801*/
113802static void addWhereTerm(
113803  Parse *pParse,                  /* Parsing context */
113804  SrcList *pSrc,                  /* List of tables in FROM clause */
113805  int iLeft,                      /* Index of first table to join in pSrc */
113806  int iColLeft,                   /* Index of column in first table */
113807  int iRight,                     /* Index of second table in pSrc */
113808  int iColRight,                  /* Index of column in second table */
113809  int isOuterJoin,                /* True if this is an OUTER join */
113810  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
113811){
113812  sqlite3 *db = pParse->db;
113813  Expr *pE1;
113814  Expr *pE2;
113815  Expr *pEq;
113816
113817  assert( iLeft<iRight );
113818  assert( pSrc->nSrc>iRight );
113819  assert( pSrc->a[iLeft].pTab );
113820  assert( pSrc->a[iRight].pTab );
113821
113822  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
113823  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
113824
113825  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
113826  if( pEq && isOuterJoin ){
113827    ExprSetProperty(pEq, EP_FromJoin);
113828    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
113829    ExprSetVVAProperty(pEq, EP_NoReduce);
113830    pEq->iRightJoinTable = (i16)pE2->iTable;
113831  }
113832  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
113833}
113834
113835/*
113836** Set the EP_FromJoin property on all terms of the given expression.
113837** And set the Expr.iRightJoinTable to iTable for every term in the
113838** expression.
113839**
113840** The EP_FromJoin property is used on terms of an expression to tell
113841** the LEFT OUTER JOIN processing logic that this term is part of the
113842** join restriction specified in the ON or USING clause and not a part
113843** of the more general WHERE clause.  These terms are moved over to the
113844** WHERE clause during join processing but we need to remember that they
113845** originated in the ON or USING clause.
113846**
113847** The Expr.iRightJoinTable tells the WHERE clause processing that the
113848** expression depends on table iRightJoinTable even if that table is not
113849** explicitly mentioned in the expression.  That information is needed
113850** for cases like this:
113851**
113852**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
113853**
113854** The where clause needs to defer the handling of the t1.x=5
113855** term until after the t2 loop of the join.  In that way, a
113856** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
113857** defer the handling of t1.x=5, it will be processed immediately
113858** after the t1 loop and rows with t1.x!=5 will never appear in
113859** the output, which is incorrect.
113860*/
113861static void setJoinExpr(Expr *p, int iTable){
113862  while( p ){
113863    ExprSetProperty(p, EP_FromJoin);
113864    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
113865    ExprSetVVAProperty(p, EP_NoReduce);
113866    p->iRightJoinTable = (i16)iTable;
113867    if( p->op==TK_FUNCTION && p->x.pList ){
113868      int i;
113869      for(i=0; i<p->x.pList->nExpr; i++){
113870        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
113871      }
113872    }
113873    setJoinExpr(p->pLeft, iTable);
113874    p = p->pRight;
113875  }
113876}
113877
113878/*
113879** This routine processes the join information for a SELECT statement.
113880** ON and USING clauses are converted into extra terms of the WHERE clause.
113881** NATURAL joins also create extra WHERE clause terms.
113882**
113883** The terms of a FROM clause are contained in the Select.pSrc structure.
113884** The left most table is the first entry in Select.pSrc.  The right-most
113885** table is the last entry.  The join operator is held in the entry to
113886** the left.  Thus entry 0 contains the join operator for the join between
113887** entries 0 and 1.  Any ON or USING clauses associated with the join are
113888** also attached to the left entry.
113889**
113890** This routine returns the number of errors encountered.
113891*/
113892static int sqliteProcessJoin(Parse *pParse, Select *p){
113893  SrcList *pSrc;                  /* All tables in the FROM clause */
113894  int i, j;                       /* Loop counters */
113895  struct SrcList_item *pLeft;     /* Left table being joined */
113896  struct SrcList_item *pRight;    /* Right table being joined */
113897
113898  pSrc = p->pSrc;
113899  pLeft = &pSrc->a[0];
113900  pRight = &pLeft[1];
113901  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
113902    Table *pLeftTab = pLeft->pTab;
113903    Table *pRightTab = pRight->pTab;
113904    int isOuter;
113905
113906    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
113907    isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
113908
113909    /* When the NATURAL keyword is present, add WHERE clause terms for
113910    ** every column that the two tables have in common.
113911    */
113912    if( pRight->fg.jointype & JT_NATURAL ){
113913      if( pRight->pOn || pRight->pUsing ){
113914        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
113915           "an ON or USING clause", 0);
113916        return 1;
113917      }
113918      for(j=0; j<pRightTab->nCol; j++){
113919        char *zName;   /* Name of column in the right table */
113920        int iLeft;     /* Matching left table */
113921        int iLeftCol;  /* Matching column in the left table */
113922
113923        zName = pRightTab->aCol[j].zName;
113924        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
113925          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
113926                       isOuter, &p->pWhere);
113927        }
113928      }
113929    }
113930
113931    /* Disallow both ON and USING clauses in the same join
113932    */
113933    if( pRight->pOn && pRight->pUsing ){
113934      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
113935        "clauses in the same join");
113936      return 1;
113937    }
113938
113939    /* Add the ON clause to the end of the WHERE clause, connected by
113940    ** an AND operator.
113941    */
113942    if( pRight->pOn ){
113943      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
113944      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
113945      pRight->pOn = 0;
113946    }
113947
113948    /* Create extra terms on the WHERE clause for each column named
113949    ** in the USING clause.  Example: If the two tables to be joined are
113950    ** A and B and the USING clause names X, Y, and Z, then add this
113951    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
113952    ** Report an error if any column mentioned in the USING clause is
113953    ** not contained in both tables to be joined.
113954    */
113955    if( pRight->pUsing ){
113956      IdList *pList = pRight->pUsing;
113957      for(j=0; j<pList->nId; j++){
113958        char *zName;     /* Name of the term in the USING clause */
113959        int iLeft;       /* Table on the left with matching column name */
113960        int iLeftCol;    /* Column number of matching column on the left */
113961        int iRightCol;   /* Column number of matching column on the right */
113962
113963        zName = pList->a[j].zName;
113964        iRightCol = columnIndex(pRightTab, zName);
113965        if( iRightCol<0
113966         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
113967        ){
113968          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
113969            "not present in both tables", zName);
113970          return 1;
113971        }
113972        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
113973                     isOuter, &p->pWhere);
113974      }
113975    }
113976  }
113977  return 0;
113978}
113979
113980/* Forward reference */
113981static KeyInfo *keyInfoFromExprList(
113982  Parse *pParse,       /* Parsing context */
113983  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
113984  int iStart,          /* Begin with this column of pList */
113985  int nExtra           /* Add this many extra columns to the end */
113986);
113987
113988/*
113989** Generate code that will push the record in registers regData
113990** through regData+nData-1 onto the sorter.
113991*/
113992static void pushOntoSorter(
113993  Parse *pParse,         /* Parser context */
113994  SortCtx *pSort,        /* Information about the ORDER BY clause */
113995  Select *pSelect,       /* The whole SELECT statement */
113996  int regData,           /* First register holding data to be sorted */
113997  int regOrigData,       /* First register holding data before packing */
113998  int nData,             /* Number of elements in the data array */
113999  int nPrefixReg         /* No. of reg prior to regData available for use */
114000){
114001  Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
114002  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
114003  int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
114004  int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
114005  int regBase;                                     /* Regs for sorter record */
114006  int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
114007  int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
114008  int op;                            /* Opcode to add sorter record to sorter */
114009  int iLimit;                        /* LIMIT counter */
114010
114011  assert( bSeq==0 || bSeq==1 );
114012  assert( nData==1 || regData==regOrigData );
114013  if( nPrefixReg ){
114014    assert( nPrefixReg==nExpr+bSeq );
114015    regBase = regData - nExpr - bSeq;
114016  }else{
114017    regBase = pParse->nMem + 1;
114018    pParse->nMem += nBase;
114019  }
114020  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
114021  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
114022  pSort->labelDone = sqlite3VdbeMakeLabel(v);
114023  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
114024                          SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
114025  if( bSeq ){
114026    sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
114027  }
114028  if( nPrefixReg==0 ){
114029    sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
114030  }
114031  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
114032  if( nOBSat>0 ){
114033    int regPrevKey;   /* The first nOBSat columns of the previous row */
114034    int addrFirst;    /* Address of the OP_IfNot opcode */
114035    int addrJmp;      /* Address of the OP_Jump opcode */
114036    VdbeOp *pOp;      /* Opcode that opens the sorter */
114037    int nKey;         /* Number of sorting key columns, including OP_Sequence */
114038    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
114039
114040    regPrevKey = pParse->nMem+1;
114041    pParse->nMem += pSort->nOBSat;
114042    nKey = nExpr - pSort->nOBSat + bSeq;
114043    if( bSeq ){
114044      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
114045    }else{
114046      addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
114047    }
114048    VdbeCoverage(v);
114049    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
114050    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
114051    if( pParse->db->mallocFailed ) return;
114052    pOp->p2 = nKey + nData;
114053    pKI = pOp->p4.pKeyInfo;
114054    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
114055    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
114056    testcase( pKI->nXField>2 );
114057    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
114058                                           pKI->nXField-1);
114059    addrJmp = sqlite3VdbeCurrentAddr(v);
114060    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
114061    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
114062    pSort->regReturn = ++pParse->nMem;
114063    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114064    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
114065    if( iLimit ){
114066      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
114067      VdbeCoverage(v);
114068    }
114069    sqlite3VdbeJumpHere(v, addrFirst);
114070    sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
114071    sqlite3VdbeJumpHere(v, addrJmp);
114072  }
114073  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114074    op = OP_SorterInsert;
114075  }else{
114076    op = OP_IdxInsert;
114077  }
114078  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
114079  if( iLimit ){
114080    int addr;
114081    int r1 = 0;
114082    /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
114083    ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
114084    ** fills up, delete the least entry in the sorter after each insert.
114085    ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
114086    addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
114087    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
114088    if( pSort->bOrderedInnerLoop ){
114089      r1 = ++pParse->nMem;
114090      sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
114091      VdbeComment((v, "seq"));
114092    }
114093    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
114094    if( pSort->bOrderedInnerLoop ){
114095      /* If the inner loop is driven by an index such that values from
114096      ** the same iteration of the inner loop are in sorted order, then
114097      ** immediately jump to the next iteration of an inner loop if the
114098      ** entry from the current iteration does not fit into the top
114099      ** LIMIT+OFFSET entries of the sorter. */
114100      int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
114101      sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
114102      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
114103      VdbeCoverage(v);
114104    }
114105    sqlite3VdbeJumpHere(v, addr);
114106  }
114107}
114108
114109/*
114110** Add code to implement the OFFSET
114111*/
114112static void codeOffset(
114113  Vdbe *v,          /* Generate code into this VM */
114114  int iOffset,      /* Register holding the offset counter */
114115  int iContinue     /* Jump here to skip the current record */
114116){
114117  if( iOffset>0 ){
114118    sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
114119    VdbeComment((v, "OFFSET"));
114120  }
114121}
114122
114123/*
114124** Add code that will check to make sure the N registers starting at iMem
114125** form a distinct entry.  iTab is a sorting index that holds previously
114126** seen combinations of the N values.  A new entry is made in iTab
114127** if the current N values are new.
114128**
114129** A jump to addrRepeat is made and the N+1 values are popped from the
114130** stack if the top N elements are not distinct.
114131*/
114132static void codeDistinct(
114133  Parse *pParse,     /* Parsing and code generating context */
114134  int iTab,          /* A sorting index used to test for distinctness */
114135  int addrRepeat,    /* Jump to here if not distinct */
114136  int N,             /* Number of elements */
114137  int iMem           /* First element */
114138){
114139  Vdbe *v;
114140  int r1;
114141
114142  v = pParse->pVdbe;
114143  r1 = sqlite3GetTempReg(pParse);
114144  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
114145  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
114146  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
114147  sqlite3ReleaseTempReg(pParse, r1);
114148}
114149
114150#ifndef SQLITE_OMIT_SUBQUERY
114151/*
114152** Generate an error message when a SELECT is used within a subexpression
114153** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
114154** column.  We do this in a subroutine because the error used to occur
114155** in multiple places.  (The error only occurs in one place now, but we
114156** retain the subroutine to minimize code disruption.)
114157*/
114158static int checkForMultiColumnSelectError(
114159  Parse *pParse,       /* Parse context. */
114160  SelectDest *pDest,   /* Destination of SELECT results */
114161  int nExpr            /* Number of result columns returned by SELECT */
114162){
114163  int eDest = pDest->eDest;
114164  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
114165    sqlite3ErrorMsg(pParse, "only a single result allowed for "
114166       "a SELECT that is part of an expression");
114167    return 1;
114168  }else{
114169    return 0;
114170  }
114171}
114172#endif
114173
114174/*
114175** This routine generates the code for the inside of the inner loop
114176** of a SELECT.
114177**
114178** If srcTab is negative, then the pEList expressions
114179** are evaluated in order to get the data for this row.  If srcTab is
114180** zero or more, then data is pulled from srcTab and pEList is used only
114181** to get number columns and the datatype for each column.
114182*/
114183static void selectInnerLoop(
114184  Parse *pParse,          /* The parser context */
114185  Select *p,              /* The complete select statement being coded */
114186  ExprList *pEList,       /* List of values being extracted */
114187  int srcTab,             /* Pull data from this table */
114188  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
114189  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
114190  SelectDest *pDest,      /* How to dispose of the results */
114191  int iContinue,          /* Jump here to continue with next row */
114192  int iBreak              /* Jump here to break out of the inner loop */
114193){
114194  Vdbe *v = pParse->pVdbe;
114195  int i;
114196  int hasDistinct;        /* True if the DISTINCT keyword is present */
114197  int regResult;              /* Start of memory holding result set */
114198  int eDest = pDest->eDest;   /* How to dispose of results */
114199  int iParm = pDest->iSDParm; /* First argument to disposal method */
114200  int nResultCol;             /* Number of result columns */
114201  int nPrefixReg = 0;         /* Number of extra registers before regResult */
114202
114203  assert( v );
114204  assert( pEList!=0 );
114205  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
114206  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
114207  if( pSort==0 && !hasDistinct ){
114208    assert( iContinue!=0 );
114209    codeOffset(v, p->iOffset, iContinue);
114210  }
114211
114212  /* Pull the requested columns.
114213  */
114214  nResultCol = pEList->nExpr;
114215
114216  if( pDest->iSdst==0 ){
114217    if( pSort ){
114218      nPrefixReg = pSort->pOrderBy->nExpr;
114219      if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
114220      pParse->nMem += nPrefixReg;
114221    }
114222    pDest->iSdst = pParse->nMem+1;
114223    pParse->nMem += nResultCol;
114224  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
114225    /* This is an error condition that can result, for example, when a SELECT
114226    ** on the right-hand side of an INSERT contains more result columns than
114227    ** there are columns in the table on the left.  The error will be caught
114228    ** and reported later.  But we need to make sure enough memory is allocated
114229    ** to avoid other spurious errors in the meantime. */
114230    pParse->nMem += nResultCol;
114231  }
114232  pDest->nSdst = nResultCol;
114233  regResult = pDest->iSdst;
114234  if( srcTab>=0 ){
114235    for(i=0; i<nResultCol; i++){
114236      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
114237      VdbeComment((v, "%s", pEList->a[i].zName));
114238    }
114239  }else if( eDest!=SRT_Exists ){
114240    /* If the destination is an EXISTS(...) expression, the actual
114241    ** values returned by the SELECT are not required.
114242    */
114243    u8 ecelFlags;
114244    if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
114245      ecelFlags = SQLITE_ECEL_DUP;
114246    }else{
114247      ecelFlags = 0;
114248    }
114249    sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
114250  }
114251
114252  /* If the DISTINCT keyword was present on the SELECT statement
114253  ** and this row has been seen before, then do not make this row
114254  ** part of the result.
114255  */
114256  if( hasDistinct ){
114257    switch( pDistinct->eTnctType ){
114258      case WHERE_DISTINCT_ORDERED: {
114259        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
114260        int iJump;              /* Jump destination */
114261        int regPrev;            /* Previous row content */
114262
114263        /* Allocate space for the previous row */
114264        regPrev = pParse->nMem+1;
114265        pParse->nMem += nResultCol;
114266
114267        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
114268        ** sets the MEM_Cleared bit on the first register of the
114269        ** previous value.  This will cause the OP_Ne below to always
114270        ** fail on the first iteration of the loop even if the first
114271        ** row is all NULLs.
114272        */
114273        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
114274        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
114275        pOp->opcode = OP_Null;
114276        pOp->p1 = 1;
114277        pOp->p2 = regPrev;
114278
114279        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
114280        for(i=0; i<nResultCol; i++){
114281          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
114282          if( i<nResultCol-1 ){
114283            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
114284            VdbeCoverage(v);
114285          }else{
114286            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
114287            VdbeCoverage(v);
114288           }
114289          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
114290          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
114291        }
114292        assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
114293        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
114294        break;
114295      }
114296
114297      case WHERE_DISTINCT_UNIQUE: {
114298        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
114299        break;
114300      }
114301
114302      default: {
114303        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
114304        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
114305                     regResult);
114306        break;
114307      }
114308    }
114309    if( pSort==0 ){
114310      codeOffset(v, p->iOffset, iContinue);
114311    }
114312  }
114313
114314  switch( eDest ){
114315    /* In this mode, write each query result to the key of the temporary
114316    ** table iParm.
114317    */
114318#ifndef SQLITE_OMIT_COMPOUND_SELECT
114319    case SRT_Union: {
114320      int r1;
114321      r1 = sqlite3GetTempReg(pParse);
114322      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
114323      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114324      sqlite3ReleaseTempReg(pParse, r1);
114325      break;
114326    }
114327
114328    /* Construct a record from the query result, but instead of
114329    ** saving that record, use it as a key to delete elements from
114330    ** the temporary table iParm.
114331    */
114332    case SRT_Except: {
114333      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
114334      break;
114335    }
114336#endif /* SQLITE_OMIT_COMPOUND_SELECT */
114337
114338    /* Store the result as data using a unique key.
114339    */
114340    case SRT_Fifo:
114341    case SRT_DistFifo:
114342    case SRT_Table:
114343    case SRT_EphemTab: {
114344      int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
114345      testcase( eDest==SRT_Table );
114346      testcase( eDest==SRT_EphemTab );
114347      testcase( eDest==SRT_Fifo );
114348      testcase( eDest==SRT_DistFifo );
114349      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
114350#ifndef SQLITE_OMIT_CTE
114351      if( eDest==SRT_DistFifo ){
114352        /* If the destination is DistFifo, then cursor (iParm+1) is open
114353        ** on an ephemeral index. If the current row is already present
114354        ** in the index, do not write it to the output. If not, add the
114355        ** current row to the index and proceed with writing it to the
114356        ** output table as well.  */
114357        int addr = sqlite3VdbeCurrentAddr(v) + 4;
114358        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
114359        VdbeCoverage(v);
114360        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
114361        assert( pSort==0 );
114362      }
114363#endif
114364      if( pSort ){
114365        pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
114366      }else{
114367        int r2 = sqlite3GetTempReg(pParse);
114368        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
114369        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
114370        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
114371        sqlite3ReleaseTempReg(pParse, r2);
114372      }
114373      sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
114374      break;
114375    }
114376
114377#ifndef SQLITE_OMIT_SUBQUERY
114378    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
114379    ** then there should be a single item on the stack.  Write this
114380    ** item into the set table with bogus data.
114381    */
114382    case SRT_Set: {
114383      assert( nResultCol==1 );
114384      pDest->affSdst =
114385                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
114386      if( pSort ){
114387        /* At first glance you would think we could optimize out the
114388        ** ORDER BY in this case since the order of entries in the set
114389        ** does not matter.  But there might be a LIMIT clause, in which
114390        ** case the order does matter */
114391        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
114392      }else{
114393        int r1 = sqlite3GetTempReg(pParse);
114394        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
114395        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
114396        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114397        sqlite3ReleaseTempReg(pParse, r1);
114398      }
114399      break;
114400    }
114401
114402    /* If any row exist in the result set, record that fact and abort.
114403    */
114404    case SRT_Exists: {
114405      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
114406      /* The LIMIT clause will terminate the loop for us */
114407      break;
114408    }
114409
114410    /* If this is a scalar select that is part of an expression, then
114411    ** store the results in the appropriate memory cell and break out
114412    ** of the scan loop.
114413    */
114414    case SRT_Mem: {
114415      assert( nResultCol==1 );
114416      if( pSort ){
114417        pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
114418      }else{
114419        assert( regResult==iParm );
114420        /* The LIMIT clause will jump out of the loop for us */
114421      }
114422      break;
114423    }
114424#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
114425
114426    case SRT_Coroutine:       /* Send data to a co-routine */
114427    case SRT_Output: {        /* Return the results */
114428      testcase( eDest==SRT_Coroutine );
114429      testcase( eDest==SRT_Output );
114430      if( pSort ){
114431        pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
114432                       nPrefixReg);
114433      }else if( eDest==SRT_Coroutine ){
114434        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114435      }else{
114436        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
114437        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
114438      }
114439      break;
114440    }
114441
114442#ifndef SQLITE_OMIT_CTE
114443    /* Write the results into a priority queue that is order according to
114444    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
114445    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
114446    ** pSO->nExpr columns, then make sure all keys are unique by adding a
114447    ** final OP_Sequence column.  The last column is the record as a blob.
114448    */
114449    case SRT_DistQueue:
114450    case SRT_Queue: {
114451      int nKey;
114452      int r1, r2, r3;
114453      int addrTest = 0;
114454      ExprList *pSO;
114455      pSO = pDest->pOrderBy;
114456      assert( pSO );
114457      nKey = pSO->nExpr;
114458      r1 = sqlite3GetTempReg(pParse);
114459      r2 = sqlite3GetTempRange(pParse, nKey+2);
114460      r3 = r2+nKey+1;
114461      if( eDest==SRT_DistQueue ){
114462        /* If the destination is DistQueue, then cursor (iParm+1) is open
114463        ** on a second ephemeral index that holds all values every previously
114464        ** added to the queue. */
114465        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
114466                                        regResult, nResultCol);
114467        VdbeCoverage(v);
114468      }
114469      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
114470      if( eDest==SRT_DistQueue ){
114471        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
114472        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
114473      }
114474      for(i=0; i<nKey; i++){
114475        sqlite3VdbeAddOp2(v, OP_SCopy,
114476                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
114477                          r2+i);
114478      }
114479      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
114480      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
114481      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114482      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
114483      sqlite3ReleaseTempReg(pParse, r1);
114484      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
114485      break;
114486    }
114487#endif /* SQLITE_OMIT_CTE */
114488
114489
114490
114491#if !defined(SQLITE_OMIT_TRIGGER)
114492    /* Discard the results.  This is used for SELECT statements inside
114493    ** the body of a TRIGGER.  The purpose of such selects is to call
114494    ** user-defined functions that have side effects.  We do not care
114495    ** about the actual results of the select.
114496    */
114497    default: {
114498      assert( eDest==SRT_Discard );
114499      break;
114500    }
114501#endif
114502  }
114503
114504  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
114505  ** there is a sorter, in which case the sorter has already limited
114506  ** the output for us.
114507  */
114508  if( pSort==0 && p->iLimit ){
114509    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
114510  }
114511}
114512
114513/*
114514** Allocate a KeyInfo object sufficient for an index of N key columns and
114515** X extra columns.
114516*/
114517SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
114518  int nExtra = (N+X)*(sizeof(CollSeq*)+1);
114519  KeyInfo *p = sqlite3DbMallocRaw(db, sizeof(KeyInfo) + nExtra);
114520  if( p ){
114521    p->aSortOrder = (u8*)&p->aColl[N+X];
114522    p->nField = (u16)N;
114523    p->nXField = (u16)X;
114524    p->enc = ENC(db);
114525    p->db = db;
114526    p->nRef = 1;
114527    memset(&p[1], 0, nExtra);
114528  }else{
114529    sqlite3OomFault(db);
114530  }
114531  return p;
114532}
114533
114534/*
114535** Deallocate a KeyInfo object
114536*/
114537SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
114538  if( p ){
114539    assert( p->nRef>0 );
114540    p->nRef--;
114541    if( p->nRef==0 ) sqlite3DbFree(p->db, p);
114542  }
114543}
114544
114545/*
114546** Make a new pointer to a KeyInfo object
114547*/
114548SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
114549  if( p ){
114550    assert( p->nRef>0 );
114551    p->nRef++;
114552  }
114553  return p;
114554}
114555
114556#ifdef SQLITE_DEBUG
114557/*
114558** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
114559** can only be changed if this is just a single reference to the object.
114560**
114561** This routine is used only inside of assert() statements.
114562*/
114563SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
114564#endif /* SQLITE_DEBUG */
114565
114566/*
114567** Given an expression list, generate a KeyInfo structure that records
114568** the collating sequence for each expression in that expression list.
114569**
114570** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
114571** KeyInfo structure is appropriate for initializing a virtual index to
114572** implement that clause.  If the ExprList is the result set of a SELECT
114573** then the KeyInfo structure is appropriate for initializing a virtual
114574** index to implement a DISTINCT test.
114575**
114576** Space to hold the KeyInfo structure is obtained from malloc.  The calling
114577** function is responsible for seeing that this structure is eventually
114578** freed.
114579*/
114580static KeyInfo *keyInfoFromExprList(
114581  Parse *pParse,       /* Parsing context */
114582  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
114583  int iStart,          /* Begin with this column of pList */
114584  int nExtra           /* Add this many extra columns to the end */
114585){
114586  int nExpr;
114587  KeyInfo *pInfo;
114588  struct ExprList_item *pItem;
114589  sqlite3 *db = pParse->db;
114590  int i;
114591
114592  nExpr = pList->nExpr;
114593  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
114594  if( pInfo ){
114595    assert( sqlite3KeyInfoIsWriteable(pInfo) );
114596    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
114597      CollSeq *pColl;
114598      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
114599      if( !pColl ) pColl = db->pDfltColl;
114600      pInfo->aColl[i-iStart] = pColl;
114601      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
114602    }
114603  }
114604  return pInfo;
114605}
114606
114607/*
114608** Name of the connection operator, used for error messages.
114609*/
114610static const char *selectOpName(int id){
114611  char *z;
114612  switch( id ){
114613    case TK_ALL:       z = "UNION ALL";   break;
114614    case TK_INTERSECT: z = "INTERSECT";   break;
114615    case TK_EXCEPT:    z = "EXCEPT";      break;
114616    default:           z = "UNION";       break;
114617  }
114618  return z;
114619}
114620
114621#ifndef SQLITE_OMIT_EXPLAIN
114622/*
114623** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
114624** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114625** where the caption is of the form:
114626**
114627**   "USE TEMP B-TREE FOR xxx"
114628**
114629** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
114630** is determined by the zUsage argument.
114631*/
114632static void explainTempTable(Parse *pParse, const char *zUsage){
114633  if( pParse->explain==2 ){
114634    Vdbe *v = pParse->pVdbe;
114635    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
114636    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
114637  }
114638}
114639
114640/*
114641** Assign expression b to lvalue a. A second, no-op, version of this macro
114642** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
114643** in sqlite3Select() to assign values to structure member variables that
114644** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
114645** code with #ifndef directives.
114646*/
114647# define explainSetInteger(a, b) a = b
114648
114649#else
114650/* No-op versions of the explainXXX() functions and macros. */
114651# define explainTempTable(y,z)
114652# define explainSetInteger(y,z)
114653#endif
114654
114655#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
114656/*
114657** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
114658** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114659** where the caption is of one of the two forms:
114660**
114661**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
114662**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
114663**
114664** where iSub1 and iSub2 are the integers passed as the corresponding
114665** function parameters, and op is the text representation of the parameter
114666** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
114667** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
114668** false, or the second form if it is true.
114669*/
114670static void explainComposite(
114671  Parse *pParse,                  /* Parse context */
114672  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
114673  int iSub1,                      /* Subquery id 1 */
114674  int iSub2,                      /* Subquery id 2 */
114675  int bUseTmp                     /* True if a temp table was used */
114676){
114677  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
114678  if( pParse->explain==2 ){
114679    Vdbe *v = pParse->pVdbe;
114680    char *zMsg = sqlite3MPrintf(
114681        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
114682        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
114683    );
114684    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
114685  }
114686}
114687#else
114688/* No-op versions of the explainXXX() functions and macros. */
114689# define explainComposite(v,w,x,y,z)
114690#endif
114691
114692/*
114693** If the inner loop was generated using a non-null pOrderBy argument,
114694** then the results were placed in a sorter.  After the loop is terminated
114695** we need to run the sorter and output the results.  The following
114696** routine generates the code needed to do that.
114697*/
114698static void generateSortTail(
114699  Parse *pParse,    /* Parsing context */
114700  Select *p,        /* The SELECT statement */
114701  SortCtx *pSort,   /* Information on the ORDER BY clause */
114702  int nColumn,      /* Number of columns of data */
114703  SelectDest *pDest /* Write the sorted results here */
114704){
114705  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
114706  int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
114707  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
114708  int addr;
114709  int addrOnce = 0;
114710  int iTab;
114711  ExprList *pOrderBy = pSort->pOrderBy;
114712  int eDest = pDest->eDest;
114713  int iParm = pDest->iSDParm;
114714  int regRow;
114715  int regRowid;
114716  int nKey;
114717  int iSortTab;                   /* Sorter cursor to read from */
114718  int nSortData;                  /* Trailing values to read from sorter */
114719  int i;
114720  int bSeq;                       /* True if sorter record includes seq. no. */
114721#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
114722  struct ExprList_item *aOutEx = p->pEList->a;
114723#endif
114724
114725  assert( addrBreak<0 );
114726  if( pSort->labelBkOut ){
114727    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114728    sqlite3VdbeGoto(v, addrBreak);
114729    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
114730  }
114731  iTab = pSort->iECursor;
114732  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
114733    regRowid = 0;
114734    regRow = pDest->iSdst;
114735    nSortData = nColumn;
114736  }else{
114737    regRowid = sqlite3GetTempReg(pParse);
114738    regRow = sqlite3GetTempReg(pParse);
114739    nSortData = 1;
114740  }
114741  nKey = pOrderBy->nExpr - pSort->nOBSat;
114742  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114743    int regSortOut = ++pParse->nMem;
114744    iSortTab = pParse->nTab++;
114745    if( pSort->labelBkOut ){
114746      addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
114747    }
114748    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
114749    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
114750    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
114751    VdbeCoverage(v);
114752    codeOffset(v, p->iOffset, addrContinue);
114753    sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
114754    bSeq = 0;
114755  }else{
114756    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
114757    codeOffset(v, p->iOffset, addrContinue);
114758    iSortTab = iTab;
114759    bSeq = 1;
114760  }
114761  for(i=0; i<nSortData; i++){
114762    sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
114763    VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
114764  }
114765  switch( eDest ){
114766    case SRT_EphemTab: {
114767      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
114768      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
114769      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
114770      break;
114771    }
114772#ifndef SQLITE_OMIT_SUBQUERY
114773    case SRT_Set: {
114774      assert( nColumn==1 );
114775      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
114776                        &pDest->affSdst, 1);
114777      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
114778      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
114779      break;
114780    }
114781    case SRT_Mem: {
114782      assert( nColumn==1 );
114783      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
114784      /* The LIMIT clause will terminate the loop for us */
114785      break;
114786    }
114787#endif
114788    default: {
114789      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
114790      testcase( eDest==SRT_Output );
114791      testcase( eDest==SRT_Coroutine );
114792      if( eDest==SRT_Output ){
114793        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
114794        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
114795      }else{
114796        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114797      }
114798      break;
114799    }
114800  }
114801  if( regRowid ){
114802    sqlite3ReleaseTempReg(pParse, regRow);
114803    sqlite3ReleaseTempReg(pParse, regRowid);
114804  }
114805  /* The bottom of the loop
114806  */
114807  sqlite3VdbeResolveLabel(v, addrContinue);
114808  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114809    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
114810  }else{
114811    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
114812  }
114813  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
114814  sqlite3VdbeResolveLabel(v, addrBreak);
114815}
114816
114817/*
114818** Return a pointer to a string containing the 'declaration type' of the
114819** expression pExpr. The string may be treated as static by the caller.
114820**
114821** Also try to estimate the size of the returned value and return that
114822** result in *pEstWidth.
114823**
114824** The declaration type is the exact datatype definition extracted from the
114825** original CREATE TABLE statement if the expression is a column. The
114826** declaration type for a ROWID field is INTEGER. Exactly when an expression
114827** is considered a column can be complex in the presence of subqueries. The
114828** result-set expression in all of the following SELECT statements is
114829** considered a column by this function.
114830**
114831**   SELECT col FROM tbl;
114832**   SELECT (SELECT col FROM tbl;
114833**   SELECT (SELECT col FROM tbl);
114834**   SELECT abc FROM (SELECT col AS abc FROM tbl);
114835**
114836** The declaration type for any expression other than a column is NULL.
114837**
114838** This routine has either 3 or 6 parameters depending on whether or not
114839** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
114840*/
114841#ifdef SQLITE_ENABLE_COLUMN_METADATA
114842# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
114843#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
114844# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
114845#endif
114846static const char *columnTypeImpl(
114847  NameContext *pNC,
114848  Expr *pExpr,
114849#ifdef SQLITE_ENABLE_COLUMN_METADATA
114850  const char **pzOrigDb,
114851  const char **pzOrigTab,
114852  const char **pzOrigCol,
114853#endif
114854  u8 *pEstWidth
114855){
114856  char const *zType = 0;
114857  int j;
114858  u8 estWidth = 1;
114859#ifdef SQLITE_ENABLE_COLUMN_METADATA
114860  char const *zOrigDb = 0;
114861  char const *zOrigTab = 0;
114862  char const *zOrigCol = 0;
114863#endif
114864
114865  assert( pExpr!=0 );
114866  assert( pNC->pSrcList!=0 );
114867  switch( pExpr->op ){
114868    case TK_AGG_COLUMN:
114869    case TK_COLUMN: {
114870      /* The expression is a column. Locate the table the column is being
114871      ** extracted from in NameContext.pSrcList. This table may be real
114872      ** database table or a subquery.
114873      */
114874      Table *pTab = 0;            /* Table structure column is extracted from */
114875      Select *pS = 0;             /* Select the column is extracted from */
114876      int iCol = pExpr->iColumn;  /* Index of column in pTab */
114877      testcase( pExpr->op==TK_AGG_COLUMN );
114878      testcase( pExpr->op==TK_COLUMN );
114879      while( pNC && !pTab ){
114880        SrcList *pTabList = pNC->pSrcList;
114881        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
114882        if( j<pTabList->nSrc ){
114883          pTab = pTabList->a[j].pTab;
114884          pS = pTabList->a[j].pSelect;
114885        }else{
114886          pNC = pNC->pNext;
114887        }
114888      }
114889
114890      if( pTab==0 ){
114891        /* At one time, code such as "SELECT new.x" within a trigger would
114892        ** cause this condition to run.  Since then, we have restructured how
114893        ** trigger code is generated and so this condition is no longer
114894        ** possible. However, it can still be true for statements like
114895        ** the following:
114896        **
114897        **   CREATE TABLE t1(col INTEGER);
114898        **   SELECT (SELECT t1.col) FROM FROM t1;
114899        **
114900        ** when columnType() is called on the expression "t1.col" in the
114901        ** sub-select. In this case, set the column type to NULL, even
114902        ** though it should really be "INTEGER".
114903        **
114904        ** This is not a problem, as the column type of "t1.col" is never
114905        ** used. When columnType() is called on the expression
114906        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
114907        ** branch below.  */
114908        break;
114909      }
114910
114911      assert( pTab && pExpr->pTab==pTab );
114912      if( pS ){
114913        /* The "table" is actually a sub-select or a view in the FROM clause
114914        ** of the SELECT statement. Return the declaration type and origin
114915        ** data for the result-set column of the sub-select.
114916        */
114917        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
114918          /* If iCol is less than zero, then the expression requests the
114919          ** rowid of the sub-select or view. This expression is legal (see
114920          ** test case misc2.2.2) - it always evaluates to NULL.
114921          **
114922          ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
114923          ** caught already by name resolution.
114924          */
114925          NameContext sNC;
114926          Expr *p = pS->pEList->a[iCol].pExpr;
114927          sNC.pSrcList = pS->pSrc;
114928          sNC.pNext = pNC;
114929          sNC.pParse = pNC->pParse;
114930          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
114931        }
114932      }else if( pTab->pSchema ){
114933        /* A real table */
114934        assert( !pS );
114935        if( iCol<0 ) iCol = pTab->iPKey;
114936        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
114937#ifdef SQLITE_ENABLE_COLUMN_METADATA
114938        if( iCol<0 ){
114939          zType = "INTEGER";
114940          zOrigCol = "rowid";
114941        }else{
114942          zOrigCol = pTab->aCol[iCol].zName;
114943          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114944          estWidth = pTab->aCol[iCol].szEst;
114945        }
114946        zOrigTab = pTab->zName;
114947        if( pNC->pParse ){
114948          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
114949          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
114950        }
114951#else
114952        if( iCol<0 ){
114953          zType = "INTEGER";
114954        }else{
114955          zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114956          estWidth = pTab->aCol[iCol].szEst;
114957        }
114958#endif
114959      }
114960      break;
114961    }
114962#ifndef SQLITE_OMIT_SUBQUERY
114963    case TK_SELECT: {
114964      /* The expression is a sub-select. Return the declaration type and
114965      ** origin info for the single column in the result set of the SELECT
114966      ** statement.
114967      */
114968      NameContext sNC;
114969      Select *pS = pExpr->x.pSelect;
114970      Expr *p = pS->pEList->a[0].pExpr;
114971      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
114972      sNC.pSrcList = pS->pSrc;
114973      sNC.pNext = pNC;
114974      sNC.pParse = pNC->pParse;
114975      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
114976      break;
114977    }
114978#endif
114979  }
114980
114981#ifdef SQLITE_ENABLE_COLUMN_METADATA
114982  if( pzOrigDb ){
114983    assert( pzOrigTab && pzOrigCol );
114984    *pzOrigDb = zOrigDb;
114985    *pzOrigTab = zOrigTab;
114986    *pzOrigCol = zOrigCol;
114987  }
114988#endif
114989  if( pEstWidth ) *pEstWidth = estWidth;
114990  return zType;
114991}
114992
114993/*
114994** Generate code that will tell the VDBE the declaration types of columns
114995** in the result set.
114996*/
114997static void generateColumnTypes(
114998  Parse *pParse,      /* Parser context */
114999  SrcList *pTabList,  /* List of tables */
115000  ExprList *pEList    /* Expressions defining the result set */
115001){
115002#ifndef SQLITE_OMIT_DECLTYPE
115003  Vdbe *v = pParse->pVdbe;
115004  int i;
115005  NameContext sNC;
115006  sNC.pSrcList = pTabList;
115007  sNC.pParse = pParse;
115008  for(i=0; i<pEList->nExpr; i++){
115009    Expr *p = pEList->a[i].pExpr;
115010    const char *zType;
115011#ifdef SQLITE_ENABLE_COLUMN_METADATA
115012    const char *zOrigDb = 0;
115013    const char *zOrigTab = 0;
115014    const char *zOrigCol = 0;
115015    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
115016
115017    /* The vdbe must make its own copy of the column-type and other
115018    ** column specific strings, in case the schema is reset before this
115019    ** virtual machine is deleted.
115020    */
115021    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
115022    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
115023    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
115024#else
115025    zType = columnType(&sNC, p, 0, 0, 0, 0);
115026#endif
115027    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
115028  }
115029#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
115030}
115031
115032/*
115033** Generate code that will tell the VDBE the names of columns
115034** in the result set.  This information is used to provide the
115035** azCol[] values in the callback.
115036*/
115037static void generateColumnNames(
115038  Parse *pParse,      /* Parser context */
115039  SrcList *pTabList,  /* List of tables */
115040  ExprList *pEList    /* Expressions defining the result set */
115041){
115042  Vdbe *v = pParse->pVdbe;
115043  int i, j;
115044  sqlite3 *db = pParse->db;
115045  int fullNames, shortNames;
115046
115047#ifndef SQLITE_OMIT_EXPLAIN
115048  /* If this is an EXPLAIN, skip this step */
115049  if( pParse->explain ){
115050    return;
115051  }
115052#endif
115053
115054  if( pParse->colNamesSet || db->mallocFailed ) return;
115055  assert( v!=0 );
115056  assert( pTabList!=0 );
115057  pParse->colNamesSet = 1;
115058  fullNames = (db->flags & SQLITE_FullColNames)!=0;
115059  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
115060  sqlite3VdbeSetNumCols(v, pEList->nExpr);
115061  for(i=0; i<pEList->nExpr; i++){
115062    Expr *p;
115063    p = pEList->a[i].pExpr;
115064    if( NEVER(p==0) ) continue;
115065    if( pEList->a[i].zName ){
115066      char *zName = pEList->a[i].zName;
115067      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
115068    }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
115069      Table *pTab;
115070      char *zCol;
115071      int iCol = p->iColumn;
115072      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
115073        if( pTabList->a[j].iCursor==p->iTable ) break;
115074      }
115075      assert( j<pTabList->nSrc );
115076      pTab = pTabList->a[j].pTab;
115077      if( iCol<0 ) iCol = pTab->iPKey;
115078      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115079      if( iCol<0 ){
115080        zCol = "rowid";
115081      }else{
115082        zCol = pTab->aCol[iCol].zName;
115083      }
115084      if( !shortNames && !fullNames ){
115085        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
115086            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
115087      }else if( fullNames ){
115088        char *zName = 0;
115089        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
115090        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
115091      }else{
115092        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
115093      }
115094    }else{
115095      const char *z = pEList->a[i].zSpan;
115096      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
115097      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
115098    }
115099  }
115100  generateColumnTypes(pParse, pTabList, pEList);
115101}
115102
115103/*
115104** Given an expression list (which is really the list of expressions
115105** that form the result set of a SELECT statement) compute appropriate
115106** column names for a table that would hold the expression list.
115107**
115108** All column names will be unique.
115109**
115110** Only the column names are computed.  Column.zType, Column.zColl,
115111** and other fields of Column are zeroed.
115112**
115113** Return SQLITE_OK on success.  If a memory allocation error occurs,
115114** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
115115*/
115116SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
115117  Parse *pParse,          /* Parsing context */
115118  ExprList *pEList,       /* Expr list from which to derive column names */
115119  i16 *pnCol,             /* Write the number of columns here */
115120  Column **paCol          /* Write the new column list here */
115121){
115122  sqlite3 *db = pParse->db;   /* Database connection */
115123  int i, j;                   /* Loop counters */
115124  u32 cnt;                    /* Index added to make the name unique */
115125  Column *aCol, *pCol;        /* For looping over result columns */
115126  int nCol;                   /* Number of columns in the result set */
115127  Expr *p;                    /* Expression for a single result column */
115128  char *zName;                /* Column name */
115129  int nName;                  /* Size of name in zName[] */
115130  Hash ht;                    /* Hash table of column names */
115131
115132  sqlite3HashInit(&ht);
115133  if( pEList ){
115134    nCol = pEList->nExpr;
115135    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
115136    testcase( aCol==0 );
115137  }else{
115138    nCol = 0;
115139    aCol = 0;
115140  }
115141  assert( nCol==(i16)nCol );
115142  *pnCol = nCol;
115143  *paCol = aCol;
115144
115145  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
115146    /* Get an appropriate name for the column
115147    */
115148    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
115149    if( (zName = pEList->a[i].zName)!=0 ){
115150      /* If the column contains an "AS <name>" phrase, use <name> as the name */
115151    }else{
115152      Expr *pColExpr = p;  /* The expression that is the result column name */
115153      Table *pTab;         /* Table associated with this expression */
115154      while( pColExpr->op==TK_DOT ){
115155        pColExpr = pColExpr->pRight;
115156        assert( pColExpr!=0 );
115157      }
115158      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
115159        /* For columns use the column name name */
115160        int iCol = pColExpr->iColumn;
115161        pTab = pColExpr->pTab;
115162        if( iCol<0 ) iCol = pTab->iPKey;
115163        zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
115164      }else if( pColExpr->op==TK_ID ){
115165        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
115166        zName = pColExpr->u.zToken;
115167      }else{
115168        /* Use the original text of the column expression as its name */
115169        zName = pEList->a[i].zSpan;
115170      }
115171    }
115172    zName = sqlite3MPrintf(db, "%s", zName);
115173
115174    /* Make sure the column name is unique.  If the name is not unique,
115175    ** append an integer to the name so that it becomes unique.
115176    */
115177    cnt = 0;
115178    while( zName && sqlite3HashFind(&ht, zName)!=0 ){
115179      nName = sqlite3Strlen30(zName);
115180      if( nName>0 ){
115181        for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
115182        if( zName[j]==':' ) nName = j;
115183      }
115184      zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
115185      if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
115186    }
115187    pCol->zName = zName;
115188    sqlite3ColumnPropertiesFromName(0, pCol);
115189    if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
115190      sqlite3OomFault(db);
115191    }
115192  }
115193  sqlite3HashClear(&ht);
115194  if( db->mallocFailed ){
115195    for(j=0; j<i; j++){
115196      sqlite3DbFree(db, aCol[j].zName);
115197    }
115198    sqlite3DbFree(db, aCol);
115199    *paCol = 0;
115200    *pnCol = 0;
115201    return SQLITE_NOMEM_BKPT;
115202  }
115203  return SQLITE_OK;
115204}
115205
115206/*
115207** Add type and collation information to a column list based on
115208** a SELECT statement.
115209**
115210** The column list presumably came from selectColumnNamesFromExprList().
115211** The column list has only names, not types or collations.  This
115212** routine goes through and adds the types and collations.
115213**
115214** This routine requires that all identifiers in the SELECT
115215** statement be resolved.
115216*/
115217SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
115218  Parse *pParse,        /* Parsing contexts */
115219  Table *pTab,          /* Add column type information to this table */
115220  Select *pSelect       /* SELECT used to determine types and collations */
115221){
115222  sqlite3 *db = pParse->db;
115223  NameContext sNC;
115224  Column *pCol;
115225  CollSeq *pColl;
115226  int i;
115227  Expr *p;
115228  struct ExprList_item *a;
115229  u64 szAll = 0;
115230
115231  assert( pSelect!=0 );
115232  assert( (pSelect->selFlags & SF_Resolved)!=0 );
115233  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
115234  if( db->mallocFailed ) return;
115235  memset(&sNC, 0, sizeof(sNC));
115236  sNC.pSrcList = pSelect->pSrc;
115237  a = pSelect->pEList->a;
115238  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
115239    const char *zType;
115240    int n, m;
115241    p = a[i].pExpr;
115242    zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
115243    szAll += pCol->szEst;
115244    pCol->affinity = sqlite3ExprAffinity(p);
115245    if( zType && (m = sqlite3Strlen30(zType))>0 ){
115246      n = sqlite3Strlen30(pCol->zName);
115247      pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
115248      if( pCol->zName ){
115249        memcpy(&pCol->zName[n+1], zType, m+1);
115250        pCol->colFlags |= COLFLAG_HASTYPE;
115251      }
115252    }
115253    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
115254    pColl = sqlite3ExprCollSeq(pParse, p);
115255    if( pColl && pCol->zColl==0 ){
115256      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
115257    }
115258  }
115259  pTab->szTabRow = sqlite3LogEst(szAll*4);
115260}
115261
115262/*
115263** Given a SELECT statement, generate a Table structure that describes
115264** the result set of that SELECT.
115265*/
115266SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
115267  Table *pTab;
115268  sqlite3 *db = pParse->db;
115269  int savedFlags;
115270
115271  savedFlags = db->flags;
115272  db->flags &= ~SQLITE_FullColNames;
115273  db->flags |= SQLITE_ShortColNames;
115274  sqlite3SelectPrep(pParse, pSelect, 0);
115275  if( pParse->nErr ) return 0;
115276  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
115277  db->flags = savedFlags;
115278  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
115279  if( pTab==0 ){
115280    return 0;
115281  }
115282  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
115283  ** is disabled */
115284  assert( db->lookaside.bDisable );
115285  pTab->nRef = 1;
115286  pTab->zName = 0;
115287  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
115288  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
115289  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
115290  pTab->iPKey = -1;
115291  if( db->mallocFailed ){
115292    sqlite3DeleteTable(db, pTab);
115293    return 0;
115294  }
115295  return pTab;
115296}
115297
115298/*
115299** Get a VDBE for the given parser context.  Create a new one if necessary.
115300** If an error occurs, return NULL and leave a message in pParse.
115301*/
115302static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
115303  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
115304  if( v ) sqlite3VdbeAddOp0(v, OP_Init);
115305  if( pParse->pToplevel==0
115306   && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
115307  ){
115308    pParse->okConstFactor = 1;
115309  }
115310  return v;
115311}
115312SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
115313  Vdbe *v = pParse->pVdbe;
115314  return v ? v : allocVdbe(pParse);
115315}
115316
115317
115318/*
115319** Compute the iLimit and iOffset fields of the SELECT based on the
115320** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
115321** that appear in the original SQL statement after the LIMIT and OFFSET
115322** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
115323** are the integer memory register numbers for counters used to compute
115324** the limit and offset.  If there is no limit and/or offset, then
115325** iLimit and iOffset are negative.
115326**
115327** This routine changes the values of iLimit and iOffset only if
115328** a limit or offset is defined by pLimit and pOffset.  iLimit and
115329** iOffset should have been preset to appropriate default values (zero)
115330** prior to calling this routine.
115331**
115332** The iOffset register (if it exists) is initialized to the value
115333** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
115334** iOffset+1 is initialized to LIMIT+OFFSET.
115335**
115336** Only if pLimit!=0 or pOffset!=0 do the limit registers get
115337** redefined.  The UNION ALL operator uses this property to force
115338** the reuse of the same limit and offset registers across multiple
115339** SELECT statements.
115340*/
115341static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
115342  Vdbe *v = 0;
115343  int iLimit = 0;
115344  int iOffset;
115345  int n;
115346  if( p->iLimit ) return;
115347
115348  /*
115349  ** "LIMIT -1" always shows all rows.  There is some
115350  ** controversy about what the correct behavior should be.
115351  ** The current implementation interprets "LIMIT 0" to mean
115352  ** no rows.
115353  */
115354  sqlite3ExprCacheClear(pParse);
115355  assert( p->pOffset==0 || p->pLimit!=0 );
115356  if( p->pLimit ){
115357    p->iLimit = iLimit = ++pParse->nMem;
115358    v = sqlite3GetVdbe(pParse);
115359    assert( v!=0 );
115360    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
115361      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
115362      VdbeComment((v, "LIMIT counter"));
115363      if( n==0 ){
115364        sqlite3VdbeGoto(v, iBreak);
115365      }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
115366        p->nSelectRow = sqlite3LogEst((u64)n);
115367        p->selFlags |= SF_FixedLimit;
115368      }
115369    }else{
115370      sqlite3ExprCode(pParse, p->pLimit, iLimit);
115371      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
115372      VdbeComment((v, "LIMIT counter"));
115373      sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
115374    }
115375    if( p->pOffset ){
115376      p->iOffset = iOffset = ++pParse->nMem;
115377      pParse->nMem++;   /* Allocate an extra register for limit+offset */
115378      sqlite3ExprCode(pParse, p->pOffset, iOffset);
115379      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
115380      VdbeComment((v, "OFFSET counter"));
115381      sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
115382      VdbeComment((v, "LIMIT+OFFSET"));
115383    }
115384  }
115385}
115386
115387#ifndef SQLITE_OMIT_COMPOUND_SELECT
115388/*
115389** Return the appropriate collating sequence for the iCol-th column of
115390** the result set for the compound-select statement "p".  Return NULL if
115391** the column has no default collating sequence.
115392**
115393** The collating sequence for the compound select is taken from the
115394** left-most term of the select that has a collating sequence.
115395*/
115396static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
115397  CollSeq *pRet;
115398  if( p->pPrior ){
115399    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
115400  }else{
115401    pRet = 0;
115402  }
115403  assert( iCol>=0 );
115404  /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
115405  ** have been thrown during name resolution and we would not have gotten
115406  ** this far */
115407  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
115408    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
115409  }
115410  return pRet;
115411}
115412
115413/*
115414** The select statement passed as the second parameter is a compound SELECT
115415** with an ORDER BY clause. This function allocates and returns a KeyInfo
115416** structure suitable for implementing the ORDER BY.
115417**
115418** Space to hold the KeyInfo structure is obtained from malloc. The calling
115419** function is responsible for ensuring that this structure is eventually
115420** freed.
115421*/
115422static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
115423  ExprList *pOrderBy = p->pOrderBy;
115424  int nOrderBy = p->pOrderBy->nExpr;
115425  sqlite3 *db = pParse->db;
115426  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
115427  if( pRet ){
115428    int i;
115429    for(i=0; i<nOrderBy; i++){
115430      struct ExprList_item *pItem = &pOrderBy->a[i];
115431      Expr *pTerm = pItem->pExpr;
115432      CollSeq *pColl;
115433
115434      if( pTerm->flags & EP_Collate ){
115435        pColl = sqlite3ExprCollSeq(pParse, pTerm);
115436      }else{
115437        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
115438        if( pColl==0 ) pColl = db->pDfltColl;
115439        pOrderBy->a[i].pExpr =
115440          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
115441      }
115442      assert( sqlite3KeyInfoIsWriteable(pRet) );
115443      pRet->aColl[i] = pColl;
115444      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
115445    }
115446  }
115447
115448  return pRet;
115449}
115450
115451#ifndef SQLITE_OMIT_CTE
115452/*
115453** This routine generates VDBE code to compute the content of a WITH RECURSIVE
115454** query of the form:
115455**
115456**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
115457**                         \___________/             \_______________/
115458**                           p->pPrior                      p
115459**
115460**
115461** There is exactly one reference to the recursive-table in the FROM clause
115462** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
115463**
115464** The setup-query runs once to generate an initial set of rows that go
115465** into a Queue table.  Rows are extracted from the Queue table one by
115466** one.  Each row extracted from Queue is output to pDest.  Then the single
115467** extracted row (now in the iCurrent table) becomes the content of the
115468** recursive-table for a recursive-query run.  The output of the recursive-query
115469** is added back into the Queue table.  Then another row is extracted from Queue
115470** and the iteration continues until the Queue table is empty.
115471**
115472** If the compound query operator is UNION then no duplicate rows are ever
115473** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
115474** that have ever been inserted into Queue and causes duplicates to be
115475** discarded.  If the operator is UNION ALL, then duplicates are allowed.
115476**
115477** If the query has an ORDER BY, then entries in the Queue table are kept in
115478** ORDER BY order and the first entry is extracted for each cycle.  Without
115479** an ORDER BY, the Queue table is just a FIFO.
115480**
115481** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
115482** have been output to pDest.  A LIMIT of zero means to output no rows and a
115483** negative LIMIT means to output all rows.  If there is also an OFFSET clause
115484** with a positive value, then the first OFFSET outputs are discarded rather
115485** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
115486** rows have been skipped.
115487*/
115488static void generateWithRecursiveQuery(
115489  Parse *pParse,        /* Parsing context */
115490  Select *p,            /* The recursive SELECT to be coded */
115491  SelectDest *pDest     /* What to do with query results */
115492){
115493  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
115494  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
115495  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
115496  Select *pSetup = p->pPrior;   /* The setup query */
115497  int addrTop;                  /* Top of the loop */
115498  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
115499  int iCurrent = 0;             /* The Current table */
115500  int regCurrent;               /* Register holding Current table */
115501  int iQueue;                   /* The Queue table */
115502  int iDistinct = 0;            /* To ensure unique results if UNION */
115503  int eDest = SRT_Fifo;         /* How to write to Queue */
115504  SelectDest destQueue;         /* SelectDest targetting the Queue table */
115505  int i;                        /* Loop counter */
115506  int rc;                       /* Result code */
115507  ExprList *pOrderBy;           /* The ORDER BY clause */
115508  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
115509  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
115510
115511  /* Obtain authorization to do a recursive query */
115512  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
115513
115514  /* Process the LIMIT and OFFSET clauses, if they exist */
115515  addrBreak = sqlite3VdbeMakeLabel(v);
115516  computeLimitRegisters(pParse, p, addrBreak);
115517  pLimit = p->pLimit;
115518  pOffset = p->pOffset;
115519  regLimit = p->iLimit;
115520  regOffset = p->iOffset;
115521  p->pLimit = p->pOffset = 0;
115522  p->iLimit = p->iOffset = 0;
115523  pOrderBy = p->pOrderBy;
115524
115525  /* Locate the cursor number of the Current table */
115526  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
115527    if( pSrc->a[i].fg.isRecursive ){
115528      iCurrent = pSrc->a[i].iCursor;
115529      break;
115530    }
115531  }
115532
115533  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
115534  ** the Distinct table must be exactly one greater than Queue in order
115535  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
115536  iQueue = pParse->nTab++;
115537  if( p->op==TK_UNION ){
115538    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
115539    iDistinct = pParse->nTab++;
115540  }else{
115541    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
115542  }
115543  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
115544
115545  /* Allocate cursors for Current, Queue, and Distinct. */
115546  regCurrent = ++pParse->nMem;
115547  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
115548  if( pOrderBy ){
115549    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
115550    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
115551                      (char*)pKeyInfo, P4_KEYINFO);
115552    destQueue.pOrderBy = pOrderBy;
115553  }else{
115554    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
115555  }
115556  VdbeComment((v, "Queue table"));
115557  if( iDistinct ){
115558    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
115559    p->selFlags |= SF_UsesEphemeral;
115560  }
115561
115562  /* Detach the ORDER BY clause from the compound SELECT */
115563  p->pOrderBy = 0;
115564
115565  /* Store the results of the setup-query in Queue. */
115566  pSetup->pNext = 0;
115567  rc = sqlite3Select(pParse, pSetup, &destQueue);
115568  pSetup->pNext = p;
115569  if( rc ) goto end_of_recursive_query;
115570
115571  /* Find the next row in the Queue and output that row */
115572  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
115573
115574  /* Transfer the next row in Queue over to Current */
115575  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
115576  if( pOrderBy ){
115577    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
115578  }else{
115579    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
115580  }
115581  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
115582
115583  /* Output the single row in Current */
115584  addrCont = sqlite3VdbeMakeLabel(v);
115585  codeOffset(v, regOffset, addrCont);
115586  selectInnerLoop(pParse, p, p->pEList, iCurrent,
115587      0, 0, pDest, addrCont, addrBreak);
115588  if( regLimit ){
115589    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
115590    VdbeCoverage(v);
115591  }
115592  sqlite3VdbeResolveLabel(v, addrCont);
115593
115594  /* Execute the recursive SELECT taking the single row in Current as
115595  ** the value for the recursive-table. Store the results in the Queue.
115596  */
115597  if( p->selFlags & SF_Aggregate ){
115598    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
115599  }else{
115600    p->pPrior = 0;
115601    sqlite3Select(pParse, p, &destQueue);
115602    assert( p->pPrior==0 );
115603    p->pPrior = pSetup;
115604  }
115605
115606  /* Keep running the loop until the Queue is empty */
115607  sqlite3VdbeGoto(v, addrTop);
115608  sqlite3VdbeResolveLabel(v, addrBreak);
115609
115610end_of_recursive_query:
115611  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
115612  p->pOrderBy = pOrderBy;
115613  p->pLimit = pLimit;
115614  p->pOffset = pOffset;
115615  return;
115616}
115617#endif /* SQLITE_OMIT_CTE */
115618
115619/* Forward references */
115620static int multiSelectOrderBy(
115621  Parse *pParse,        /* Parsing context */
115622  Select *p,            /* The right-most of SELECTs to be coded */
115623  SelectDest *pDest     /* What to do with query results */
115624);
115625
115626/*
115627** Handle the special case of a compound-select that originates from a
115628** VALUES clause.  By handling this as a special case, we avoid deep
115629** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
115630** on a VALUES clause.
115631**
115632** Because the Select object originates from a VALUES clause:
115633**   (1) It has no LIMIT or OFFSET
115634**   (2) All terms are UNION ALL
115635**   (3) There is no ORDER BY clause
115636*/
115637static int multiSelectValues(
115638  Parse *pParse,        /* Parsing context */
115639  Select *p,            /* The right-most of SELECTs to be coded */
115640  SelectDest *pDest     /* What to do with query results */
115641){
115642  Select *pPrior;
115643  int nRow = 1;
115644  int rc = 0;
115645  assert( p->selFlags & SF_MultiValue );
115646  do{
115647    assert( p->selFlags & SF_Values );
115648    assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
115649    assert( p->pLimit==0 );
115650    assert( p->pOffset==0 );
115651    assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
115652    if( p->pPrior==0 ) break;
115653    assert( p->pPrior->pNext==p );
115654    p = p->pPrior;
115655    nRow++;
115656  }while(1);
115657  while( p ){
115658    pPrior = p->pPrior;
115659    p->pPrior = 0;
115660    rc = sqlite3Select(pParse, p, pDest);
115661    p->pPrior = pPrior;
115662    if( rc ) break;
115663    p->nSelectRow = nRow;
115664    p = p->pNext;
115665  }
115666  return rc;
115667}
115668
115669/*
115670** This routine is called to process a compound query form from
115671** two or more separate queries using UNION, UNION ALL, EXCEPT, or
115672** INTERSECT
115673**
115674** "p" points to the right-most of the two queries.  the query on the
115675** left is p->pPrior.  The left query could also be a compound query
115676** in which case this routine will be called recursively.
115677**
115678** The results of the total query are to be written into a destination
115679** of type eDest with parameter iParm.
115680**
115681** Example 1:  Consider a three-way compound SQL statement.
115682**
115683**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
115684**
115685** This statement is parsed up as follows:
115686**
115687**     SELECT c FROM t3
115688**      |
115689**      `----->  SELECT b FROM t2
115690**                |
115691**                `------>  SELECT a FROM t1
115692**
115693** The arrows in the diagram above represent the Select.pPrior pointer.
115694** So if this routine is called with p equal to the t3 query, then
115695** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
115696**
115697** Notice that because of the way SQLite parses compound SELECTs, the
115698** individual selects always group from left to right.
115699*/
115700static int multiSelect(
115701  Parse *pParse,        /* Parsing context */
115702  Select *p,            /* The right-most of SELECTs to be coded */
115703  SelectDest *pDest     /* What to do with query results */
115704){
115705  int rc = SQLITE_OK;   /* Success code from a subroutine */
115706  Select *pPrior;       /* Another SELECT immediately to our left */
115707  Vdbe *v;              /* Generate code to this VDBE */
115708  SelectDest dest;      /* Alternative data destination */
115709  Select *pDelete = 0;  /* Chain of simple selects to delete */
115710  sqlite3 *db;          /* Database connection */
115711#ifndef SQLITE_OMIT_EXPLAIN
115712  int iSub1 = 0;        /* EQP id of left-hand query */
115713  int iSub2 = 0;        /* EQP id of right-hand query */
115714#endif
115715
115716  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
115717  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
115718  */
115719  assert( p && p->pPrior );  /* Calling function guarantees this much */
115720  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
115721  db = pParse->db;
115722  pPrior = p->pPrior;
115723  dest = *pDest;
115724  if( pPrior->pOrderBy ){
115725    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
115726      selectOpName(p->op));
115727    rc = 1;
115728    goto multi_select_end;
115729  }
115730  if( pPrior->pLimit ){
115731    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
115732      selectOpName(p->op));
115733    rc = 1;
115734    goto multi_select_end;
115735  }
115736
115737  v = sqlite3GetVdbe(pParse);
115738  assert( v!=0 );  /* The VDBE already created by calling function */
115739
115740  /* Create the destination temporary table if necessary
115741  */
115742  if( dest.eDest==SRT_EphemTab ){
115743    assert( p->pEList );
115744    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
115745    dest.eDest = SRT_Table;
115746  }
115747
115748  /* Special handling for a compound-select that originates as a VALUES clause.
115749  */
115750  if( p->selFlags & SF_MultiValue ){
115751    rc = multiSelectValues(pParse, p, &dest);
115752    goto multi_select_end;
115753  }
115754
115755  /* Make sure all SELECTs in the statement have the same number of elements
115756  ** in their result sets.
115757  */
115758  assert( p->pEList && pPrior->pEList );
115759  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
115760
115761#ifndef SQLITE_OMIT_CTE
115762  if( p->selFlags & SF_Recursive ){
115763    generateWithRecursiveQuery(pParse, p, &dest);
115764  }else
115765#endif
115766
115767  /* Compound SELECTs that have an ORDER BY clause are handled separately.
115768  */
115769  if( p->pOrderBy ){
115770    return multiSelectOrderBy(pParse, p, pDest);
115771  }else
115772
115773  /* Generate code for the left and right SELECT statements.
115774  */
115775  switch( p->op ){
115776    case TK_ALL: {
115777      int addr = 0;
115778      int nLimit;
115779      assert( !pPrior->pLimit );
115780      pPrior->iLimit = p->iLimit;
115781      pPrior->iOffset = p->iOffset;
115782      pPrior->pLimit = p->pLimit;
115783      pPrior->pOffset = p->pOffset;
115784      explainSetInteger(iSub1, pParse->iNextSelectId);
115785      rc = sqlite3Select(pParse, pPrior, &dest);
115786      p->pLimit = 0;
115787      p->pOffset = 0;
115788      if( rc ){
115789        goto multi_select_end;
115790      }
115791      p->pPrior = 0;
115792      p->iLimit = pPrior->iLimit;
115793      p->iOffset = pPrior->iOffset;
115794      if( p->iLimit ){
115795        addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
115796        VdbeComment((v, "Jump ahead if LIMIT reached"));
115797        if( p->iOffset ){
115798          sqlite3VdbeAddOp3(v, OP_OffsetLimit,
115799                            p->iLimit, p->iOffset+1, p->iOffset);
115800        }
115801      }
115802      explainSetInteger(iSub2, pParse->iNextSelectId);
115803      rc = sqlite3Select(pParse, p, &dest);
115804      testcase( rc!=SQLITE_OK );
115805      pDelete = p->pPrior;
115806      p->pPrior = pPrior;
115807      p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115808      if( pPrior->pLimit
115809       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
115810       && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
115811      ){
115812        p->nSelectRow = sqlite3LogEst((u64)nLimit);
115813      }
115814      if( addr ){
115815        sqlite3VdbeJumpHere(v, addr);
115816      }
115817      break;
115818    }
115819    case TK_EXCEPT:
115820    case TK_UNION: {
115821      int unionTab;    /* Cursor number of the temporary table holding result */
115822      u8 op = 0;       /* One of the SRT_ operations to apply to self */
115823      int priorOp;     /* The SRT_ operation to apply to prior selects */
115824      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
115825      int addr;
115826      SelectDest uniondest;
115827
115828      testcase( p->op==TK_EXCEPT );
115829      testcase( p->op==TK_UNION );
115830      priorOp = SRT_Union;
115831      if( dest.eDest==priorOp ){
115832        /* We can reuse a temporary table generated by a SELECT to our
115833        ** right.
115834        */
115835        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
115836        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
115837        unionTab = dest.iSDParm;
115838      }else{
115839        /* We will need to create our own temporary table to hold the
115840        ** intermediate results.
115841        */
115842        unionTab = pParse->nTab++;
115843        assert( p->pOrderBy==0 );
115844        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
115845        assert( p->addrOpenEphm[0] == -1 );
115846        p->addrOpenEphm[0] = addr;
115847        findRightmost(p)->selFlags |= SF_UsesEphemeral;
115848        assert( p->pEList );
115849      }
115850
115851      /* Code the SELECT statements to our left
115852      */
115853      assert( !pPrior->pOrderBy );
115854      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
115855      explainSetInteger(iSub1, pParse->iNextSelectId);
115856      rc = sqlite3Select(pParse, pPrior, &uniondest);
115857      if( rc ){
115858        goto multi_select_end;
115859      }
115860
115861      /* Code the current SELECT statement
115862      */
115863      if( p->op==TK_EXCEPT ){
115864        op = SRT_Except;
115865      }else{
115866        assert( p->op==TK_UNION );
115867        op = SRT_Union;
115868      }
115869      p->pPrior = 0;
115870      pLimit = p->pLimit;
115871      p->pLimit = 0;
115872      pOffset = p->pOffset;
115873      p->pOffset = 0;
115874      uniondest.eDest = op;
115875      explainSetInteger(iSub2, pParse->iNextSelectId);
115876      rc = sqlite3Select(pParse, p, &uniondest);
115877      testcase( rc!=SQLITE_OK );
115878      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
115879      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
115880      sqlite3ExprListDelete(db, p->pOrderBy);
115881      pDelete = p->pPrior;
115882      p->pPrior = pPrior;
115883      p->pOrderBy = 0;
115884      if( p->op==TK_UNION ){
115885        p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115886      }
115887      sqlite3ExprDelete(db, p->pLimit);
115888      p->pLimit = pLimit;
115889      p->pOffset = pOffset;
115890      p->iLimit = 0;
115891      p->iOffset = 0;
115892
115893      /* Convert the data in the temporary table into whatever form
115894      ** it is that we currently need.
115895      */
115896      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
115897      if( dest.eDest!=priorOp ){
115898        int iCont, iBreak, iStart;
115899        assert( p->pEList );
115900        if( dest.eDest==SRT_Output ){
115901          Select *pFirst = p;
115902          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115903          generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115904        }
115905        iBreak = sqlite3VdbeMakeLabel(v);
115906        iCont = sqlite3VdbeMakeLabel(v);
115907        computeLimitRegisters(pParse, p, iBreak);
115908        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
115909        iStart = sqlite3VdbeCurrentAddr(v);
115910        selectInnerLoop(pParse, p, p->pEList, unionTab,
115911                        0, 0, &dest, iCont, iBreak);
115912        sqlite3VdbeResolveLabel(v, iCont);
115913        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
115914        sqlite3VdbeResolveLabel(v, iBreak);
115915        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
115916      }
115917      break;
115918    }
115919    default: assert( p->op==TK_INTERSECT ); {
115920      int tab1, tab2;
115921      int iCont, iBreak, iStart;
115922      Expr *pLimit, *pOffset;
115923      int addr;
115924      SelectDest intersectdest;
115925      int r1;
115926
115927      /* INTERSECT is different from the others since it requires
115928      ** two temporary tables.  Hence it has its own case.  Begin
115929      ** by allocating the tables we will need.
115930      */
115931      tab1 = pParse->nTab++;
115932      tab2 = pParse->nTab++;
115933      assert( p->pOrderBy==0 );
115934
115935      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
115936      assert( p->addrOpenEphm[0] == -1 );
115937      p->addrOpenEphm[0] = addr;
115938      findRightmost(p)->selFlags |= SF_UsesEphemeral;
115939      assert( p->pEList );
115940
115941      /* Code the SELECTs to our left into temporary table "tab1".
115942      */
115943      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
115944      explainSetInteger(iSub1, pParse->iNextSelectId);
115945      rc = sqlite3Select(pParse, pPrior, &intersectdest);
115946      if( rc ){
115947        goto multi_select_end;
115948      }
115949
115950      /* Code the current SELECT into temporary table "tab2"
115951      */
115952      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
115953      assert( p->addrOpenEphm[1] == -1 );
115954      p->addrOpenEphm[1] = addr;
115955      p->pPrior = 0;
115956      pLimit = p->pLimit;
115957      p->pLimit = 0;
115958      pOffset = p->pOffset;
115959      p->pOffset = 0;
115960      intersectdest.iSDParm = tab2;
115961      explainSetInteger(iSub2, pParse->iNextSelectId);
115962      rc = sqlite3Select(pParse, p, &intersectdest);
115963      testcase( rc!=SQLITE_OK );
115964      pDelete = p->pPrior;
115965      p->pPrior = pPrior;
115966      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
115967      sqlite3ExprDelete(db, p->pLimit);
115968      p->pLimit = pLimit;
115969      p->pOffset = pOffset;
115970
115971      /* Generate code to take the intersection of the two temporary
115972      ** tables.
115973      */
115974      assert( p->pEList );
115975      if( dest.eDest==SRT_Output ){
115976        Select *pFirst = p;
115977        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115978        generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115979      }
115980      iBreak = sqlite3VdbeMakeLabel(v);
115981      iCont = sqlite3VdbeMakeLabel(v);
115982      computeLimitRegisters(pParse, p, iBreak);
115983      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
115984      r1 = sqlite3GetTempReg(pParse);
115985      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
115986      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
115987      sqlite3ReleaseTempReg(pParse, r1);
115988      selectInnerLoop(pParse, p, p->pEList, tab1,
115989                      0, 0, &dest, iCont, iBreak);
115990      sqlite3VdbeResolveLabel(v, iCont);
115991      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
115992      sqlite3VdbeResolveLabel(v, iBreak);
115993      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
115994      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
115995      break;
115996    }
115997  }
115998
115999  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
116000
116001  /* Compute collating sequences used by
116002  ** temporary tables needed to implement the compound select.
116003  ** Attach the KeyInfo structure to all temporary tables.
116004  **
116005  ** This section is run by the right-most SELECT statement only.
116006  ** SELECT statements to the left always skip this part.  The right-most
116007  ** SELECT might also skip this part if it has no ORDER BY clause and
116008  ** no temp tables are required.
116009  */
116010  if( p->selFlags & SF_UsesEphemeral ){
116011    int i;                        /* Loop counter */
116012    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
116013    Select *pLoop;                /* For looping through SELECT statements */
116014    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
116015    int nCol;                     /* Number of columns in result set */
116016
116017    assert( p->pNext==0 );
116018    nCol = p->pEList->nExpr;
116019    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
116020    if( !pKeyInfo ){
116021      rc = SQLITE_NOMEM_BKPT;
116022      goto multi_select_end;
116023    }
116024    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
116025      *apColl = multiSelectCollSeq(pParse, p, i);
116026      if( 0==*apColl ){
116027        *apColl = db->pDfltColl;
116028      }
116029    }
116030
116031    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
116032      for(i=0; i<2; i++){
116033        int addr = pLoop->addrOpenEphm[i];
116034        if( addr<0 ){
116035          /* If [0] is unused then [1] is also unused.  So we can
116036          ** always safely abort as soon as the first unused slot is found */
116037          assert( pLoop->addrOpenEphm[1]<0 );
116038          break;
116039        }
116040        sqlite3VdbeChangeP2(v, addr, nCol);
116041        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
116042                            P4_KEYINFO);
116043        pLoop->addrOpenEphm[i] = -1;
116044      }
116045    }
116046    sqlite3KeyInfoUnref(pKeyInfo);
116047  }
116048
116049multi_select_end:
116050  pDest->iSdst = dest.iSdst;
116051  pDest->nSdst = dest.nSdst;
116052  sqlite3SelectDelete(db, pDelete);
116053  return rc;
116054}
116055#endif /* SQLITE_OMIT_COMPOUND_SELECT */
116056
116057/*
116058** Error message for when two or more terms of a compound select have different
116059** size result sets.
116060*/
116061SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
116062  if( p->selFlags & SF_Values ){
116063    sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
116064  }else{
116065    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
116066      " do not have the same number of result columns", selectOpName(p->op));
116067  }
116068}
116069
116070/*
116071** Code an output subroutine for a coroutine implementation of a
116072** SELECT statment.
116073**
116074** The data to be output is contained in pIn->iSdst.  There are
116075** pIn->nSdst columns to be output.  pDest is where the output should
116076** be sent.
116077**
116078** regReturn is the number of the register holding the subroutine
116079** return address.
116080**
116081** If regPrev>0 then it is the first register in a vector that
116082** records the previous output.  mem[regPrev] is a flag that is false
116083** if there has been no previous output.  If regPrev>0 then code is
116084** generated to suppress duplicates.  pKeyInfo is used for comparing
116085** keys.
116086**
116087** If the LIMIT found in p->iLimit is reached, jump immediately to
116088** iBreak.
116089*/
116090static int generateOutputSubroutine(
116091  Parse *pParse,          /* Parsing context */
116092  Select *p,              /* The SELECT statement */
116093  SelectDest *pIn,        /* Coroutine supplying data */
116094  SelectDest *pDest,      /* Where to send the data */
116095  int regReturn,          /* The return address register */
116096  int regPrev,            /* Previous result register.  No uniqueness if 0 */
116097  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
116098  int iBreak              /* Jump here if we hit the LIMIT */
116099){
116100  Vdbe *v = pParse->pVdbe;
116101  int iContinue;
116102  int addr;
116103
116104  addr = sqlite3VdbeCurrentAddr(v);
116105  iContinue = sqlite3VdbeMakeLabel(v);
116106
116107  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
116108  */
116109  if( regPrev ){
116110    int addr1, addr2;
116111    addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
116112    addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
116113                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
116114    sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
116115    sqlite3VdbeJumpHere(v, addr1);
116116    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
116117    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
116118  }
116119  if( pParse->db->mallocFailed ) return 0;
116120
116121  /* Suppress the first OFFSET entries if there is an OFFSET clause
116122  */
116123  codeOffset(v, p->iOffset, iContinue);
116124
116125  assert( pDest->eDest!=SRT_Exists );
116126  assert( pDest->eDest!=SRT_Table );
116127  switch( pDest->eDest ){
116128    /* Store the result as data using a unique key.
116129    */
116130    case SRT_EphemTab: {
116131      int r1 = sqlite3GetTempReg(pParse);
116132      int r2 = sqlite3GetTempReg(pParse);
116133      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
116134      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
116135      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
116136      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
116137      sqlite3ReleaseTempReg(pParse, r2);
116138      sqlite3ReleaseTempReg(pParse, r1);
116139      break;
116140    }
116141
116142#ifndef SQLITE_OMIT_SUBQUERY
116143    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
116144    ** then there should be a single item on the stack.  Write this
116145    ** item into the set table with bogus data.
116146    */
116147    case SRT_Set: {
116148      int r1;
116149      assert( pIn->nSdst==1 || pParse->nErr>0 );
116150      pDest->affSdst =
116151         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
116152      r1 = sqlite3GetTempReg(pParse);
116153      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
116154      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
116155      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
116156      sqlite3ReleaseTempReg(pParse, r1);
116157      break;
116158    }
116159
116160    /* If this is a scalar select that is part of an expression, then
116161    ** store the results in the appropriate memory cell and break out
116162    ** of the scan loop.
116163    */
116164    case SRT_Mem: {
116165      assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
116166      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
116167      /* The LIMIT clause will jump out of the loop for us */
116168      break;
116169    }
116170#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
116171
116172    /* The results are stored in a sequence of registers
116173    ** starting at pDest->iSdst.  Then the co-routine yields.
116174    */
116175    case SRT_Coroutine: {
116176      if( pDest->iSdst==0 ){
116177        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
116178        pDest->nSdst = pIn->nSdst;
116179      }
116180      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
116181      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
116182      break;
116183    }
116184
116185    /* If none of the above, then the result destination must be
116186    ** SRT_Output.  This routine is never called with any other
116187    ** destination other than the ones handled above or SRT_Output.
116188    **
116189    ** For SRT_Output, results are stored in a sequence of registers.
116190    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
116191    ** return the next row of result.
116192    */
116193    default: {
116194      assert( pDest->eDest==SRT_Output );
116195      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
116196      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
116197      break;
116198    }
116199  }
116200
116201  /* Jump to the end of the loop if the LIMIT is reached.
116202  */
116203  if( p->iLimit ){
116204    sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
116205  }
116206
116207  /* Generate the subroutine return
116208  */
116209  sqlite3VdbeResolveLabel(v, iContinue);
116210  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
116211
116212  return addr;
116213}
116214
116215/*
116216** Alternative compound select code generator for cases when there
116217** is an ORDER BY clause.
116218**
116219** We assume a query of the following form:
116220**
116221**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
116222**
116223** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
116224** is to code both <selectA> and <selectB> with the ORDER BY clause as
116225** co-routines.  Then run the co-routines in parallel and merge the results
116226** into the output.  In addition to the two coroutines (called selectA and
116227** selectB) there are 7 subroutines:
116228**
116229**    outA:    Move the output of the selectA coroutine into the output
116230**             of the compound query.
116231**
116232**    outB:    Move the output of the selectB coroutine into the output
116233**             of the compound query.  (Only generated for UNION and
116234**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
116235**             appears only in B.)
116236**
116237**    AltB:    Called when there is data from both coroutines and A<B.
116238**
116239**    AeqB:    Called when there is data from both coroutines and A==B.
116240**
116241**    AgtB:    Called when there is data from both coroutines and A>B.
116242**
116243**    EofA:    Called when data is exhausted from selectA.
116244**
116245**    EofB:    Called when data is exhausted from selectB.
116246**
116247** The implementation of the latter five subroutines depend on which
116248** <operator> is used:
116249**
116250**
116251**             UNION ALL         UNION            EXCEPT          INTERSECT
116252**          -------------  -----------------  --------------  -----------------
116253**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
116254**
116255**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
116256**
116257**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
116258**
116259**   EofA:   outB, nextB      outB, nextB          halt             halt
116260**
116261**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
116262**
116263** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
116264** causes an immediate jump to EofA and an EOF on B following nextB causes
116265** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
116266** following nextX causes a jump to the end of the select processing.
116267**
116268** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
116269** within the output subroutine.  The regPrev register set holds the previously
116270** output value.  A comparison is made against this value and the output
116271** is skipped if the next results would be the same as the previous.
116272**
116273** The implementation plan is to implement the two coroutines and seven
116274** subroutines first, then put the control logic at the bottom.  Like this:
116275**
116276**          goto Init
116277**     coA: coroutine for left query (A)
116278**     coB: coroutine for right query (B)
116279**    outA: output one row of A
116280**    outB: output one row of B (UNION and UNION ALL only)
116281**    EofA: ...
116282**    EofB: ...
116283**    AltB: ...
116284**    AeqB: ...
116285**    AgtB: ...
116286**    Init: initialize coroutine registers
116287**          yield coA
116288**          if eof(A) goto EofA
116289**          yield coB
116290**          if eof(B) goto EofB
116291**    Cmpr: Compare A, B
116292**          Jump AltB, AeqB, AgtB
116293**     End: ...
116294**
116295** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
116296** actually called using Gosub and they do not Return.  EofA and EofB loop
116297** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
116298** and AgtB jump to either L2 or to one of EofA or EofB.
116299*/
116300#ifndef SQLITE_OMIT_COMPOUND_SELECT
116301static int multiSelectOrderBy(
116302  Parse *pParse,        /* Parsing context */
116303  Select *p,            /* The right-most of SELECTs to be coded */
116304  SelectDest *pDest     /* What to do with query results */
116305){
116306  int i, j;             /* Loop counters */
116307  Select *pPrior;       /* Another SELECT immediately to our left */
116308  Vdbe *v;              /* Generate code to this VDBE */
116309  SelectDest destA;     /* Destination for coroutine A */
116310  SelectDest destB;     /* Destination for coroutine B */
116311  int regAddrA;         /* Address register for select-A coroutine */
116312  int regAddrB;         /* Address register for select-B coroutine */
116313  int addrSelectA;      /* Address of the select-A coroutine */
116314  int addrSelectB;      /* Address of the select-B coroutine */
116315  int regOutA;          /* Address register for the output-A subroutine */
116316  int regOutB;          /* Address register for the output-B subroutine */
116317  int addrOutA;         /* Address of the output-A subroutine */
116318  int addrOutB = 0;     /* Address of the output-B subroutine */
116319  int addrEofA;         /* Address of the select-A-exhausted subroutine */
116320  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
116321  int addrEofB;         /* Address of the select-B-exhausted subroutine */
116322  int addrAltB;         /* Address of the A<B subroutine */
116323  int addrAeqB;         /* Address of the A==B subroutine */
116324  int addrAgtB;         /* Address of the A>B subroutine */
116325  int regLimitA;        /* Limit register for select-A */
116326  int regLimitB;        /* Limit register for select-A */
116327  int regPrev;          /* A range of registers to hold previous output */
116328  int savedLimit;       /* Saved value of p->iLimit */
116329  int savedOffset;      /* Saved value of p->iOffset */
116330  int labelCmpr;        /* Label for the start of the merge algorithm */
116331  int labelEnd;         /* Label for the end of the overall SELECT stmt */
116332  int addr1;            /* Jump instructions that get retargetted */
116333  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
116334  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
116335  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
116336  sqlite3 *db;          /* Database connection */
116337  ExprList *pOrderBy;   /* The ORDER BY clause */
116338  int nOrderBy;         /* Number of terms in the ORDER BY clause */
116339  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
116340#ifndef SQLITE_OMIT_EXPLAIN
116341  int iSub1;            /* EQP id of left-hand query */
116342  int iSub2;            /* EQP id of right-hand query */
116343#endif
116344
116345  assert( p->pOrderBy!=0 );
116346  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
116347  db = pParse->db;
116348  v = pParse->pVdbe;
116349  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
116350  labelEnd = sqlite3VdbeMakeLabel(v);
116351  labelCmpr = sqlite3VdbeMakeLabel(v);
116352
116353
116354  /* Patch up the ORDER BY clause
116355  */
116356  op = p->op;
116357  pPrior = p->pPrior;
116358  assert( pPrior->pOrderBy==0 );
116359  pOrderBy = p->pOrderBy;
116360  assert( pOrderBy );
116361  nOrderBy = pOrderBy->nExpr;
116362
116363  /* For operators other than UNION ALL we have to make sure that
116364  ** the ORDER BY clause covers every term of the result set.  Add
116365  ** terms to the ORDER BY clause as necessary.
116366  */
116367  if( op!=TK_ALL ){
116368    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
116369      struct ExprList_item *pItem;
116370      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
116371        assert( pItem->u.x.iOrderByCol>0 );
116372        if( pItem->u.x.iOrderByCol==i ) break;
116373      }
116374      if( j==nOrderBy ){
116375        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
116376        if( pNew==0 ) return SQLITE_NOMEM_BKPT;
116377        pNew->flags |= EP_IntValue;
116378        pNew->u.iValue = i;
116379        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
116380        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
116381      }
116382    }
116383  }
116384
116385  /* Compute the comparison permutation and keyinfo that is used with
116386  ** the permutation used to determine if the next
116387  ** row of results comes from selectA or selectB.  Also add explicit
116388  ** collations to the ORDER BY clause terms so that when the subqueries
116389  ** to the right and the left are evaluated, they use the correct
116390  ** collation.
116391  */
116392  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
116393  if( aPermute ){
116394    struct ExprList_item *pItem;
116395    aPermute[0] = nOrderBy;
116396    for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
116397      assert( pItem->u.x.iOrderByCol>0 );
116398      assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
116399      aPermute[i] = pItem->u.x.iOrderByCol - 1;
116400    }
116401    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
116402  }else{
116403    pKeyMerge = 0;
116404  }
116405
116406  /* Reattach the ORDER BY clause to the query.
116407  */
116408  p->pOrderBy = pOrderBy;
116409  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
116410
116411  /* Allocate a range of temporary registers and the KeyInfo needed
116412  ** for the logic that removes duplicate result rows when the
116413  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
116414  */
116415  if( op==TK_ALL ){
116416    regPrev = 0;
116417  }else{
116418    int nExpr = p->pEList->nExpr;
116419    assert( nOrderBy>=nExpr || db->mallocFailed );
116420    regPrev = pParse->nMem+1;
116421    pParse->nMem += nExpr+1;
116422    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
116423    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
116424    if( pKeyDup ){
116425      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
116426      for(i=0; i<nExpr; i++){
116427        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
116428        pKeyDup->aSortOrder[i] = 0;
116429      }
116430    }
116431  }
116432
116433  /* Separate the left and the right query from one another
116434  */
116435  p->pPrior = 0;
116436  pPrior->pNext = 0;
116437  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
116438  if( pPrior->pPrior==0 ){
116439    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
116440  }
116441
116442  /* Compute the limit registers */
116443  computeLimitRegisters(pParse, p, labelEnd);
116444  if( p->iLimit && op==TK_ALL ){
116445    regLimitA = ++pParse->nMem;
116446    regLimitB = ++pParse->nMem;
116447    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
116448                                  regLimitA);
116449    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
116450  }else{
116451    regLimitA = regLimitB = 0;
116452  }
116453  sqlite3ExprDelete(db, p->pLimit);
116454  p->pLimit = 0;
116455  sqlite3ExprDelete(db, p->pOffset);
116456  p->pOffset = 0;
116457
116458  regAddrA = ++pParse->nMem;
116459  regAddrB = ++pParse->nMem;
116460  regOutA = ++pParse->nMem;
116461  regOutB = ++pParse->nMem;
116462  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
116463  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
116464
116465  /* Generate a coroutine to evaluate the SELECT statement to the
116466  ** left of the compound operator - the "A" select.
116467  */
116468  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
116469  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
116470  VdbeComment((v, "left SELECT"));
116471  pPrior->iLimit = regLimitA;
116472  explainSetInteger(iSub1, pParse->iNextSelectId);
116473  sqlite3Select(pParse, pPrior, &destA);
116474  sqlite3VdbeEndCoroutine(v, regAddrA);
116475  sqlite3VdbeJumpHere(v, addr1);
116476
116477  /* Generate a coroutine to evaluate the SELECT statement on
116478  ** the right - the "B" select
116479  */
116480  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
116481  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
116482  VdbeComment((v, "right SELECT"));
116483  savedLimit = p->iLimit;
116484  savedOffset = p->iOffset;
116485  p->iLimit = regLimitB;
116486  p->iOffset = 0;
116487  explainSetInteger(iSub2, pParse->iNextSelectId);
116488  sqlite3Select(pParse, p, &destB);
116489  p->iLimit = savedLimit;
116490  p->iOffset = savedOffset;
116491  sqlite3VdbeEndCoroutine(v, regAddrB);
116492
116493  /* Generate a subroutine that outputs the current row of the A
116494  ** select as the next output row of the compound select.
116495  */
116496  VdbeNoopComment((v, "Output routine for A"));
116497  addrOutA = generateOutputSubroutine(pParse,
116498                 p, &destA, pDest, regOutA,
116499                 regPrev, pKeyDup, labelEnd);
116500
116501  /* Generate a subroutine that outputs the current row of the B
116502  ** select as the next output row of the compound select.
116503  */
116504  if( op==TK_ALL || op==TK_UNION ){
116505    VdbeNoopComment((v, "Output routine for B"));
116506    addrOutB = generateOutputSubroutine(pParse,
116507                 p, &destB, pDest, regOutB,
116508                 regPrev, pKeyDup, labelEnd);
116509  }
116510  sqlite3KeyInfoUnref(pKeyDup);
116511
116512  /* Generate a subroutine to run when the results from select A
116513  ** are exhausted and only data in select B remains.
116514  */
116515  if( op==TK_EXCEPT || op==TK_INTERSECT ){
116516    addrEofA_noB = addrEofA = labelEnd;
116517  }else{
116518    VdbeNoopComment((v, "eof-A subroutine"));
116519    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
116520    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
116521                                     VdbeCoverage(v);
116522    sqlite3VdbeGoto(v, addrEofA);
116523    p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116524  }
116525
116526  /* Generate a subroutine to run when the results from select B
116527  ** are exhausted and only data in select A remains.
116528  */
116529  if( op==TK_INTERSECT ){
116530    addrEofB = addrEofA;
116531    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
116532  }else{
116533    VdbeNoopComment((v, "eof-B subroutine"));
116534    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
116535    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
116536    sqlite3VdbeGoto(v, addrEofB);
116537  }
116538
116539  /* Generate code to handle the case of A<B
116540  */
116541  VdbeNoopComment((v, "A-lt-B subroutine"));
116542  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
116543  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
116544  sqlite3VdbeGoto(v, labelCmpr);
116545
116546  /* Generate code to handle the case of A==B
116547  */
116548  if( op==TK_ALL ){
116549    addrAeqB = addrAltB;
116550  }else if( op==TK_INTERSECT ){
116551    addrAeqB = addrAltB;
116552    addrAltB++;
116553  }else{
116554    VdbeNoopComment((v, "A-eq-B subroutine"));
116555    addrAeqB =
116556    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
116557    sqlite3VdbeGoto(v, labelCmpr);
116558  }
116559
116560  /* Generate code to handle the case of A>B
116561  */
116562  VdbeNoopComment((v, "A-gt-B subroutine"));
116563  addrAgtB = sqlite3VdbeCurrentAddr(v);
116564  if( op==TK_ALL || op==TK_UNION ){
116565    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
116566  }
116567  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
116568  sqlite3VdbeGoto(v, labelCmpr);
116569
116570  /* This code runs once to initialize everything.
116571  */
116572  sqlite3VdbeJumpHere(v, addr1);
116573  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
116574  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
116575
116576  /* Implement the main merge loop
116577  */
116578  sqlite3VdbeResolveLabel(v, labelCmpr);
116579  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
116580  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
116581                         (char*)pKeyMerge, P4_KEYINFO);
116582  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
116583  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
116584
116585  /* Jump to the this point in order to terminate the query.
116586  */
116587  sqlite3VdbeResolveLabel(v, labelEnd);
116588
116589  /* Set the number of output columns
116590  */
116591  if( pDest->eDest==SRT_Output ){
116592    Select *pFirst = pPrior;
116593    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116594    generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116595  }
116596
116597  /* Reassembly the compound query so that it will be freed correctly
116598  ** by the calling function */
116599  if( p->pPrior ){
116600    sqlite3SelectDelete(db, p->pPrior);
116601  }
116602  p->pPrior = pPrior;
116603  pPrior->pNext = p;
116604
116605  /*** TBD:  Insert subroutine calls to close cursors on incomplete
116606  **** subqueries ****/
116607  explainComposite(pParse, p->op, iSub1, iSub2, 0);
116608  return pParse->nErr!=0;
116609}
116610#endif
116611
116612#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116613/* Forward Declarations */
116614static void substExprList(sqlite3*, ExprList*, int, ExprList*);
116615static void substSelect(sqlite3*, Select *, int, ExprList*, int);
116616
116617/*
116618** Scan through the expression pExpr.  Replace every reference to
116619** a column in table number iTable with a copy of the iColumn-th
116620** entry in pEList.  (But leave references to the ROWID column
116621** unchanged.)
116622**
116623** This routine is part of the flattening procedure.  A subquery
116624** whose result set is defined by pEList appears as entry in the
116625** FROM clause of a SELECT such that the VDBE cursor assigned to that
116626** FORM clause entry is iTable.  This routine make the necessary
116627** changes to pExpr so that it refers directly to the source table
116628** of the subquery rather the result set of the subquery.
116629*/
116630static Expr *substExpr(
116631  sqlite3 *db,        /* Report malloc errors to this connection */
116632  Expr *pExpr,        /* Expr in which substitution occurs */
116633  int iTable,         /* Table to be substituted */
116634  ExprList *pEList    /* Substitute expressions */
116635){
116636  if( pExpr==0 ) return 0;
116637  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
116638    if( pExpr->iColumn<0 ){
116639      pExpr->op = TK_NULL;
116640    }else{
116641      Expr *pNew;
116642      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
116643      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
116644      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
116645      sqlite3ExprDelete(db, pExpr);
116646      pExpr = pNew;
116647    }
116648  }else{
116649    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
116650    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
116651    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
116652      substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
116653    }else{
116654      substExprList(db, pExpr->x.pList, iTable, pEList);
116655    }
116656  }
116657  return pExpr;
116658}
116659static void substExprList(
116660  sqlite3 *db,         /* Report malloc errors here */
116661  ExprList *pList,     /* List to scan and in which to make substitutes */
116662  int iTable,          /* Table to be substituted */
116663  ExprList *pEList     /* Substitute values */
116664){
116665  int i;
116666  if( pList==0 ) return;
116667  for(i=0; i<pList->nExpr; i++){
116668    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
116669  }
116670}
116671static void substSelect(
116672  sqlite3 *db,         /* Report malloc errors here */
116673  Select *p,           /* SELECT statement in which to make substitutions */
116674  int iTable,          /* Table to be replaced */
116675  ExprList *pEList,    /* Substitute values */
116676  int doPrior          /* Do substitutes on p->pPrior too */
116677){
116678  SrcList *pSrc;
116679  struct SrcList_item *pItem;
116680  int i;
116681  if( !p ) return;
116682  do{
116683    substExprList(db, p->pEList, iTable, pEList);
116684    substExprList(db, p->pGroupBy, iTable, pEList);
116685    substExprList(db, p->pOrderBy, iTable, pEList);
116686    p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
116687    p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
116688    pSrc = p->pSrc;
116689    assert( pSrc!=0 );
116690    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
116691      substSelect(db, pItem->pSelect, iTable, pEList, 1);
116692      if( pItem->fg.isTabFunc ){
116693        substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
116694      }
116695    }
116696  }while( doPrior && (p = p->pPrior)!=0 );
116697}
116698#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
116699
116700#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116701/*
116702** This routine attempts to flatten subqueries as a performance optimization.
116703** This routine returns 1 if it makes changes and 0 if no flattening occurs.
116704**
116705** To understand the concept of flattening, consider the following
116706** query:
116707**
116708**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
116709**
116710** The default way of implementing this query is to execute the
116711** subquery first and store the results in a temporary table, then
116712** run the outer query on that temporary table.  This requires two
116713** passes over the data.  Furthermore, because the temporary table
116714** has no indices, the WHERE clause on the outer query cannot be
116715** optimized.
116716**
116717** This routine attempts to rewrite queries such as the above into
116718** a single flat select, like this:
116719**
116720**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
116721**
116722** The code generated for this simplification gives the same result
116723** but only has to scan the data once.  And because indices might
116724** exist on the table t1, a complete scan of the data might be
116725** avoided.
116726**
116727** Flattening is only attempted if all of the following are true:
116728**
116729**   (1)  The subquery and the outer query do not both use aggregates.
116730**
116731**   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
116732**        and (2b) the outer query does not use subqueries other than the one
116733**        FROM-clause subquery that is a candidate for flattening.  (2b is
116734**        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
116735**
116736**   (3)  The subquery is not the right operand of a left outer join
116737**        (Originally ticket #306.  Strengthened by ticket #3300)
116738**
116739**   (4)  The subquery is not DISTINCT.
116740**
116741**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
116742**        sub-queries that were excluded from this optimization. Restriction
116743**        (4) has since been expanded to exclude all DISTINCT subqueries.
116744**
116745**   (6)  The subquery does not use aggregates or the outer query is not
116746**        DISTINCT.
116747**
116748**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
116749**        A FROM clause, consider adding a FROM close with the special
116750**        table sqlite_once that consists of a single row containing a
116751**        single NULL.
116752**
116753**   (8)  The subquery does not use LIMIT or the outer query is not a join.
116754**
116755**   (9)  The subquery does not use LIMIT or the outer query does not use
116756**        aggregates.
116757**
116758**  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
116759**        accidently carried the comment forward until 2014-09-15.  Original
116760**        text: "The subquery does not use aggregates or the outer query
116761**        does not use LIMIT."
116762**
116763**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
116764**
116765**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
116766**        a separate restriction deriving from ticket #350.
116767**
116768**  (13)  The subquery and outer query do not both use LIMIT.
116769**
116770**  (14)  The subquery does not use OFFSET.
116771**
116772**  (15)  The outer query is not part of a compound select or the
116773**        subquery does not have a LIMIT clause.
116774**        (See ticket #2339 and ticket [02a8e81d44]).
116775**
116776**  (16)  The outer query is not an aggregate or the subquery does
116777**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
116778**        until we introduced the group_concat() function.
116779**
116780**  (17)  The sub-query is not a compound select, or it is a UNION ALL
116781**        compound clause made up entirely of non-aggregate queries, and
116782**        the parent query:
116783**
116784**          * is not itself part of a compound select,
116785**          * is not an aggregate or DISTINCT query, and
116786**          * is not a join
116787**
116788**        The parent and sub-query may contain WHERE clauses. Subject to
116789**        rules (11), (13) and (14), they may also contain ORDER BY,
116790**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
116791**        operator other than UNION ALL because all the other compound
116792**        operators have an implied DISTINCT which is disallowed by
116793**        restriction (4).
116794**
116795**        Also, each component of the sub-query must return the same number
116796**        of result columns. This is actually a requirement for any compound
116797**        SELECT statement, but all the code here does is make sure that no
116798**        such (illegal) sub-query is flattened. The caller will detect the
116799**        syntax error and return a detailed message.
116800**
116801**  (18)  If the sub-query is a compound select, then all terms of the
116802**        ORDER by clause of the parent must be simple references to
116803**        columns of the sub-query.
116804**
116805**  (19)  The subquery does not use LIMIT or the outer query does not
116806**        have a WHERE clause.
116807**
116808**  (20)  If the sub-query is a compound select, then it must not use
116809**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
116810**        somewhat by saying that the terms of the ORDER BY clause must
116811**        appear as unmodified result columns in the outer query.  But we
116812**        have other optimizations in mind to deal with that case.
116813**
116814**  (21)  The subquery does not use LIMIT or the outer query is not
116815**        DISTINCT.  (See ticket [752e1646fc]).
116816**
116817**  (22)  The subquery is not a recursive CTE.
116818**
116819**  (23)  The parent is not a recursive CTE, or the sub-query is not a
116820**        compound query. This restriction is because transforming the
116821**        parent to a compound query confuses the code that handles
116822**        recursive queries in multiSelect().
116823**
116824**  (24)  The subquery is not an aggregate that uses the built-in min() or
116825**        or max() functions.  (Without this restriction, a query like:
116826**        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
116827**        return the value X for which Y was maximal.)
116828**
116829**
116830** In this routine, the "p" parameter is a pointer to the outer query.
116831** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
116832** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
116833**
116834** If flattening is not attempted, this routine is a no-op and returns 0.
116835** If flattening is attempted this routine returns 1.
116836**
116837** All of the expression analysis must occur on both the outer query and
116838** the subquery before this routine runs.
116839*/
116840static int flattenSubquery(
116841  Parse *pParse,       /* Parsing context */
116842  Select *p,           /* The parent or outer SELECT statement */
116843  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
116844  int isAgg,           /* True if outer SELECT uses aggregate functions */
116845  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
116846){
116847  const char *zSavedAuthContext = pParse->zAuthContext;
116848  Select *pParent;    /* Current UNION ALL term of the other query */
116849  Select *pSub;       /* The inner query or "subquery" */
116850  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
116851  SrcList *pSrc;      /* The FROM clause of the outer query */
116852  SrcList *pSubSrc;   /* The FROM clause of the subquery */
116853  ExprList *pList;    /* The result set of the outer query */
116854  int iParent;        /* VDBE cursor number of the pSub result set temp table */
116855  int i;              /* Loop counter */
116856  Expr *pWhere;                    /* The WHERE clause */
116857  struct SrcList_item *pSubitem;   /* The subquery */
116858  sqlite3 *db = pParse->db;
116859
116860  /* Check to see if flattening is permitted.  Return 0 if not.
116861  */
116862  assert( p!=0 );
116863  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
116864  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
116865  pSrc = p->pSrc;
116866  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
116867  pSubitem = &pSrc->a[iFrom];
116868  iParent = pSubitem->iCursor;
116869  pSub = pSubitem->pSelect;
116870  assert( pSub!=0 );
116871  if( subqueryIsAgg ){
116872    if( isAgg ) return 0;                                /* Restriction (1)   */
116873    if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
116874    if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
116875     || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
116876     || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
116877    ){
116878      return 0;                                          /* Restriction (2b)  */
116879    }
116880  }
116881
116882  pSubSrc = pSub->pSrc;
116883  assert( pSubSrc );
116884  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
116885  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
116886  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
116887  ** became arbitrary expressions, we were forced to add restrictions (13)
116888  ** and (14). */
116889  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
116890  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
116891  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
116892    return 0;                                            /* Restriction (15) */
116893  }
116894  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
116895  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
116896  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
116897     return 0;         /* Restrictions (8)(9) */
116898  }
116899  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
116900     return 0;         /* Restriction (6)  */
116901  }
116902  if( p->pOrderBy && pSub->pOrderBy ){
116903     return 0;                                           /* Restriction (11) */
116904  }
116905  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
116906  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
116907  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
116908     return 0;         /* Restriction (21) */
116909  }
116910  testcase( pSub->selFlags & SF_Recursive );
116911  testcase( pSub->selFlags & SF_MinMaxAgg );
116912  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
116913    return 0; /* Restrictions (22) and (24) */
116914  }
116915  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
116916    return 0; /* Restriction (23) */
116917  }
116918
116919  /* OBSOLETE COMMENT 1:
116920  ** Restriction 3:  If the subquery is a join, make sure the subquery is
116921  ** not used as the right operand of an outer join.  Examples of why this
116922  ** is not allowed:
116923  **
116924  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
116925  **
116926  ** If we flatten the above, we would get
116927  **
116928  **         (t1 LEFT OUTER JOIN t2) JOIN t3
116929  **
116930  ** which is not at all the same thing.
116931  **
116932  ** OBSOLETE COMMENT 2:
116933  ** Restriction 12:  If the subquery is the right operand of a left outer
116934  ** join, make sure the subquery has no WHERE clause.
116935  ** An examples of why this is not allowed:
116936  **
116937  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
116938  **
116939  ** If we flatten the above, we would get
116940  **
116941  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
116942  **
116943  ** But the t2.x>0 test will always fail on a NULL row of t2, which
116944  ** effectively converts the OUTER JOIN into an INNER JOIN.
116945  **
116946  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
116947  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
116948  ** is fraught with danger.  Best to avoid the whole thing.  If the
116949  ** subquery is the right term of a LEFT JOIN, then do not flatten.
116950  */
116951  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
116952    return 0;
116953  }
116954
116955  /* Restriction 17: If the sub-query is a compound SELECT, then it must
116956  ** use only the UNION ALL operator. And none of the simple select queries
116957  ** that make up the compound SELECT are allowed to be aggregate or distinct
116958  ** queries.
116959  */
116960  if( pSub->pPrior ){
116961    if( pSub->pOrderBy ){
116962      return 0;  /* Restriction 20 */
116963    }
116964    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
116965      return 0;
116966    }
116967    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
116968      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
116969      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
116970      assert( pSub->pSrc!=0 );
116971      assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
116972      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
116973       || (pSub1->pPrior && pSub1->op!=TK_ALL)
116974       || pSub1->pSrc->nSrc<1
116975      ){
116976        return 0;
116977      }
116978      testcase( pSub1->pSrc->nSrc>1 );
116979    }
116980
116981    /* Restriction 18. */
116982    if( p->pOrderBy ){
116983      int ii;
116984      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
116985        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
116986      }
116987    }
116988  }
116989
116990  /***** If we reach this point, flattening is permitted. *****/
116991  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
116992                   pSub->zSelName, pSub, iFrom));
116993
116994  /* Authorize the subquery */
116995  pParse->zAuthContext = pSubitem->zName;
116996  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
116997  testcase( i==SQLITE_DENY );
116998  pParse->zAuthContext = zSavedAuthContext;
116999
117000  /* If the sub-query is a compound SELECT statement, then (by restrictions
117001  ** 17 and 18 above) it must be a UNION ALL and the parent query must
117002  ** be of the form:
117003  **
117004  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
117005  **
117006  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
117007  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
117008  ** OFFSET clauses and joins them to the left-hand-side of the original
117009  ** using UNION ALL operators. In this case N is the number of simple
117010  ** select statements in the compound sub-query.
117011  **
117012  ** Example:
117013  **
117014  **     SELECT a+1 FROM (
117015  **        SELECT x FROM tab
117016  **        UNION ALL
117017  **        SELECT y FROM tab
117018  **        UNION ALL
117019  **        SELECT abs(z*2) FROM tab2
117020  **     ) WHERE a!=5 ORDER BY 1
117021  **
117022  ** Transformed into:
117023  **
117024  **     SELECT x+1 FROM tab WHERE x+1!=5
117025  **     UNION ALL
117026  **     SELECT y+1 FROM tab WHERE y+1!=5
117027  **     UNION ALL
117028  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
117029  **     ORDER BY 1
117030  **
117031  ** We call this the "compound-subquery flattening".
117032  */
117033  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
117034    Select *pNew;
117035    ExprList *pOrderBy = p->pOrderBy;
117036    Expr *pLimit = p->pLimit;
117037    Expr *pOffset = p->pOffset;
117038    Select *pPrior = p->pPrior;
117039    p->pOrderBy = 0;
117040    p->pSrc = 0;
117041    p->pPrior = 0;
117042    p->pLimit = 0;
117043    p->pOffset = 0;
117044    pNew = sqlite3SelectDup(db, p, 0);
117045    sqlite3SelectSetName(pNew, pSub->zSelName);
117046    p->pOffset = pOffset;
117047    p->pLimit = pLimit;
117048    p->pOrderBy = pOrderBy;
117049    p->pSrc = pSrc;
117050    p->op = TK_ALL;
117051    if( pNew==0 ){
117052      p->pPrior = pPrior;
117053    }else{
117054      pNew->pPrior = pPrior;
117055      if( pPrior ) pPrior->pNext = pNew;
117056      pNew->pNext = p;
117057      p->pPrior = pNew;
117058      SELECTTRACE(2,pParse,p,
117059         ("compound-subquery flattener creates %s.%p as peer\n",
117060         pNew->zSelName, pNew));
117061    }
117062    if( db->mallocFailed ) return 1;
117063  }
117064
117065  /* Begin flattening the iFrom-th entry of the FROM clause
117066  ** in the outer query.
117067  */
117068  pSub = pSub1 = pSubitem->pSelect;
117069
117070  /* Delete the transient table structure associated with the
117071  ** subquery
117072  */
117073  sqlite3DbFree(db, pSubitem->zDatabase);
117074  sqlite3DbFree(db, pSubitem->zName);
117075  sqlite3DbFree(db, pSubitem->zAlias);
117076  pSubitem->zDatabase = 0;
117077  pSubitem->zName = 0;
117078  pSubitem->zAlias = 0;
117079  pSubitem->pSelect = 0;
117080
117081  /* Defer deleting the Table object associated with the
117082  ** subquery until code generation is
117083  ** complete, since there may still exist Expr.pTab entries that
117084  ** refer to the subquery even after flattening.  Ticket #3346.
117085  **
117086  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
117087  */
117088  if( ALWAYS(pSubitem->pTab!=0) ){
117089    Table *pTabToDel = pSubitem->pTab;
117090    if( pTabToDel->nRef==1 ){
117091      Parse *pToplevel = sqlite3ParseToplevel(pParse);
117092      pTabToDel->pNextZombie = pToplevel->pZombieTab;
117093      pToplevel->pZombieTab = pTabToDel;
117094    }else{
117095      pTabToDel->nRef--;
117096    }
117097    pSubitem->pTab = 0;
117098  }
117099
117100  /* The following loop runs once for each term in a compound-subquery
117101  ** flattening (as described above).  If we are doing a different kind
117102  ** of flattening - a flattening other than a compound-subquery flattening -
117103  ** then this loop only runs once.
117104  **
117105  ** This loop moves all of the FROM elements of the subquery into the
117106  ** the FROM clause of the outer query.  Before doing this, remember
117107  ** the cursor number for the original outer query FROM element in
117108  ** iParent.  The iParent cursor will never be used.  Subsequent code
117109  ** will scan expressions looking for iParent references and replace
117110  ** those references with expressions that resolve to the subquery FROM
117111  ** elements we are now copying in.
117112  */
117113  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
117114    int nSubSrc;
117115    u8 jointype = 0;
117116    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
117117    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
117118    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
117119
117120    if( pSrc ){
117121      assert( pParent==p );  /* First time through the loop */
117122      jointype = pSubitem->fg.jointype;
117123    }else{
117124      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
117125      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
117126      if( pSrc==0 ){
117127        assert( db->mallocFailed );
117128        break;
117129      }
117130    }
117131
117132    /* The subquery uses a single slot of the FROM clause of the outer
117133    ** query.  If the subquery has more than one element in its FROM clause,
117134    ** then expand the outer query to make space for it to hold all elements
117135    ** of the subquery.
117136    **
117137    ** Example:
117138    **
117139    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
117140    **
117141    ** The outer query has 3 slots in its FROM clause.  One slot of the
117142    ** outer query (the middle slot) is used by the subquery.  The next
117143    ** block of code will expand the outer query FROM clause to 4 slots.
117144    ** The middle slot is expanded to two slots in order to make space
117145    ** for the two elements in the FROM clause of the subquery.
117146    */
117147    if( nSubSrc>1 ){
117148      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
117149      if( db->mallocFailed ){
117150        break;
117151      }
117152    }
117153
117154    /* Transfer the FROM clause terms from the subquery into the
117155    ** outer query.
117156    */
117157    for(i=0; i<nSubSrc; i++){
117158      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
117159      assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
117160      pSrc->a[i+iFrom] = pSubSrc->a[i];
117161      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
117162    }
117163    pSrc->a[iFrom].fg.jointype = jointype;
117164
117165    /* Now begin substituting subquery result set expressions for
117166    ** references to the iParent in the outer query.
117167    **
117168    ** Example:
117169    **
117170    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
117171    **   \                     \_____________ subquery __________/          /
117172    **    \_____________________ outer query ______________________________/
117173    **
117174    ** We look at every expression in the outer query and every place we see
117175    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
117176    */
117177    pList = pParent->pEList;
117178    for(i=0; i<pList->nExpr; i++){
117179      if( pList->a[i].zName==0 ){
117180        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
117181        sqlite3Dequote(zName);
117182        pList->a[i].zName = zName;
117183      }
117184    }
117185    if( pSub->pOrderBy ){
117186      /* At this point, any non-zero iOrderByCol values indicate that the
117187      ** ORDER BY column expression is identical to the iOrderByCol'th
117188      ** expression returned by SELECT statement pSub. Since these values
117189      ** do not necessarily correspond to columns in SELECT statement pParent,
117190      ** zero them before transfering the ORDER BY clause.
117191      **
117192      ** Not doing this may cause an error if a subsequent call to this
117193      ** function attempts to flatten a compound sub-query into pParent
117194      ** (the only way this can happen is if the compound sub-query is
117195      ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
117196      ExprList *pOrderBy = pSub->pOrderBy;
117197      for(i=0; i<pOrderBy->nExpr; i++){
117198        pOrderBy->a[i].u.x.iOrderByCol = 0;
117199      }
117200      assert( pParent->pOrderBy==0 );
117201      assert( pSub->pPrior==0 );
117202      pParent->pOrderBy = pOrderBy;
117203      pSub->pOrderBy = 0;
117204    }
117205    pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
117206    if( subqueryIsAgg ){
117207      assert( pParent->pHaving==0 );
117208      pParent->pHaving = pParent->pWhere;
117209      pParent->pWhere = pWhere;
117210      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
117211                                  sqlite3ExprDup(db, pSub->pHaving, 0));
117212      assert( pParent->pGroupBy==0 );
117213      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
117214    }else{
117215      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
117216    }
117217    substSelect(db, pParent, iParent, pSub->pEList, 0);
117218
117219    /* The flattened query is distinct if either the inner or the
117220    ** outer query is distinct.
117221    */
117222    pParent->selFlags |= pSub->selFlags & SF_Distinct;
117223
117224    /*
117225    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
117226    **
117227    ** One is tempted to try to add a and b to combine the limits.  But this
117228    ** does not work if either limit is negative.
117229    */
117230    if( pSub->pLimit ){
117231      pParent->pLimit = pSub->pLimit;
117232      pSub->pLimit = 0;
117233    }
117234  }
117235
117236  /* Finially, delete what is left of the subquery and return
117237  ** success.
117238  */
117239  sqlite3SelectDelete(db, pSub1);
117240
117241#if SELECTTRACE_ENABLED
117242  if( sqlite3SelectTrace & 0x100 ){
117243    SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
117244    sqlite3TreeViewSelect(0, p, 0);
117245  }
117246#endif
117247
117248  return 1;
117249}
117250#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117251
117252
117253
117254#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117255/*
117256** Make copies of relevant WHERE clause terms of the outer query into
117257** the WHERE clause of subquery.  Example:
117258**
117259**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
117260**
117261** Transformed into:
117262**
117263**    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
117264**     WHERE x=5 AND y=10;
117265**
117266** The hope is that the terms added to the inner query will make it more
117267** efficient.
117268**
117269** Do not attempt this optimization if:
117270**
117271**   (1) The inner query is an aggregate.  (In that case, we'd really want
117272**       to copy the outer WHERE-clause terms onto the HAVING clause of the
117273**       inner query.  But they probably won't help there so do not bother.)
117274**
117275**   (2) The inner query is the recursive part of a common table expression.
117276**
117277**   (3) The inner query has a LIMIT clause (since the changes to the WHERE
117278**       close would change the meaning of the LIMIT).
117279**
117280**   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
117281**       enforces this restriction since this routine does not have enough
117282**       information to know.)
117283**
117284**   (5) The WHERE clause expression originates in the ON or USING clause
117285**       of a LEFT JOIN.
117286**
117287** Return 0 if no changes are made and non-zero if one or more WHERE clause
117288** terms are duplicated into the subquery.
117289*/
117290static int pushDownWhereTerms(
117291  sqlite3 *db,          /* The database connection (for malloc()) */
117292  Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
117293  Expr *pWhere,         /* The WHERE clause of the outer query */
117294  int iCursor           /* Cursor number of the subquery */
117295){
117296  Expr *pNew;
117297  int nChng = 0;
117298  Select *pX;           /* For looping over compound SELECTs in pSubq */
117299  if( pWhere==0 ) return 0;
117300  for(pX=pSubq; pX; pX=pX->pPrior){
117301    if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
117302      testcase( pX->selFlags & SF_Aggregate );
117303      testcase( pX->selFlags & SF_Recursive );
117304      testcase( pX!=pSubq );
117305      return 0; /* restrictions (1) and (2) */
117306    }
117307  }
117308  if( pSubq->pLimit!=0 ){
117309    return 0; /* restriction (3) */
117310  }
117311  while( pWhere->op==TK_AND ){
117312    nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
117313    pWhere = pWhere->pLeft;
117314  }
117315  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
117316  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
117317    nChng++;
117318    while( pSubq ){
117319      pNew = sqlite3ExprDup(db, pWhere, 0);
117320      pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
117321      pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
117322      pSubq = pSubq->pPrior;
117323    }
117324  }
117325  return nChng;
117326}
117327#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117328
117329/*
117330** Based on the contents of the AggInfo structure indicated by the first
117331** argument, this function checks if the following are true:
117332**
117333**    * the query contains just a single aggregate function,
117334**    * the aggregate function is either min() or max(), and
117335**    * the argument to the aggregate function is a column value.
117336**
117337** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
117338** is returned as appropriate. Also, *ppMinMax is set to point to the
117339** list of arguments passed to the aggregate before returning.
117340**
117341** Or, if the conditions above are not met, *ppMinMax is set to 0 and
117342** WHERE_ORDERBY_NORMAL is returned.
117343*/
117344static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
117345  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
117346
117347  *ppMinMax = 0;
117348  if( pAggInfo->nFunc==1 ){
117349    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
117350    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
117351
117352    assert( pExpr->op==TK_AGG_FUNCTION );
117353    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
117354      const char *zFunc = pExpr->u.zToken;
117355      if( sqlite3StrICmp(zFunc, "min")==0 ){
117356        eRet = WHERE_ORDERBY_MIN;
117357        *ppMinMax = pEList;
117358      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
117359        eRet = WHERE_ORDERBY_MAX;
117360        *ppMinMax = pEList;
117361      }
117362    }
117363  }
117364
117365  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
117366  return eRet;
117367}
117368
117369/*
117370** The select statement passed as the first argument is an aggregate query.
117371** The second argument is the associated aggregate-info object. This
117372** function tests if the SELECT is of the form:
117373**
117374**   SELECT count(*) FROM <tbl>
117375**
117376** where table is a database table, not a sub-select or view. If the query
117377** does match this pattern, then a pointer to the Table object representing
117378** <tbl> is returned. Otherwise, 0 is returned.
117379*/
117380static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
117381  Table *pTab;
117382  Expr *pExpr;
117383
117384  assert( !p->pGroupBy );
117385
117386  if( p->pWhere || p->pEList->nExpr!=1
117387   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
117388  ){
117389    return 0;
117390  }
117391  pTab = p->pSrc->a[0].pTab;
117392  pExpr = p->pEList->a[0].pExpr;
117393  assert( pTab && !pTab->pSelect && pExpr );
117394
117395  if( IsVirtual(pTab) ) return 0;
117396  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
117397  if( NEVER(pAggInfo->nFunc==0) ) return 0;
117398  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
117399  if( pExpr->flags&EP_Distinct ) return 0;
117400
117401  return pTab;
117402}
117403
117404/*
117405** If the source-list item passed as an argument was augmented with an
117406** INDEXED BY clause, then try to locate the specified index. If there
117407** was such a clause and the named index cannot be found, return
117408** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
117409** pFrom->pIndex and return SQLITE_OK.
117410*/
117411SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
117412  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
117413    Table *pTab = pFrom->pTab;
117414    char *zIndexedBy = pFrom->u1.zIndexedBy;
117415    Index *pIdx;
117416    for(pIdx=pTab->pIndex;
117417        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
117418        pIdx=pIdx->pNext
117419    );
117420    if( !pIdx ){
117421      sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
117422      pParse->checkSchema = 1;
117423      return SQLITE_ERROR;
117424    }
117425    pFrom->pIBIndex = pIdx;
117426  }
117427  return SQLITE_OK;
117428}
117429/*
117430** Detect compound SELECT statements that use an ORDER BY clause with
117431** an alternative collating sequence.
117432**
117433**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
117434**
117435** These are rewritten as a subquery:
117436**
117437**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
117438**     ORDER BY ... COLLATE ...
117439**
117440** This transformation is necessary because the multiSelectOrderBy() routine
117441** above that generates the code for a compound SELECT with an ORDER BY clause
117442** uses a merge algorithm that requires the same collating sequence on the
117443** result columns as on the ORDER BY clause.  See ticket
117444** http://www.sqlite.org/src/info/6709574d2a
117445**
117446** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
117447** The UNION ALL operator works fine with multiSelectOrderBy() even when
117448** there are COLLATE terms in the ORDER BY.
117449*/
117450static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
117451  int i;
117452  Select *pNew;
117453  Select *pX;
117454  sqlite3 *db;
117455  struct ExprList_item *a;
117456  SrcList *pNewSrc;
117457  Parse *pParse;
117458  Token dummy;
117459
117460  if( p->pPrior==0 ) return WRC_Continue;
117461  if( p->pOrderBy==0 ) return WRC_Continue;
117462  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
117463  if( pX==0 ) return WRC_Continue;
117464  a = p->pOrderBy->a;
117465  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
117466    if( a[i].pExpr->flags & EP_Collate ) break;
117467  }
117468  if( i<0 ) return WRC_Continue;
117469
117470  /* If we reach this point, that means the transformation is required. */
117471
117472  pParse = pWalker->pParse;
117473  db = pParse->db;
117474  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
117475  if( pNew==0 ) return WRC_Abort;
117476  memset(&dummy, 0, sizeof(dummy));
117477  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
117478  if( pNewSrc==0 ) return WRC_Abort;
117479  *pNew = *p;
117480  p->pSrc = pNewSrc;
117481  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
117482  p->op = TK_SELECT;
117483  p->pWhere = 0;
117484  pNew->pGroupBy = 0;
117485  pNew->pHaving = 0;
117486  pNew->pOrderBy = 0;
117487  p->pPrior = 0;
117488  p->pNext = 0;
117489  p->pWith = 0;
117490  p->selFlags &= ~SF_Compound;
117491  assert( (p->selFlags & SF_Converted)==0 );
117492  p->selFlags |= SF_Converted;
117493  assert( pNew->pPrior!=0 );
117494  pNew->pPrior->pNext = pNew;
117495  pNew->pLimit = 0;
117496  pNew->pOffset = 0;
117497  return WRC_Continue;
117498}
117499
117500/*
117501** Check to see if the FROM clause term pFrom has table-valued function
117502** arguments.  If it does, leave an error message in pParse and return
117503** non-zero, since pFrom is not allowed to be a table-valued function.
117504*/
117505static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
117506  if( pFrom->fg.isTabFunc ){
117507    sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
117508    return 1;
117509  }
117510  return 0;
117511}
117512
117513#ifndef SQLITE_OMIT_CTE
117514/*
117515** Argument pWith (which may be NULL) points to a linked list of nested
117516** WITH contexts, from inner to outermost. If the table identified by
117517** FROM clause element pItem is really a common-table-expression (CTE)
117518** then return a pointer to the CTE definition for that table. Otherwise
117519** return NULL.
117520**
117521** If a non-NULL value is returned, set *ppContext to point to the With
117522** object that the returned CTE belongs to.
117523*/
117524static struct Cte *searchWith(
117525  With *pWith,                    /* Current innermost WITH clause */
117526  struct SrcList_item *pItem,     /* FROM clause element to resolve */
117527  With **ppContext                /* OUT: WITH clause return value belongs to */
117528){
117529  const char *zName;
117530  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
117531    With *p;
117532    for(p=pWith; p; p=p->pOuter){
117533      int i;
117534      for(i=0; i<p->nCte; i++){
117535        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
117536          *ppContext = p;
117537          return &p->a[i];
117538        }
117539      }
117540    }
117541  }
117542  return 0;
117543}
117544
117545/* The code generator maintains a stack of active WITH clauses
117546** with the inner-most WITH clause being at the top of the stack.
117547**
117548** This routine pushes the WITH clause passed as the second argument
117549** onto the top of the stack. If argument bFree is true, then this
117550** WITH clause will never be popped from the stack. In this case it
117551** should be freed along with the Parse object. In other cases, when
117552** bFree==0, the With object will be freed along with the SELECT
117553** statement with which it is associated.
117554*/
117555SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
117556  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
117557  if( pWith ){
117558    assert( pParse->pWith!=pWith );
117559    pWith->pOuter = pParse->pWith;
117560    pParse->pWith = pWith;
117561    if( bFree ) pParse->pWithToFree = pWith;
117562  }
117563}
117564
117565/*
117566** This function checks if argument pFrom refers to a CTE declared by
117567** a WITH clause on the stack currently maintained by the parser. And,
117568** if currently processing a CTE expression, if it is a recursive
117569** reference to the current CTE.
117570**
117571** If pFrom falls into either of the two categories above, pFrom->pTab
117572** and other fields are populated accordingly. The caller should check
117573** (pFrom->pTab!=0) to determine whether or not a successful match
117574** was found.
117575**
117576** Whether or not a match is found, SQLITE_OK is returned if no error
117577** occurs. If an error does occur, an error message is stored in the
117578** parser and some error code other than SQLITE_OK returned.
117579*/
117580static int withExpand(
117581  Walker *pWalker,
117582  struct SrcList_item *pFrom
117583){
117584  Parse *pParse = pWalker->pParse;
117585  sqlite3 *db = pParse->db;
117586  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
117587  With *pWith;                    /* WITH clause that pCte belongs to */
117588
117589  assert( pFrom->pTab==0 );
117590
117591  pCte = searchWith(pParse->pWith, pFrom, &pWith);
117592  if( pCte ){
117593    Table *pTab;
117594    ExprList *pEList;
117595    Select *pSel;
117596    Select *pLeft;                /* Left-most SELECT statement */
117597    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
117598    With *pSavedWith;             /* Initial value of pParse->pWith */
117599
117600    /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
117601    ** recursive reference to CTE pCte. Leave an error in pParse and return
117602    ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
117603    ** In this case, proceed.  */
117604    if( pCte->zCteErr ){
117605      sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
117606      return SQLITE_ERROR;
117607    }
117608    if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
117609
117610    assert( pFrom->pTab==0 );
117611    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117612    if( pTab==0 ) return WRC_Abort;
117613    pTab->nRef = 1;
117614    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
117615    pTab->iPKey = -1;
117616    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117617    pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
117618    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
117619    if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
117620    assert( pFrom->pSelect );
117621
117622    /* Check if this is a recursive CTE. */
117623    pSel = pFrom->pSelect;
117624    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
117625    if( bMayRecursive ){
117626      int i;
117627      SrcList *pSrc = pFrom->pSelect->pSrc;
117628      for(i=0; i<pSrc->nSrc; i++){
117629        struct SrcList_item *pItem = &pSrc->a[i];
117630        if( pItem->zDatabase==0
117631         && pItem->zName!=0
117632         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
117633          ){
117634          pItem->pTab = pTab;
117635          pItem->fg.isRecursive = 1;
117636          pTab->nRef++;
117637          pSel->selFlags |= SF_Recursive;
117638        }
117639      }
117640    }
117641
117642    /* Only one recursive reference is permitted. */
117643    if( pTab->nRef>2 ){
117644      sqlite3ErrorMsg(
117645          pParse, "multiple references to recursive table: %s", pCte->zName
117646      );
117647      return SQLITE_ERROR;
117648    }
117649    assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
117650
117651    pCte->zCteErr = "circular reference: %s";
117652    pSavedWith = pParse->pWith;
117653    pParse->pWith = pWith;
117654    sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
117655    pParse->pWith = pWith;
117656
117657    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
117658    pEList = pLeft->pEList;
117659    if( pCte->pCols ){
117660      if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
117661        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
117662            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
117663        );
117664        pParse->pWith = pSavedWith;
117665        return SQLITE_ERROR;
117666      }
117667      pEList = pCte->pCols;
117668    }
117669
117670    sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
117671    if( bMayRecursive ){
117672      if( pSel->selFlags & SF_Recursive ){
117673        pCte->zCteErr = "multiple recursive references: %s";
117674      }else{
117675        pCte->zCteErr = "recursive reference in a subquery: %s";
117676      }
117677      sqlite3WalkSelect(pWalker, pSel);
117678    }
117679    pCte->zCteErr = 0;
117680    pParse->pWith = pSavedWith;
117681  }
117682
117683  return SQLITE_OK;
117684}
117685#endif
117686
117687#ifndef SQLITE_OMIT_CTE
117688/*
117689** If the SELECT passed as the second argument has an associated WITH
117690** clause, pop it from the stack stored as part of the Parse object.
117691**
117692** This function is used as the xSelectCallback2() callback by
117693** sqlite3SelectExpand() when walking a SELECT tree to resolve table
117694** names and other FROM clause elements.
117695*/
117696static void selectPopWith(Walker *pWalker, Select *p){
117697  Parse *pParse = pWalker->pParse;
117698  With *pWith = findRightmost(p)->pWith;
117699  if( pWith!=0 ){
117700    assert( pParse->pWith==pWith );
117701    pParse->pWith = pWith->pOuter;
117702  }
117703}
117704#else
117705#define selectPopWith 0
117706#endif
117707
117708/*
117709** This routine is a Walker callback for "expanding" a SELECT statement.
117710** "Expanding" means to do the following:
117711**
117712**    (1)  Make sure VDBE cursor numbers have been assigned to every
117713**         element of the FROM clause.
117714**
117715**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
117716**         defines FROM clause.  When views appear in the FROM clause,
117717**         fill pTabList->a[].pSelect with a copy of the SELECT statement
117718**         that implements the view.  A copy is made of the view's SELECT
117719**         statement so that we can freely modify or delete that statement
117720**         without worrying about messing up the persistent representation
117721**         of the view.
117722**
117723**    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
117724**         on joins and the ON and USING clause of joins.
117725**
117726**    (4)  Scan the list of columns in the result set (pEList) looking
117727**         for instances of the "*" operator or the TABLE.* operator.
117728**         If found, expand each "*" to be every column in every table
117729**         and TABLE.* to be every column in TABLE.
117730**
117731*/
117732static int selectExpander(Walker *pWalker, Select *p){
117733  Parse *pParse = pWalker->pParse;
117734  int i, j, k;
117735  SrcList *pTabList;
117736  ExprList *pEList;
117737  struct SrcList_item *pFrom;
117738  sqlite3 *db = pParse->db;
117739  Expr *pE, *pRight, *pExpr;
117740  u16 selFlags = p->selFlags;
117741
117742  p->selFlags |= SF_Expanded;
117743  if( db->mallocFailed  ){
117744    return WRC_Abort;
117745  }
117746  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
117747    return WRC_Prune;
117748  }
117749  pTabList = p->pSrc;
117750  pEList = p->pEList;
117751  if( pWalker->xSelectCallback2==selectPopWith ){
117752    sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
117753  }
117754
117755  /* Make sure cursor numbers have been assigned to all entries in
117756  ** the FROM clause of the SELECT statement.
117757  */
117758  sqlite3SrcListAssignCursors(pParse, pTabList);
117759
117760  /* Look up every table named in the FROM clause of the select.  If
117761  ** an entry of the FROM clause is a subquery instead of a table or view,
117762  ** then create a transient table structure to describe the subquery.
117763  */
117764  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117765    Table *pTab;
117766    assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
117767    if( pFrom->fg.isRecursive ) continue;
117768    assert( pFrom->pTab==0 );
117769#ifndef SQLITE_OMIT_CTE
117770    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
117771    if( pFrom->pTab ) {} else
117772#endif
117773    if( pFrom->zName==0 ){
117774#ifndef SQLITE_OMIT_SUBQUERY
117775      Select *pSel = pFrom->pSelect;
117776      /* A sub-query in the FROM clause of a SELECT */
117777      assert( pSel!=0 );
117778      assert( pFrom->pTab==0 );
117779      if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
117780      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117781      if( pTab==0 ) return WRC_Abort;
117782      pTab->nRef = 1;
117783      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
117784      while( pSel->pPrior ){ pSel = pSel->pPrior; }
117785      sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
117786      pTab->iPKey = -1;
117787      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117788      pTab->tabFlags |= TF_Ephemeral;
117789#endif
117790    }else{
117791      /* An ordinary table or view name in the FROM clause */
117792      assert( pFrom->pTab==0 );
117793      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
117794      if( pTab==0 ) return WRC_Abort;
117795      if( pTab->nRef==0xffff ){
117796        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
117797           pTab->zName);
117798        pFrom->pTab = 0;
117799        return WRC_Abort;
117800      }
117801      pTab->nRef++;
117802      if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
117803        return WRC_Abort;
117804      }
117805#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
117806      if( IsVirtual(pTab) || pTab->pSelect ){
117807        i16 nCol;
117808        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
117809        assert( pFrom->pSelect==0 );
117810        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
117811        sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
117812        nCol = pTab->nCol;
117813        pTab->nCol = -1;
117814        sqlite3WalkSelect(pWalker, pFrom->pSelect);
117815        pTab->nCol = nCol;
117816      }
117817#endif
117818    }
117819
117820    /* Locate the index named by the INDEXED BY clause, if any. */
117821    if( sqlite3IndexedByLookup(pParse, pFrom) ){
117822      return WRC_Abort;
117823    }
117824  }
117825
117826  /* Process NATURAL keywords, and ON and USING clauses of joins.
117827  */
117828  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
117829    return WRC_Abort;
117830  }
117831
117832  /* For every "*" that occurs in the column list, insert the names of
117833  ** all columns in all tables.  And for every TABLE.* insert the names
117834  ** of all columns in TABLE.  The parser inserted a special expression
117835  ** with the TK_ASTERISK operator for each "*" that it found in the column
117836  ** list.  The following code just has to locate the TK_ASTERISK
117837  ** expressions and expand each one to the list of all columns in
117838  ** all tables.
117839  **
117840  ** The first loop just checks to see if there are any "*" operators
117841  ** that need expanding.
117842  */
117843  for(k=0; k<pEList->nExpr; k++){
117844    pE = pEList->a[k].pExpr;
117845    if( pE->op==TK_ASTERISK ) break;
117846    assert( pE->op!=TK_DOT || pE->pRight!=0 );
117847    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
117848    if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
117849  }
117850  if( k<pEList->nExpr ){
117851    /*
117852    ** If we get here it means the result set contains one or more "*"
117853    ** operators that need to be expanded.  Loop through each expression
117854    ** in the result set and expand them one by one.
117855    */
117856    struct ExprList_item *a = pEList->a;
117857    ExprList *pNew = 0;
117858    int flags = pParse->db->flags;
117859    int longNames = (flags & SQLITE_FullColNames)!=0
117860                      && (flags & SQLITE_ShortColNames)==0;
117861
117862    for(k=0; k<pEList->nExpr; k++){
117863      pE = a[k].pExpr;
117864      pRight = pE->pRight;
117865      assert( pE->op!=TK_DOT || pRight!=0 );
117866      if( pE->op!=TK_ASTERISK
117867       && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
117868      ){
117869        /* This particular expression does not need to be expanded.
117870        */
117871        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
117872        if( pNew ){
117873          pNew->a[pNew->nExpr-1].zName = a[k].zName;
117874          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
117875          a[k].zName = 0;
117876          a[k].zSpan = 0;
117877        }
117878        a[k].pExpr = 0;
117879      }else{
117880        /* This expression is a "*" or a "TABLE.*" and needs to be
117881        ** expanded. */
117882        int tableSeen = 0;      /* Set to 1 when TABLE matches */
117883        char *zTName = 0;       /* text of name of TABLE */
117884        if( pE->op==TK_DOT ){
117885          assert( pE->pLeft!=0 );
117886          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
117887          zTName = pE->pLeft->u.zToken;
117888        }
117889        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117890          Table *pTab = pFrom->pTab;
117891          Select *pSub = pFrom->pSelect;
117892          char *zTabName = pFrom->zAlias;
117893          const char *zSchemaName = 0;
117894          int iDb;
117895          if( zTabName==0 ){
117896            zTabName = pTab->zName;
117897          }
117898          if( db->mallocFailed ) break;
117899          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
117900            pSub = 0;
117901            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
117902              continue;
117903            }
117904            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117905            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
117906          }
117907          for(j=0; j<pTab->nCol; j++){
117908            char *zName = pTab->aCol[j].zName;
117909            char *zColname;  /* The computed column name */
117910            char *zToFree;   /* Malloced string that needs to be freed */
117911            Token sColname;  /* Computed column name as a token */
117912
117913            assert( zName );
117914            if( zTName && pSub
117915             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
117916            ){
117917              continue;
117918            }
117919
117920            /* If a column is marked as 'hidden', omit it from the expanded
117921            ** result-set list unless the SELECT has the SF_IncludeHidden
117922            ** bit set.
117923            */
117924            if( (p->selFlags & SF_IncludeHidden)==0
117925             && IsHiddenColumn(&pTab->aCol[j])
117926            ){
117927              continue;
117928            }
117929            tableSeen = 1;
117930
117931            if( i>0 && zTName==0 ){
117932              if( (pFrom->fg.jointype & JT_NATURAL)!=0
117933                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
117934              ){
117935                /* In a NATURAL join, omit the join columns from the
117936                ** table to the right of the join */
117937                continue;
117938              }
117939              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
117940                /* In a join with a USING clause, omit columns in the
117941                ** using clause from the table on the right. */
117942                continue;
117943              }
117944            }
117945            pRight = sqlite3Expr(db, TK_ID, zName);
117946            zColname = zName;
117947            zToFree = 0;
117948            if( longNames || pTabList->nSrc>1 ){
117949              Expr *pLeft;
117950              pLeft = sqlite3Expr(db, TK_ID, zTabName);
117951              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
117952              if( zSchemaName ){
117953                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
117954                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
117955              }
117956              if( longNames ){
117957                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
117958                zToFree = zColname;
117959              }
117960            }else{
117961              pExpr = pRight;
117962            }
117963            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
117964            sqlite3TokenInit(&sColname, zColname);
117965            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
117966            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
117967              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
117968              if( pSub ){
117969                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
117970                testcase( pX->zSpan==0 );
117971              }else{
117972                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
117973                                           zSchemaName, zTabName, zColname);
117974                testcase( pX->zSpan==0 );
117975              }
117976              pX->bSpanIsTab = 1;
117977            }
117978            sqlite3DbFree(db, zToFree);
117979          }
117980        }
117981        if( !tableSeen ){
117982          if( zTName ){
117983            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
117984          }else{
117985            sqlite3ErrorMsg(pParse, "no tables specified");
117986          }
117987        }
117988      }
117989    }
117990    sqlite3ExprListDelete(db, pEList);
117991    p->pEList = pNew;
117992  }
117993#if SQLITE_MAX_COLUMN
117994  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
117995    sqlite3ErrorMsg(pParse, "too many columns in result set");
117996    return WRC_Abort;
117997  }
117998#endif
117999  return WRC_Continue;
118000}
118001
118002/*
118003** No-op routine for the parse-tree walker.
118004**
118005** When this routine is the Walker.xExprCallback then expression trees
118006** are walked without any actions being taken at each node.  Presumably,
118007** when this routine is used for Walker.xExprCallback then
118008** Walker.xSelectCallback is set to do something useful for every
118009** subquery in the parser tree.
118010*/
118011SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
118012  UNUSED_PARAMETER2(NotUsed, NotUsed2);
118013  return WRC_Continue;
118014}
118015
118016/*
118017** This routine "expands" a SELECT statement and all of its subqueries.
118018** For additional information on what it means to "expand" a SELECT
118019** statement, see the comment on the selectExpand worker callback above.
118020**
118021** Expanding a SELECT statement is the first step in processing a
118022** SELECT statement.  The SELECT statement must be expanded before
118023** name resolution is performed.
118024**
118025** If anything goes wrong, an error message is written into pParse.
118026** The calling function can detect the problem by looking at pParse->nErr
118027** and/or pParse->db->mallocFailed.
118028*/
118029static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
118030  Walker w;
118031  memset(&w, 0, sizeof(w));
118032  w.xExprCallback = sqlite3ExprWalkNoop;
118033  w.pParse = pParse;
118034  if( pParse->hasCompound ){
118035    w.xSelectCallback = convertCompoundSelectToSubquery;
118036    sqlite3WalkSelect(&w, pSelect);
118037  }
118038  w.xSelectCallback = selectExpander;
118039  if( (pSelect->selFlags & SF_MultiValue)==0 ){
118040    w.xSelectCallback2 = selectPopWith;
118041  }
118042  sqlite3WalkSelect(&w, pSelect);
118043}
118044
118045
118046#ifndef SQLITE_OMIT_SUBQUERY
118047/*
118048** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
118049** interface.
118050**
118051** For each FROM-clause subquery, add Column.zType and Column.zColl
118052** information to the Table structure that represents the result set
118053** of that subquery.
118054**
118055** The Table structure that represents the result set was constructed
118056** by selectExpander() but the type and collation information was omitted
118057** at that point because identifiers had not yet been resolved.  This
118058** routine is called after identifier resolution.
118059*/
118060static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
118061  Parse *pParse;
118062  int i;
118063  SrcList *pTabList;
118064  struct SrcList_item *pFrom;
118065
118066  assert( p->selFlags & SF_Resolved );
118067  assert( (p->selFlags & SF_HasTypeInfo)==0 );
118068  p->selFlags |= SF_HasTypeInfo;
118069  pParse = pWalker->pParse;
118070  pTabList = p->pSrc;
118071  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118072    Table *pTab = pFrom->pTab;
118073    assert( pTab!=0 );
118074    if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
118075      /* A sub-query in the FROM clause of a SELECT */
118076      Select *pSel = pFrom->pSelect;
118077      if( pSel ){
118078        while( pSel->pPrior ) pSel = pSel->pPrior;
118079        sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
118080      }
118081    }
118082  }
118083}
118084#endif
118085
118086
118087/*
118088** This routine adds datatype and collating sequence information to
118089** the Table structures of all FROM-clause subqueries in a
118090** SELECT statement.
118091**
118092** Use this routine after name resolution.
118093*/
118094static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
118095#ifndef SQLITE_OMIT_SUBQUERY
118096  Walker w;
118097  memset(&w, 0, sizeof(w));
118098  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
118099  w.xExprCallback = sqlite3ExprWalkNoop;
118100  w.pParse = pParse;
118101  sqlite3WalkSelect(&w, pSelect);
118102#endif
118103}
118104
118105
118106/*
118107** This routine sets up a SELECT statement for processing.  The
118108** following is accomplished:
118109**
118110**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
118111**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
118112**     *  ON and USING clauses are shifted into WHERE statements
118113**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
118114**     *  Identifiers in expression are matched to tables.
118115**
118116** This routine acts recursively on all subqueries within the SELECT.
118117*/
118118SQLITE_PRIVATE void sqlite3SelectPrep(
118119  Parse *pParse,         /* The parser context */
118120  Select *p,             /* The SELECT statement being coded. */
118121  NameContext *pOuterNC  /* Name context for container */
118122){
118123  sqlite3 *db;
118124  if( NEVER(p==0) ) return;
118125  db = pParse->db;
118126  if( db->mallocFailed ) return;
118127  if( p->selFlags & SF_HasTypeInfo ) return;
118128  sqlite3SelectExpand(pParse, p);
118129  if( pParse->nErr || db->mallocFailed ) return;
118130  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
118131  if( pParse->nErr || db->mallocFailed ) return;
118132  sqlite3SelectAddTypeInfo(pParse, p);
118133}
118134
118135/*
118136** Reset the aggregate accumulator.
118137**
118138** The aggregate accumulator is a set of memory cells that hold
118139** intermediate results while calculating an aggregate.  This
118140** routine generates code that stores NULLs in all of those memory
118141** cells.
118142*/
118143static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
118144  Vdbe *v = pParse->pVdbe;
118145  int i;
118146  struct AggInfo_func *pFunc;
118147  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
118148  if( nReg==0 ) return;
118149#ifdef SQLITE_DEBUG
118150  /* Verify that all AggInfo registers are within the range specified by
118151  ** AggInfo.mnReg..AggInfo.mxReg */
118152  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
118153  for(i=0; i<pAggInfo->nColumn; i++){
118154    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
118155         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
118156  }
118157  for(i=0; i<pAggInfo->nFunc; i++){
118158    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
118159         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
118160  }
118161#endif
118162  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
118163  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
118164    if( pFunc->iDistinct>=0 ){
118165      Expr *pE = pFunc->pExpr;
118166      assert( !ExprHasProperty(pE, EP_xIsSelect) );
118167      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
118168        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
118169           "argument");
118170        pFunc->iDistinct = -1;
118171      }else{
118172        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
118173        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
118174                          (char*)pKeyInfo, P4_KEYINFO);
118175      }
118176    }
118177  }
118178}
118179
118180/*
118181** Invoke the OP_AggFinalize opcode for every aggregate function
118182** in the AggInfo structure.
118183*/
118184static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
118185  Vdbe *v = pParse->pVdbe;
118186  int i;
118187  struct AggInfo_func *pF;
118188  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
118189    ExprList *pList = pF->pExpr->x.pList;
118190    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
118191    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
118192                      (void*)pF->pFunc, P4_FUNCDEF);
118193  }
118194}
118195
118196/*
118197** Update the accumulator memory cells for an aggregate based on
118198** the current cursor position.
118199*/
118200static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
118201  Vdbe *v = pParse->pVdbe;
118202  int i;
118203  int regHit = 0;
118204  int addrHitTest = 0;
118205  struct AggInfo_func *pF;
118206  struct AggInfo_col *pC;
118207
118208  pAggInfo->directMode = 1;
118209  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
118210    int nArg;
118211    int addrNext = 0;
118212    int regAgg;
118213    ExprList *pList = pF->pExpr->x.pList;
118214    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
118215    if( pList ){
118216      nArg = pList->nExpr;
118217      regAgg = sqlite3GetTempRange(pParse, nArg);
118218      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
118219    }else{
118220      nArg = 0;
118221      regAgg = 0;
118222    }
118223    if( pF->iDistinct>=0 ){
118224      addrNext = sqlite3VdbeMakeLabel(v);
118225      testcase( nArg==0 );  /* Error condition */
118226      testcase( nArg>1 );   /* Also an error */
118227      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
118228    }
118229    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
118230      CollSeq *pColl = 0;
118231      struct ExprList_item *pItem;
118232      int j;
118233      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
118234      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
118235        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
118236      }
118237      if( !pColl ){
118238        pColl = pParse->db->pDfltColl;
118239      }
118240      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
118241      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
118242    }
118243    sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
118244                      (void*)pF->pFunc, P4_FUNCDEF);
118245    sqlite3VdbeChangeP5(v, (u8)nArg);
118246    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
118247    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
118248    if( addrNext ){
118249      sqlite3VdbeResolveLabel(v, addrNext);
118250      sqlite3ExprCacheClear(pParse);
118251    }
118252  }
118253
118254  /* Before populating the accumulator registers, clear the column cache.
118255  ** Otherwise, if any of the required column values are already present
118256  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
118257  ** to pC->iMem. But by the time the value is used, the original register
118258  ** may have been used, invalidating the underlying buffer holding the
118259  ** text or blob value. See ticket [883034dcb5].
118260  **
118261  ** Another solution would be to change the OP_SCopy used to copy cached
118262  ** values to an OP_Copy.
118263  */
118264  if( regHit ){
118265    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
118266  }
118267  sqlite3ExprCacheClear(pParse);
118268  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
118269    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
118270  }
118271  pAggInfo->directMode = 0;
118272  sqlite3ExprCacheClear(pParse);
118273  if( addrHitTest ){
118274    sqlite3VdbeJumpHere(v, addrHitTest);
118275  }
118276}
118277
118278/*
118279** Add a single OP_Explain instruction to the VDBE to explain a simple
118280** count(*) query ("SELECT count(*) FROM pTab").
118281*/
118282#ifndef SQLITE_OMIT_EXPLAIN
118283static void explainSimpleCount(
118284  Parse *pParse,                  /* Parse context */
118285  Table *pTab,                    /* Table being queried */
118286  Index *pIdx                     /* Index used to optimize scan, or NULL */
118287){
118288  if( pParse->explain==2 ){
118289    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
118290    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
118291        pTab->zName,
118292        bCover ? " USING COVERING INDEX " : "",
118293        bCover ? pIdx->zName : ""
118294    );
118295    sqlite3VdbeAddOp4(
118296        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
118297    );
118298  }
118299}
118300#else
118301# define explainSimpleCount(a,b,c)
118302#endif
118303
118304/*
118305** Generate code for the SELECT statement given in the p argument.
118306**
118307** The results are returned according to the SelectDest structure.
118308** See comments in sqliteInt.h for further information.
118309**
118310** This routine returns the number of errors.  If any errors are
118311** encountered, then an appropriate error message is left in
118312** pParse->zErrMsg.
118313**
118314** This routine does NOT free the Select structure passed in.  The
118315** calling function needs to do that.
118316*/
118317SQLITE_PRIVATE int sqlite3Select(
118318  Parse *pParse,         /* The parser context */
118319  Select *p,             /* The SELECT statement being coded. */
118320  SelectDest *pDest      /* What to do with the query results */
118321){
118322  int i, j;              /* Loop counters */
118323  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
118324  Vdbe *v;               /* The virtual machine under construction */
118325  int isAgg;             /* True for select lists like "count(*)" */
118326  ExprList *pEList = 0;  /* List of columns to extract. */
118327  SrcList *pTabList;     /* List of tables to select from */
118328  Expr *pWhere;          /* The WHERE clause.  May be NULL */
118329  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
118330  Expr *pHaving;         /* The HAVING clause.  May be NULL */
118331  int rc = 1;            /* Value to return from this function */
118332  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
118333  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
118334  AggInfo sAggInfo;      /* Information used by aggregate queries */
118335  int iEnd;              /* Address of the end of the query */
118336  sqlite3 *db;           /* The database connection */
118337
118338#ifndef SQLITE_OMIT_EXPLAIN
118339  int iRestoreSelectId = pParse->iSelectId;
118340  pParse->iSelectId = pParse->iNextSelectId++;
118341#endif
118342
118343  db = pParse->db;
118344  if( p==0 || db->mallocFailed || pParse->nErr ){
118345    return 1;
118346  }
118347  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
118348  memset(&sAggInfo, 0, sizeof(sAggInfo));
118349#if SELECTTRACE_ENABLED
118350  pParse->nSelectIndent++;
118351  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
118352  if( sqlite3SelectTrace & 0x100 ){
118353    sqlite3TreeViewSelect(0, p, 0);
118354  }
118355#endif
118356
118357  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
118358  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
118359  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
118360  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
118361  if( IgnorableOrderby(pDest) ){
118362    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
118363           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
118364           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
118365           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
118366    /* If ORDER BY makes no difference in the output then neither does
118367    ** DISTINCT so it can be removed too. */
118368    sqlite3ExprListDelete(db, p->pOrderBy);
118369    p->pOrderBy = 0;
118370    p->selFlags &= ~SF_Distinct;
118371  }
118372  sqlite3SelectPrep(pParse, p, 0);
118373  memset(&sSort, 0, sizeof(sSort));
118374  sSort.pOrderBy = p->pOrderBy;
118375  pTabList = p->pSrc;
118376  if( pParse->nErr || db->mallocFailed ){
118377    goto select_end;
118378  }
118379  assert( p->pEList!=0 );
118380  isAgg = (p->selFlags & SF_Aggregate)!=0;
118381#if SELECTTRACE_ENABLED
118382  if( sqlite3SelectTrace & 0x100 ){
118383    SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
118384    sqlite3TreeViewSelect(0, p, 0);
118385  }
118386#endif
118387
118388
118389  /* If writing to memory or generating a set
118390  ** only a single column may be output.
118391  */
118392#ifndef SQLITE_OMIT_SUBQUERY
118393  if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
118394    goto select_end;
118395  }
118396#endif
118397
118398  /* Try to flatten subqueries in the FROM clause up into the main query
118399  */
118400#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118401  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
118402    struct SrcList_item *pItem = &pTabList->a[i];
118403    Select *pSub = pItem->pSelect;
118404    int isAggSub;
118405    Table *pTab = pItem->pTab;
118406    if( pSub==0 ) continue;
118407
118408    /* Catch mismatch in the declared columns of a view and the number of
118409    ** columns in the SELECT on the RHS */
118410    if( pTab->nCol!=pSub->pEList->nExpr ){
118411      sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
118412                      pTab->nCol, pTab->zName, pSub->pEList->nExpr);
118413      goto select_end;
118414    }
118415
118416    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
118417    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
118418      /* This subquery can be absorbed into its parent. */
118419      if( isAggSub ){
118420        isAgg = 1;
118421        p->selFlags |= SF_Aggregate;
118422      }
118423      i = -1;
118424    }
118425    pTabList = p->pSrc;
118426    if( db->mallocFailed ) goto select_end;
118427    if( !IgnorableOrderby(pDest) ){
118428      sSort.pOrderBy = p->pOrderBy;
118429    }
118430  }
118431#endif
118432
118433  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
118434  ** does not already exist */
118435  v = sqlite3GetVdbe(pParse);
118436  if( v==0 ) goto select_end;
118437
118438#ifndef SQLITE_OMIT_COMPOUND_SELECT
118439  /* Handle compound SELECT statements using the separate multiSelect()
118440  ** procedure.
118441  */
118442  if( p->pPrior ){
118443    rc = multiSelect(pParse, p, pDest);
118444    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
118445#if SELECTTRACE_ENABLED
118446    SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
118447    pParse->nSelectIndent--;
118448#endif
118449    return rc;
118450  }
118451#endif
118452
118453  /* Generate code for all sub-queries in the FROM clause
118454  */
118455#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118456  for(i=0; i<pTabList->nSrc; i++){
118457    struct SrcList_item *pItem = &pTabList->a[i];
118458    SelectDest dest;
118459    Select *pSub = pItem->pSelect;
118460    if( pSub==0 ) continue;
118461
118462    /* Sometimes the code for a subquery will be generated more than
118463    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
118464    ** for example.  In that case, do not regenerate the code to manifest
118465    ** a view or the co-routine to implement a view.  The first instance
118466    ** is sufficient, though the subroutine to manifest the view does need
118467    ** to be invoked again. */
118468    if( pItem->addrFillSub ){
118469      if( pItem->fg.viaCoroutine==0 ){
118470        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
118471      }
118472      continue;
118473    }
118474
118475    /* Increment Parse.nHeight by the height of the largest expression
118476    ** tree referred to by this, the parent select. The child select
118477    ** may contain expression trees of at most
118478    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
118479    ** more conservative than necessary, but much easier than enforcing
118480    ** an exact limit.
118481    */
118482    pParse->nHeight += sqlite3SelectExprHeight(p);
118483
118484    /* Make copies of constant WHERE-clause terms in the outer query down
118485    ** inside the subquery.  This can help the subquery to run more efficiently.
118486    */
118487    if( (pItem->fg.jointype & JT_OUTER)==0
118488     && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
118489    ){
118490#if SELECTTRACE_ENABLED
118491      if( sqlite3SelectTrace & 0x100 ){
118492        SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
118493        sqlite3TreeViewSelect(0, p, 0);
118494      }
118495#endif
118496    }
118497
118498    /* Generate code to implement the subquery
118499    **
118500    ** The subquery is implemented as a co-routine if all of these are true:
118501    **   (1)  The subquery is guaranteed to be the outer loop (so that it
118502    **        does not need to be computed more than once)
118503    **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
118504    **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
118505    **        the use of co-routines.)
118506    **   (3)  Co-routines are not disabled using sqlite3_test_control()
118507    **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
118508    **
118509    ** TODO: Are there other reasons beside (1) to use a co-routine
118510    ** implementation?
118511    */
118512    if( i==0
118513     && (pTabList->nSrc==1
118514            || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
118515     && (p->selFlags & SF_All)==0                                   /* (2) */
118516     && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
118517    ){
118518      /* Implement a co-routine that will return a single row of the result
118519      ** set on each invocation.
118520      */
118521      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
118522      pItem->regReturn = ++pParse->nMem;
118523      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
118524      VdbeComment((v, "%s", pItem->pTab->zName));
118525      pItem->addrFillSub = addrTop;
118526      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
118527      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
118528      sqlite3Select(pParse, pSub, &dest);
118529      pItem->pTab->nRowLogEst = pSub->nSelectRow;
118530      pItem->fg.viaCoroutine = 1;
118531      pItem->regResult = dest.iSdst;
118532      sqlite3VdbeEndCoroutine(v, pItem->regReturn);
118533      sqlite3VdbeJumpHere(v, addrTop-1);
118534      sqlite3ClearTempRegCache(pParse);
118535    }else{
118536      /* Generate a subroutine that will fill an ephemeral table with
118537      ** the content of this subquery.  pItem->addrFillSub will point
118538      ** to the address of the generated subroutine.  pItem->regReturn
118539      ** is a register allocated to hold the subroutine return address
118540      */
118541      int topAddr;
118542      int onceAddr = 0;
118543      int retAddr;
118544      assert( pItem->addrFillSub==0 );
118545      pItem->regReturn = ++pParse->nMem;
118546      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
118547      pItem->addrFillSub = topAddr+1;
118548      if( pItem->fg.isCorrelated==0 ){
118549        /* If the subquery is not correlated and if we are not inside of
118550        ** a trigger, then we only need to compute the value of the subquery
118551        ** once. */
118552        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
118553        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
118554      }else{
118555        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
118556      }
118557      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
118558      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
118559      sqlite3Select(pParse, pSub, &dest);
118560      pItem->pTab->nRowLogEst = pSub->nSelectRow;
118561      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
118562      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
118563      VdbeComment((v, "end %s", pItem->pTab->zName));
118564      sqlite3VdbeChangeP1(v, topAddr, retAddr);
118565      sqlite3ClearTempRegCache(pParse);
118566    }
118567    if( db->mallocFailed ) goto select_end;
118568    pParse->nHeight -= sqlite3SelectExprHeight(p);
118569  }
118570#endif
118571
118572  /* Various elements of the SELECT copied into local variables for
118573  ** convenience */
118574  pEList = p->pEList;
118575  pWhere = p->pWhere;
118576  pGroupBy = p->pGroupBy;
118577  pHaving = p->pHaving;
118578  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
118579
118580#if SELECTTRACE_ENABLED
118581  if( sqlite3SelectTrace & 0x400 ){
118582    SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
118583    sqlite3TreeViewSelect(0, p, 0);
118584  }
118585#endif
118586
118587  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
118588  ** if the select-list is the same as the ORDER BY list, then this query
118589  ** can be rewritten as a GROUP BY. In other words, this:
118590  **
118591  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
118592  **
118593  ** is transformed to:
118594  **
118595  **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
118596  **
118597  ** The second form is preferred as a single index (or temp-table) may be
118598  ** used for both the ORDER BY and DISTINCT processing. As originally
118599  ** written the query must use a temp-table for at least one of the ORDER
118600  ** BY and DISTINCT, and an index or separate temp-table for the other.
118601  */
118602  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
118603   && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
118604  ){
118605    p->selFlags &= ~SF_Distinct;
118606    pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
118607    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
118608    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
118609    ** original setting of the SF_Distinct flag, not the current setting */
118610    assert( sDistinct.isTnct );
118611
118612#if SELECTTRACE_ENABLED
118613    if( sqlite3SelectTrace & 0x400 ){
118614      SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
118615      sqlite3TreeViewSelect(0, p, 0);
118616    }
118617#endif
118618  }
118619
118620  /* If there is an ORDER BY clause, then create an ephemeral index to
118621  ** do the sorting.  But this sorting ephemeral index might end up
118622  ** being unused if the data can be extracted in pre-sorted order.
118623  ** If that is the case, then the OP_OpenEphemeral instruction will be
118624  ** changed to an OP_Noop once we figure out that the sorting index is
118625  ** not needed.  The sSort.addrSortIndex variable is used to facilitate
118626  ** that change.
118627  */
118628  if( sSort.pOrderBy ){
118629    KeyInfo *pKeyInfo;
118630    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
118631    sSort.iECursor = pParse->nTab++;
118632    sSort.addrSortIndex =
118633      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
118634          sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
118635          (char*)pKeyInfo, P4_KEYINFO
118636      );
118637  }else{
118638    sSort.addrSortIndex = -1;
118639  }
118640
118641  /* If the output is destined for a temporary table, open that table.
118642  */
118643  if( pDest->eDest==SRT_EphemTab ){
118644    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
118645  }
118646
118647  /* Set the limiter.
118648  */
118649  iEnd = sqlite3VdbeMakeLabel(v);
118650  p->nSelectRow = 320;  /* 4 billion rows */
118651  computeLimitRegisters(pParse, p, iEnd);
118652  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
118653    sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
118654    sSort.sortFlags |= SORTFLAG_UseSorter;
118655  }
118656
118657  /* Open an ephemeral index to use for the distinct set.
118658  */
118659  if( p->selFlags & SF_Distinct ){
118660    sDistinct.tabTnct = pParse->nTab++;
118661    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
118662                             sDistinct.tabTnct, 0, 0,
118663                             (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
118664                             P4_KEYINFO);
118665    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
118666    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
118667  }else{
118668    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
118669  }
118670
118671  if( !isAgg && pGroupBy==0 ){
118672    /* No aggregate functions and no GROUP BY clause */
118673    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
118674    assert( WHERE_USE_LIMIT==SF_FixedLimit );
118675    wctrlFlags |= p->selFlags & SF_FixedLimit;
118676
118677    /* Begin the database scan. */
118678    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
118679                               p->pEList, wctrlFlags, p->nSelectRow);
118680    if( pWInfo==0 ) goto select_end;
118681    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
118682      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
118683    }
118684    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
118685      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
118686    }
118687    if( sSort.pOrderBy ){
118688      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
118689      sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
118690      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
118691        sSort.pOrderBy = 0;
118692      }
118693    }
118694
118695    /* If sorting index that was created by a prior OP_OpenEphemeral
118696    ** instruction ended up not being needed, then change the OP_OpenEphemeral
118697    ** into an OP_Noop.
118698    */
118699    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
118700      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
118701    }
118702
118703    /* Use the standard inner loop. */
118704    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
118705                    sqlite3WhereContinueLabel(pWInfo),
118706                    sqlite3WhereBreakLabel(pWInfo));
118707
118708    /* End the database scan loop.
118709    */
118710    sqlite3WhereEnd(pWInfo);
118711  }else{
118712    /* This case when there exist aggregate functions or a GROUP BY clause
118713    ** or both */
118714    NameContext sNC;    /* Name context for processing aggregate information */
118715    int iAMem;          /* First Mem address for storing current GROUP BY */
118716    int iBMem;          /* First Mem address for previous GROUP BY */
118717    int iUseFlag;       /* Mem address holding flag indicating that at least
118718                        ** one row of the input to the aggregator has been
118719                        ** processed */
118720    int iAbortFlag;     /* Mem address which causes query abort if positive */
118721    int groupBySort;    /* Rows come from source in GROUP BY order */
118722    int addrEnd;        /* End of processing for this SELECT */
118723    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
118724    int sortOut = 0;    /* Output register from the sorter */
118725    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
118726
118727    /* Remove any and all aliases between the result set and the
118728    ** GROUP BY clause.
118729    */
118730    if( pGroupBy ){
118731      int k;                        /* Loop counter */
118732      struct ExprList_item *pItem;  /* For looping over expression in a list */
118733
118734      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
118735        pItem->u.x.iAlias = 0;
118736      }
118737      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
118738        pItem->u.x.iAlias = 0;
118739      }
118740      assert( 66==sqlite3LogEst(100) );
118741      if( p->nSelectRow>66 ) p->nSelectRow = 66;
118742    }else{
118743      assert( 0==sqlite3LogEst(1) );
118744      p->nSelectRow = 0;
118745    }
118746
118747    /* If there is both a GROUP BY and an ORDER BY clause and they are
118748    ** identical, then it may be possible to disable the ORDER BY clause
118749    ** on the grounds that the GROUP BY will cause elements to come out
118750    ** in the correct order. It also may not - the GROUP BY might use a
118751    ** database index that causes rows to be grouped together as required
118752    ** but not actually sorted. Either way, record the fact that the
118753    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
118754    ** variable.  */
118755    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
118756      orderByGrp = 1;
118757    }
118758
118759    /* Create a label to jump to when we want to abort the query */
118760    addrEnd = sqlite3VdbeMakeLabel(v);
118761
118762    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
118763    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
118764    ** SELECT statement.
118765    */
118766    memset(&sNC, 0, sizeof(sNC));
118767    sNC.pParse = pParse;
118768    sNC.pSrcList = pTabList;
118769    sNC.pAggInfo = &sAggInfo;
118770    sAggInfo.mnReg = pParse->nMem+1;
118771    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
118772    sAggInfo.pGroupBy = pGroupBy;
118773    sqlite3ExprAnalyzeAggList(&sNC, pEList);
118774    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
118775    if( pHaving ){
118776      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
118777    }
118778    sAggInfo.nAccumulator = sAggInfo.nColumn;
118779    for(i=0; i<sAggInfo.nFunc; i++){
118780      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
118781      sNC.ncFlags |= NC_InAggFunc;
118782      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
118783      sNC.ncFlags &= ~NC_InAggFunc;
118784    }
118785    sAggInfo.mxReg = pParse->nMem;
118786    if( db->mallocFailed ) goto select_end;
118787
118788    /* Processing for aggregates with GROUP BY is very different and
118789    ** much more complex than aggregates without a GROUP BY.
118790    */
118791    if( pGroupBy ){
118792      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
118793      int addr1;          /* A-vs-B comparision jump */
118794      int addrOutputRow;  /* Start of subroutine that outputs a result row */
118795      int regOutputRow;   /* Return address register for output subroutine */
118796      int addrSetAbort;   /* Set the abort flag and return */
118797      int addrTopOfLoop;  /* Top of the input loop */
118798      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
118799      int addrReset;      /* Subroutine for resetting the accumulator */
118800      int regReset;       /* Return address register for reset subroutine */
118801
118802      /* If there is a GROUP BY clause we might need a sorting index to
118803      ** implement it.  Allocate that sorting index now.  If it turns out
118804      ** that we do not need it after all, the OP_SorterOpen instruction
118805      ** will be converted into a Noop.
118806      */
118807      sAggInfo.sortingIdx = pParse->nTab++;
118808      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
118809      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
118810          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
118811          0, (char*)pKeyInfo, P4_KEYINFO);
118812
118813      /* Initialize memory locations used by GROUP BY aggregate processing
118814      */
118815      iUseFlag = ++pParse->nMem;
118816      iAbortFlag = ++pParse->nMem;
118817      regOutputRow = ++pParse->nMem;
118818      addrOutputRow = sqlite3VdbeMakeLabel(v);
118819      regReset = ++pParse->nMem;
118820      addrReset = sqlite3VdbeMakeLabel(v);
118821      iAMem = pParse->nMem + 1;
118822      pParse->nMem += pGroupBy->nExpr;
118823      iBMem = pParse->nMem + 1;
118824      pParse->nMem += pGroupBy->nExpr;
118825      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
118826      VdbeComment((v, "clear abort flag"));
118827      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
118828      VdbeComment((v, "indicate accumulator empty"));
118829      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
118830
118831      /* Begin a loop that will extract all source rows in GROUP BY order.
118832      ** This might involve two separate loops with an OP_Sort in between, or
118833      ** it might be a single loop that uses an index to extract information
118834      ** in the right order to begin with.
118835      */
118836      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118837      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
118838          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
118839      );
118840      if( pWInfo==0 ) goto select_end;
118841      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
118842        /* The optimizer is able to deliver rows in group by order so
118843        ** we do not have to sort.  The OP_OpenEphemeral table will be
118844        ** cancelled later because we still need to use the pKeyInfo
118845        */
118846        groupBySort = 0;
118847      }else{
118848        /* Rows are coming out in undetermined order.  We have to push
118849        ** each row into a sorting index, terminate the first loop,
118850        ** then loop over the sorting index in order to get the output
118851        ** in sorted order
118852        */
118853        int regBase;
118854        int regRecord;
118855        int nCol;
118856        int nGroupBy;
118857
118858        explainTempTable(pParse,
118859            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
118860                    "DISTINCT" : "GROUP BY");
118861
118862        groupBySort = 1;
118863        nGroupBy = pGroupBy->nExpr;
118864        nCol = nGroupBy;
118865        j = nGroupBy;
118866        for(i=0; i<sAggInfo.nColumn; i++){
118867          if( sAggInfo.aCol[i].iSorterColumn>=j ){
118868            nCol++;
118869            j++;
118870          }
118871        }
118872        regBase = sqlite3GetTempRange(pParse, nCol);
118873        sqlite3ExprCacheClear(pParse);
118874        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
118875        j = nGroupBy;
118876        for(i=0; i<sAggInfo.nColumn; i++){
118877          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
118878          if( pCol->iSorterColumn>=j ){
118879            int r1 = j + regBase;
118880            sqlite3ExprCodeGetColumnToReg(pParse,
118881                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
118882            j++;
118883          }
118884        }
118885        regRecord = sqlite3GetTempReg(pParse);
118886        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
118887        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
118888        sqlite3ReleaseTempReg(pParse, regRecord);
118889        sqlite3ReleaseTempRange(pParse, regBase, nCol);
118890        sqlite3WhereEnd(pWInfo);
118891        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
118892        sortOut = sqlite3GetTempReg(pParse);
118893        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
118894        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
118895        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
118896        sAggInfo.useSortingIdx = 1;
118897        sqlite3ExprCacheClear(pParse);
118898
118899      }
118900
118901      /* If the index or temporary table used by the GROUP BY sort
118902      ** will naturally deliver rows in the order required by the ORDER BY
118903      ** clause, cancel the ephemeral table open coded earlier.
118904      **
118905      ** This is an optimization - the correct answer should result regardless.
118906      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
118907      ** disable this optimization for testing purposes.  */
118908      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
118909       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
118910      ){
118911        sSort.pOrderBy = 0;
118912        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
118913      }
118914
118915      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
118916      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
118917      ** Then compare the current GROUP BY terms against the GROUP BY terms
118918      ** from the previous row currently stored in a0, a1, a2...
118919      */
118920      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
118921      sqlite3ExprCacheClear(pParse);
118922      if( groupBySort ){
118923        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
118924                          sortOut, sortPTab);
118925      }
118926      for(j=0; j<pGroupBy->nExpr; j++){
118927        if( groupBySort ){
118928          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
118929        }else{
118930          sAggInfo.directMode = 1;
118931          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
118932        }
118933      }
118934      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
118935                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
118936      addr1 = sqlite3VdbeCurrentAddr(v);
118937      sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
118938
118939      /* Generate code that runs whenever the GROUP BY changes.
118940      ** Changes in the GROUP BY are detected by the previous code
118941      ** block.  If there were no changes, this block is skipped.
118942      **
118943      ** This code copies current group by terms in b0,b1,b2,...
118944      ** over to a0,a1,a2.  It then calls the output subroutine
118945      ** and resets the aggregate accumulator registers in preparation
118946      ** for the next GROUP BY batch.
118947      */
118948      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
118949      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118950      VdbeComment((v, "output one row"));
118951      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
118952      VdbeComment((v, "check abort flag"));
118953      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118954      VdbeComment((v, "reset accumulator"));
118955
118956      /* Update the aggregate accumulators based on the content of
118957      ** the current row
118958      */
118959      sqlite3VdbeJumpHere(v, addr1);
118960      updateAccumulator(pParse, &sAggInfo);
118961      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
118962      VdbeComment((v, "indicate data in accumulator"));
118963
118964      /* End of the loop
118965      */
118966      if( groupBySort ){
118967        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
118968        VdbeCoverage(v);
118969      }else{
118970        sqlite3WhereEnd(pWInfo);
118971        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
118972      }
118973
118974      /* Output the final row of result
118975      */
118976      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118977      VdbeComment((v, "output final row"));
118978
118979      /* Jump over the subroutines
118980      */
118981      sqlite3VdbeGoto(v, addrEnd);
118982
118983      /* Generate a subroutine that outputs a single row of the result
118984      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
118985      ** is less than or equal to zero, the subroutine is a no-op.  If
118986      ** the processing calls for the query to abort, this subroutine
118987      ** increments the iAbortFlag memory location before returning in
118988      ** order to signal the caller to abort.
118989      */
118990      addrSetAbort = sqlite3VdbeCurrentAddr(v);
118991      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
118992      VdbeComment((v, "set abort flag"));
118993      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118994      sqlite3VdbeResolveLabel(v, addrOutputRow);
118995      addrOutputRow = sqlite3VdbeCurrentAddr(v);
118996      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
118997      VdbeCoverage(v);
118998      VdbeComment((v, "Groupby result generator entry point"));
118999      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119000      finalizeAggFunctions(pParse, &sAggInfo);
119001      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
119002      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
119003                      &sDistinct, pDest,
119004                      addrOutputRow+1, addrSetAbort);
119005      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119006      VdbeComment((v, "end groupby result generator"));
119007
119008      /* Generate a subroutine that will reset the group-by accumulator
119009      */
119010      sqlite3VdbeResolveLabel(v, addrReset);
119011      resetAccumulator(pParse, &sAggInfo);
119012      sqlite3VdbeAddOp1(v, OP_Return, regReset);
119013
119014    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
119015    else {
119016      ExprList *pDel = 0;
119017#ifndef SQLITE_OMIT_BTREECOUNT
119018      Table *pTab;
119019      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
119020        /* If isSimpleCount() returns a pointer to a Table structure, then
119021        ** the SQL statement is of the form:
119022        **
119023        **   SELECT count(*) FROM <tbl>
119024        **
119025        ** where the Table structure returned represents table <tbl>.
119026        **
119027        ** This statement is so common that it is optimized specially. The
119028        ** OP_Count instruction is executed either on the intkey table that
119029        ** contains the data for table <tbl> or on one of its indexes. It
119030        ** is better to execute the op on an index, as indexes are almost
119031        ** always spread across less pages than their corresponding tables.
119032        */
119033        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119034        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
119035        Index *pIdx;                         /* Iterator variable */
119036        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
119037        Index *pBest = 0;                    /* Best index found so far */
119038        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
119039
119040        sqlite3CodeVerifySchema(pParse, iDb);
119041        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119042
119043        /* Search for the index that has the lowest scan cost.
119044        **
119045        ** (2011-04-15) Do not do a full scan of an unordered index.
119046        **
119047        ** (2013-10-03) Do not count the entries in a partial index.
119048        **
119049        ** In practice the KeyInfo structure will not be used. It is only
119050        ** passed to keep OP_OpenRead happy.
119051        */
119052        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
119053        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119054          if( pIdx->bUnordered==0
119055           && pIdx->szIdxRow<pTab->szTabRow
119056           && pIdx->pPartIdxWhere==0
119057           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
119058          ){
119059            pBest = pIdx;
119060          }
119061        }
119062        if( pBest ){
119063          iRoot = pBest->tnum;
119064          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
119065        }
119066
119067        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
119068        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
119069        if( pKeyInfo ){
119070          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
119071        }
119072        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
119073        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
119074        explainSimpleCount(pParse, pTab, pBest);
119075      }else
119076#endif /* SQLITE_OMIT_BTREECOUNT */
119077      {
119078        /* Check if the query is of one of the following forms:
119079        **
119080        **   SELECT min(x) FROM ...
119081        **   SELECT max(x) FROM ...
119082        **
119083        ** If it is, then ask the code in where.c to attempt to sort results
119084        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
119085        ** If where.c is able to produce results sorted in this order, then
119086        ** add vdbe code to break out of the processing loop after the
119087        ** first iteration (since the first iteration of the loop is
119088        ** guaranteed to operate on the row with the minimum or maximum
119089        ** value of x, the only row required).
119090        **
119091        ** A special flag must be passed to sqlite3WhereBegin() to slightly
119092        ** modify behavior as follows:
119093        **
119094        **   + If the query is a "SELECT min(x)", then the loop coded by
119095        **     where.c should not iterate over any values with a NULL value
119096        **     for x.
119097        **
119098        **   + The optimizer code in where.c (the thing that decides which
119099        **     index or indices to use) should place a different priority on
119100        **     satisfying the 'ORDER BY' clause than it does in other cases.
119101        **     Refer to code and comments in where.c for details.
119102        */
119103        ExprList *pMinMax = 0;
119104        u8 flag = WHERE_ORDERBY_NORMAL;
119105
119106        assert( p->pGroupBy==0 );
119107        assert( flag==0 );
119108        if( p->pHaving==0 ){
119109          flag = minMaxQuery(&sAggInfo, &pMinMax);
119110        }
119111        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
119112
119113        if( flag ){
119114          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
119115          pDel = pMinMax;
119116          assert( db->mallocFailed || pMinMax!=0 );
119117          if( !db->mallocFailed ){
119118            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
119119            pMinMax->a[0].pExpr->op = TK_COLUMN;
119120          }
119121        }
119122
119123        /* This case runs if the aggregate has no GROUP BY clause.  The
119124        ** processing is much simpler since there is only a single row
119125        ** of output.
119126        */
119127        resetAccumulator(pParse, &sAggInfo);
119128        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
119129        if( pWInfo==0 ){
119130          sqlite3ExprListDelete(db, pDel);
119131          goto select_end;
119132        }
119133        updateAccumulator(pParse, &sAggInfo);
119134        assert( pMinMax==0 || pMinMax->nExpr==1 );
119135        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
119136          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
119137          VdbeComment((v, "%s() by index",
119138                (flag==WHERE_ORDERBY_MIN?"min":"max")));
119139        }
119140        sqlite3WhereEnd(pWInfo);
119141        finalizeAggFunctions(pParse, &sAggInfo);
119142      }
119143
119144      sSort.pOrderBy = 0;
119145      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
119146      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
119147                      pDest, addrEnd, addrEnd);
119148      sqlite3ExprListDelete(db, pDel);
119149    }
119150    sqlite3VdbeResolveLabel(v, addrEnd);
119151
119152  } /* endif aggregate query */
119153
119154  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
119155    explainTempTable(pParse, "DISTINCT");
119156  }
119157
119158  /* If there is an ORDER BY clause, then we need to sort the results
119159  ** and send them to the callback one by one.
119160  */
119161  if( sSort.pOrderBy ){
119162    explainTempTable(pParse,
119163                     sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
119164    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
119165  }
119166
119167  /* Jump here to skip this query
119168  */
119169  sqlite3VdbeResolveLabel(v, iEnd);
119170
119171  /* The SELECT has been coded. If there is an error in the Parse structure,
119172  ** set the return code to 1. Otherwise 0. */
119173  rc = (pParse->nErr>0);
119174
119175  /* Control jumps to here if an error is encountered above, or upon
119176  ** successful coding of the SELECT.
119177  */
119178select_end:
119179  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
119180
119181  /* Identify column names if results of the SELECT are to be output.
119182  */
119183  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
119184    generateColumnNames(pParse, pTabList, pEList);
119185  }
119186
119187  sqlite3DbFree(db, sAggInfo.aCol);
119188  sqlite3DbFree(db, sAggInfo.aFunc);
119189#if SELECTTRACE_ENABLED
119190  SELECTTRACE(1,pParse,p,("end processing\n"));
119191  pParse->nSelectIndent--;
119192#endif
119193  return rc;
119194}
119195
119196/************** End of select.c **********************************************/
119197/************** Begin file table.c *******************************************/
119198/*
119199** 2001 September 15
119200**
119201** The author disclaims copyright to this source code.  In place of
119202** a legal notice, here is a blessing:
119203**
119204**    May you do good and not evil.
119205**    May you find forgiveness for yourself and forgive others.
119206**    May you share freely, never taking more than you give.
119207**
119208*************************************************************************
119209** This file contains the sqlite3_get_table() and sqlite3_free_table()
119210** interface routines.  These are just wrappers around the main
119211** interface routine of sqlite3_exec().
119212**
119213** These routines are in a separate files so that they will not be linked
119214** if they are not used.
119215*/
119216/* #include "sqliteInt.h" */
119217/* #include <stdlib.h> */
119218/* #include <string.h> */
119219
119220#ifndef SQLITE_OMIT_GET_TABLE
119221
119222/*
119223** This structure is used to pass data from sqlite3_get_table() through
119224** to the callback function is uses to build the result.
119225*/
119226typedef struct TabResult {
119227  char **azResult;   /* Accumulated output */
119228  char *zErrMsg;     /* Error message text, if an error occurs */
119229  u32 nAlloc;        /* Slots allocated for azResult[] */
119230  u32 nRow;          /* Number of rows in the result */
119231  u32 nColumn;       /* Number of columns in the result */
119232  u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
119233  int rc;            /* Return code from sqlite3_exec() */
119234} TabResult;
119235
119236/*
119237** This routine is called once for each row in the result table.  Its job
119238** is to fill in the TabResult structure appropriately, allocating new
119239** memory as necessary.
119240*/
119241static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
119242  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
119243  int need;                         /* Slots needed in p->azResult[] */
119244  int i;                            /* Loop counter */
119245  char *z;                          /* A single column of result */
119246
119247  /* Make sure there is enough space in p->azResult to hold everything
119248  ** we need to remember from this invocation of the callback.
119249  */
119250  if( p->nRow==0 && argv!=0 ){
119251    need = nCol*2;
119252  }else{
119253    need = nCol;
119254  }
119255  if( p->nData + need > p->nAlloc ){
119256    char **azNew;
119257    p->nAlloc = p->nAlloc*2 + need;
119258    azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
119259    if( azNew==0 ) goto malloc_failed;
119260    p->azResult = azNew;
119261  }
119262
119263  /* If this is the first row, then generate an extra row containing
119264  ** the names of all columns.
119265  */
119266  if( p->nRow==0 ){
119267    p->nColumn = nCol;
119268    for(i=0; i<nCol; i++){
119269      z = sqlite3_mprintf("%s", colv[i]);
119270      if( z==0 ) goto malloc_failed;
119271      p->azResult[p->nData++] = z;
119272    }
119273  }else if( (int)p->nColumn!=nCol ){
119274    sqlite3_free(p->zErrMsg);
119275    p->zErrMsg = sqlite3_mprintf(
119276       "sqlite3_get_table() called with two or more incompatible queries"
119277    );
119278    p->rc = SQLITE_ERROR;
119279    return 1;
119280  }
119281
119282  /* Copy over the row data
119283  */
119284  if( argv!=0 ){
119285    for(i=0; i<nCol; i++){
119286      if( argv[i]==0 ){
119287        z = 0;
119288      }else{
119289        int n = sqlite3Strlen30(argv[i])+1;
119290        z = sqlite3_malloc64( n );
119291        if( z==0 ) goto malloc_failed;
119292        memcpy(z, argv[i], n);
119293      }
119294      p->azResult[p->nData++] = z;
119295    }
119296    p->nRow++;
119297  }
119298  return 0;
119299
119300malloc_failed:
119301  p->rc = SQLITE_NOMEM_BKPT;
119302  return 1;
119303}
119304
119305/*
119306** Query the database.  But instead of invoking a callback for each row,
119307** malloc() for space to hold the result and return the entire results
119308** at the conclusion of the call.
119309**
119310** The result that is written to ***pazResult is held in memory obtained
119311** from malloc().  But the caller cannot free this memory directly.
119312** Instead, the entire table should be passed to sqlite3_free_table() when
119313** the calling procedure is finished using it.
119314*/
119315SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
119316  sqlite3 *db,                /* The database on which the SQL executes */
119317  const char *zSql,           /* The SQL to be executed */
119318  char ***pazResult,          /* Write the result table here */
119319  int *pnRow,                 /* Write the number of rows in the result here */
119320  int *pnColumn,              /* Write the number of columns of result here */
119321  char **pzErrMsg             /* Write error messages here */
119322){
119323  int rc;
119324  TabResult res;
119325
119326#ifdef SQLITE_ENABLE_API_ARMOR
119327  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
119328#endif
119329  *pazResult = 0;
119330  if( pnColumn ) *pnColumn = 0;
119331  if( pnRow ) *pnRow = 0;
119332  if( pzErrMsg ) *pzErrMsg = 0;
119333  res.zErrMsg = 0;
119334  res.nRow = 0;
119335  res.nColumn = 0;
119336  res.nData = 1;
119337  res.nAlloc = 20;
119338  res.rc = SQLITE_OK;
119339  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
119340  if( res.azResult==0 ){
119341     db->errCode = SQLITE_NOMEM;
119342     return SQLITE_NOMEM_BKPT;
119343  }
119344  res.azResult[0] = 0;
119345  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
119346  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
119347  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
119348  if( (rc&0xff)==SQLITE_ABORT ){
119349    sqlite3_free_table(&res.azResult[1]);
119350    if( res.zErrMsg ){
119351      if( pzErrMsg ){
119352        sqlite3_free(*pzErrMsg);
119353        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
119354      }
119355      sqlite3_free(res.zErrMsg);
119356    }
119357    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
119358    return res.rc;
119359  }
119360  sqlite3_free(res.zErrMsg);
119361  if( rc!=SQLITE_OK ){
119362    sqlite3_free_table(&res.azResult[1]);
119363    return rc;
119364  }
119365  if( res.nAlloc>res.nData ){
119366    char **azNew;
119367    azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
119368    if( azNew==0 ){
119369      sqlite3_free_table(&res.azResult[1]);
119370      db->errCode = SQLITE_NOMEM;
119371      return SQLITE_NOMEM_BKPT;
119372    }
119373    res.azResult = azNew;
119374  }
119375  *pazResult = &res.azResult[1];
119376  if( pnColumn ) *pnColumn = res.nColumn;
119377  if( pnRow ) *pnRow = res.nRow;
119378  return rc;
119379}
119380
119381/*
119382** This routine frees the space the sqlite3_get_table() malloced.
119383*/
119384SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
119385  char **azResult            /* Result returned from sqlite3_get_table() */
119386){
119387  if( azResult ){
119388    int i, n;
119389    azResult--;
119390    assert( azResult!=0 );
119391    n = SQLITE_PTR_TO_INT(azResult[0]);
119392    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
119393    sqlite3_free(azResult);
119394  }
119395}
119396
119397#endif /* SQLITE_OMIT_GET_TABLE */
119398
119399/************** End of table.c ***********************************************/
119400/************** Begin file trigger.c *****************************************/
119401/*
119402**
119403** The author disclaims copyright to this source code.  In place of
119404** a legal notice, here is a blessing:
119405**
119406**    May you do good and not evil.
119407**    May you find forgiveness for yourself and forgive others.
119408**    May you share freely, never taking more than you give.
119409**
119410*************************************************************************
119411** This file contains the implementation for TRIGGERs
119412*/
119413/* #include "sqliteInt.h" */
119414
119415#ifndef SQLITE_OMIT_TRIGGER
119416/*
119417** Delete a linked list of TriggerStep structures.
119418*/
119419SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
119420  while( pTriggerStep ){
119421    TriggerStep * pTmp = pTriggerStep;
119422    pTriggerStep = pTriggerStep->pNext;
119423
119424    sqlite3ExprDelete(db, pTmp->pWhere);
119425    sqlite3ExprListDelete(db, pTmp->pExprList);
119426    sqlite3SelectDelete(db, pTmp->pSelect);
119427    sqlite3IdListDelete(db, pTmp->pIdList);
119428
119429    sqlite3DbFree(db, pTmp);
119430  }
119431}
119432
119433/*
119434** Given table pTab, return a list of all the triggers attached to
119435** the table. The list is connected by Trigger.pNext pointers.
119436**
119437** All of the triggers on pTab that are in the same database as pTab
119438** are already attached to pTab->pTrigger.  But there might be additional
119439** triggers on pTab in the TEMP schema.  This routine prepends all
119440** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
119441** and returns the combined list.
119442**
119443** To state it another way:  This routine returns a list of all triggers
119444** that fire off of pTab.  The list will include any TEMP triggers on
119445** pTab as well as the triggers lised in pTab->pTrigger.
119446*/
119447SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
119448  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
119449  Trigger *pList = 0;                  /* List of triggers to return */
119450
119451  if( pParse->disableTriggers ){
119452    return 0;
119453  }
119454
119455  if( pTmpSchema!=pTab->pSchema ){
119456    HashElem *p;
119457    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
119458    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
119459      Trigger *pTrig = (Trigger *)sqliteHashData(p);
119460      if( pTrig->pTabSchema==pTab->pSchema
119461       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
119462      ){
119463        pTrig->pNext = (pList ? pList : pTab->pTrigger);
119464        pList = pTrig;
119465      }
119466    }
119467  }
119468
119469  return (pList ? pList : pTab->pTrigger);
119470}
119471
119472/*
119473** This is called by the parser when it sees a CREATE TRIGGER statement
119474** up to the point of the BEGIN before the trigger actions.  A Trigger
119475** structure is generated based on the information available and stored
119476** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
119477** sqlite3FinishTrigger() function is called to complete the trigger
119478** construction process.
119479*/
119480SQLITE_PRIVATE void sqlite3BeginTrigger(
119481  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
119482  Token *pName1,      /* The name of the trigger */
119483  Token *pName2,      /* The name of the trigger */
119484  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
119485  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
119486  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
119487  SrcList *pTableName,/* The name of the table/view the trigger applies to */
119488  Expr *pWhen,        /* WHEN clause */
119489  int isTemp,         /* True if the TEMPORARY keyword is present */
119490  int noErr           /* Suppress errors if the trigger already exists */
119491){
119492  Trigger *pTrigger = 0;  /* The new trigger */
119493  Table *pTab;            /* Table that the trigger fires off of */
119494  char *zName = 0;        /* Name of the trigger */
119495  sqlite3 *db = pParse->db;  /* The database connection */
119496  int iDb;                /* The database to store the trigger in */
119497  Token *pName;           /* The unqualified db name */
119498  DbFixer sFix;           /* State vector for the DB fixer */
119499  int iTabDb;             /* Index of the database holding pTab */
119500
119501  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
119502  assert( pName2!=0 );
119503  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
119504  assert( op>0 && op<0xff );
119505  if( isTemp ){
119506    /* If TEMP was specified, then the trigger name may not be qualified. */
119507    if( pName2->n>0 ){
119508      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
119509      goto trigger_cleanup;
119510    }
119511    iDb = 1;
119512    pName = pName1;
119513  }else{
119514    /* Figure out the db that the trigger will be created in */
119515    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
119516    if( iDb<0 ){
119517      goto trigger_cleanup;
119518    }
119519  }
119520  if( !pTableName || db->mallocFailed ){
119521    goto trigger_cleanup;
119522  }
119523
119524  /* A long-standing parser bug is that this syntax was allowed:
119525  **
119526  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
119527  **                                                 ^^^^^^^^
119528  **
119529  ** To maintain backwards compatibility, ignore the database
119530  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
119531  */
119532  if( db->init.busy && iDb!=1 ){
119533    sqlite3DbFree(db, pTableName->a[0].zDatabase);
119534    pTableName->a[0].zDatabase = 0;
119535  }
119536
119537  /* If the trigger name was unqualified, and the table is a temp table,
119538  ** then set iDb to 1 to create the trigger in the temporary database.
119539  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
119540  ** exist, the error is caught by the block below.
119541  */
119542  pTab = sqlite3SrcListLookup(pParse, pTableName);
119543  if( db->init.busy==0 && pName2->n==0 && pTab
119544        && pTab->pSchema==db->aDb[1].pSchema ){
119545    iDb = 1;
119546  }
119547
119548  /* Ensure the table name matches database name and that the table exists */
119549  if( db->mallocFailed ) goto trigger_cleanup;
119550  assert( pTableName->nSrc==1 );
119551  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
119552  if( sqlite3FixSrcList(&sFix, pTableName) ){
119553    goto trigger_cleanup;
119554  }
119555  pTab = sqlite3SrcListLookup(pParse, pTableName);
119556  if( !pTab ){
119557    /* The table does not exist. */
119558    if( db->init.iDb==1 ){
119559      /* Ticket #3810.
119560      ** Normally, whenever a table is dropped, all associated triggers are
119561      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
119562      ** and the table is dropped by a different database connection, the
119563      ** trigger is not visible to the database connection that does the
119564      ** drop so the trigger cannot be dropped.  This results in an
119565      ** "orphaned trigger" - a trigger whose associated table is missing.
119566      */
119567      db->init.orphanTrigger = 1;
119568    }
119569    goto trigger_cleanup;
119570  }
119571  if( IsVirtual(pTab) ){
119572    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
119573    goto trigger_cleanup;
119574  }
119575
119576  /* Check that the trigger name is not reserved and that no trigger of the
119577  ** specified name exists */
119578  zName = sqlite3NameFromToken(db, pName);
119579  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
119580    goto trigger_cleanup;
119581  }
119582  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119583  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
119584    if( !noErr ){
119585      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
119586    }else{
119587      assert( !db->init.busy );
119588      sqlite3CodeVerifySchema(pParse, iDb);
119589    }
119590    goto trigger_cleanup;
119591  }
119592
119593  /* Do not create a trigger on a system table */
119594  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
119595    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
119596    goto trigger_cleanup;
119597  }
119598
119599  /* INSTEAD of triggers are only for views and views only support INSTEAD
119600  ** of triggers.
119601  */
119602  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
119603    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
119604        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
119605    goto trigger_cleanup;
119606  }
119607  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
119608    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
119609        " trigger on table: %S", pTableName, 0);
119610    goto trigger_cleanup;
119611  }
119612  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
119613
119614#ifndef SQLITE_OMIT_AUTHORIZATION
119615  {
119616    int code = SQLITE_CREATE_TRIGGER;
119617    const char *zDb = db->aDb[iTabDb].zName;
119618    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
119619    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
119620    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
119621      goto trigger_cleanup;
119622    }
119623    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
119624      goto trigger_cleanup;
119625    }
119626  }
119627#endif
119628
119629  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
119630  ** cannot appear on views.  So we might as well translate every
119631  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
119632  ** elsewhere.
119633  */
119634  if (tr_tm == TK_INSTEAD){
119635    tr_tm = TK_BEFORE;
119636  }
119637
119638  /* Build the Trigger object */
119639  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
119640  if( pTrigger==0 ) goto trigger_cleanup;
119641  pTrigger->zName = zName;
119642  zName = 0;
119643  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
119644  pTrigger->pSchema = db->aDb[iDb].pSchema;
119645  pTrigger->pTabSchema = pTab->pSchema;
119646  pTrigger->op = (u8)op;
119647  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
119648  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
119649  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
119650  assert( pParse->pNewTrigger==0 );
119651  pParse->pNewTrigger = pTrigger;
119652
119653trigger_cleanup:
119654  sqlite3DbFree(db, zName);
119655  sqlite3SrcListDelete(db, pTableName);
119656  sqlite3IdListDelete(db, pColumns);
119657  sqlite3ExprDelete(db, pWhen);
119658  if( !pParse->pNewTrigger ){
119659    sqlite3DeleteTrigger(db, pTrigger);
119660  }else{
119661    assert( pParse->pNewTrigger==pTrigger );
119662  }
119663}
119664
119665/*
119666** This routine is called after all of the trigger actions have been parsed
119667** in order to complete the process of building the trigger.
119668*/
119669SQLITE_PRIVATE void sqlite3FinishTrigger(
119670  Parse *pParse,          /* Parser context */
119671  TriggerStep *pStepList, /* The triggered program */
119672  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
119673){
119674  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
119675  char *zName;                            /* Name of trigger */
119676  sqlite3 *db = pParse->db;               /* The database */
119677  DbFixer sFix;                           /* Fixer object */
119678  int iDb;                                /* Database containing the trigger */
119679  Token nameToken;                        /* Trigger name for error reporting */
119680
119681  pParse->pNewTrigger = 0;
119682  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
119683  zName = pTrig->zName;
119684  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
119685  pTrig->step_list = pStepList;
119686  while( pStepList ){
119687    pStepList->pTrig = pTrig;
119688    pStepList = pStepList->pNext;
119689  }
119690  sqlite3TokenInit(&nameToken, pTrig->zName);
119691  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
119692  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
119693   || sqlite3FixExpr(&sFix, pTrig->pWhen)
119694  ){
119695    goto triggerfinish_cleanup;
119696  }
119697
119698  /* if we are not initializing,
119699  ** build the sqlite_master entry
119700  */
119701  if( !db->init.busy ){
119702    Vdbe *v;
119703    char *z;
119704
119705    /* Make an entry in the sqlite_master table */
119706    v = sqlite3GetVdbe(pParse);
119707    if( v==0 ) goto triggerfinish_cleanup;
119708    sqlite3BeginWriteOperation(pParse, 0, iDb);
119709    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
119710    sqlite3NestedParse(pParse,
119711       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
119712       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
119713       pTrig->table, z);
119714    sqlite3DbFree(db, z);
119715    sqlite3ChangeCookie(pParse, iDb);
119716    sqlite3VdbeAddParseSchemaOp(v, iDb,
119717        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
119718  }
119719
119720  if( db->init.busy ){
119721    Trigger *pLink = pTrig;
119722    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
119723    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119724    pTrig = sqlite3HashInsert(pHash, zName, pTrig);
119725    if( pTrig ){
119726      sqlite3OomFault(db);
119727    }else if( pLink->pSchema==pLink->pTabSchema ){
119728      Table *pTab;
119729      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
119730      assert( pTab!=0 );
119731      pLink->pNext = pTab->pTrigger;
119732      pTab->pTrigger = pLink;
119733    }
119734  }
119735
119736triggerfinish_cleanup:
119737  sqlite3DeleteTrigger(db, pTrig);
119738  assert( !pParse->pNewTrigger );
119739  sqlite3DeleteTriggerStep(db, pStepList);
119740}
119741
119742/*
119743** Turn a SELECT statement (that the pSelect parameter points to) into
119744** a trigger step.  Return a pointer to a TriggerStep structure.
119745**
119746** The parser calls this routine when it finds a SELECT statement in
119747** body of a TRIGGER.
119748*/
119749SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
119750  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
119751  if( pTriggerStep==0 ) {
119752    sqlite3SelectDelete(db, pSelect);
119753    return 0;
119754  }
119755  pTriggerStep->op = TK_SELECT;
119756  pTriggerStep->pSelect = pSelect;
119757  pTriggerStep->orconf = OE_Default;
119758  return pTriggerStep;
119759}
119760
119761/*
119762** Allocate space to hold a new trigger step.  The allocated space
119763** holds both the TriggerStep object and the TriggerStep.target.z string.
119764**
119765** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
119766*/
119767static TriggerStep *triggerStepAllocate(
119768  sqlite3 *db,                /* Database connection */
119769  u8 op,                      /* Trigger opcode */
119770  Token *pName                /* The target name */
119771){
119772  TriggerStep *pTriggerStep;
119773
119774  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
119775  if( pTriggerStep ){
119776    char *z = (char*)&pTriggerStep[1];
119777    memcpy(z, pName->z, pName->n);
119778    sqlite3Dequote(z);
119779    pTriggerStep->zTarget = z;
119780    pTriggerStep->op = op;
119781  }
119782  return pTriggerStep;
119783}
119784
119785/*
119786** Build a trigger step out of an INSERT statement.  Return a pointer
119787** to the new trigger step.
119788**
119789** The parser calls this routine when it sees an INSERT inside the
119790** body of a trigger.
119791*/
119792SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
119793  sqlite3 *db,        /* The database connection */
119794  Token *pTableName,  /* Name of the table into which we insert */
119795  IdList *pColumn,    /* List of columns in pTableName to insert into */
119796  Select *pSelect,    /* A SELECT statement that supplies values */
119797  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
119798){
119799  TriggerStep *pTriggerStep;
119800
119801  assert(pSelect != 0 || db->mallocFailed);
119802
119803  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
119804  if( pTriggerStep ){
119805    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
119806    pTriggerStep->pIdList = pColumn;
119807    pTriggerStep->orconf = orconf;
119808  }else{
119809    sqlite3IdListDelete(db, pColumn);
119810  }
119811  sqlite3SelectDelete(db, pSelect);
119812
119813  return pTriggerStep;
119814}
119815
119816/*
119817** Construct a trigger step that implements an UPDATE statement and return
119818** a pointer to that trigger step.  The parser calls this routine when it
119819** sees an UPDATE statement inside the body of a CREATE TRIGGER.
119820*/
119821SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
119822  sqlite3 *db,         /* The database connection */
119823  Token *pTableName,   /* Name of the table to be updated */
119824  ExprList *pEList,    /* The SET clause: list of column and new values */
119825  Expr *pWhere,        /* The WHERE clause */
119826  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
119827){
119828  TriggerStep *pTriggerStep;
119829
119830  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
119831  if( pTriggerStep ){
119832    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
119833    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119834    pTriggerStep->orconf = orconf;
119835  }
119836  sqlite3ExprListDelete(db, pEList);
119837  sqlite3ExprDelete(db, pWhere);
119838  return pTriggerStep;
119839}
119840
119841/*
119842** Construct a trigger step that implements a DELETE statement and return
119843** a pointer to that trigger step.  The parser calls this routine when it
119844** sees a DELETE statement inside the body of a CREATE TRIGGER.
119845*/
119846SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
119847  sqlite3 *db,            /* Database connection */
119848  Token *pTableName,      /* The table from which rows are deleted */
119849  Expr *pWhere            /* The WHERE clause */
119850){
119851  TriggerStep *pTriggerStep;
119852
119853  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
119854  if( pTriggerStep ){
119855    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119856    pTriggerStep->orconf = OE_Default;
119857  }
119858  sqlite3ExprDelete(db, pWhere);
119859  return pTriggerStep;
119860}
119861
119862/*
119863** Recursively delete a Trigger structure
119864*/
119865SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
119866  if( pTrigger==0 ) return;
119867  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
119868  sqlite3DbFree(db, pTrigger->zName);
119869  sqlite3DbFree(db, pTrigger->table);
119870  sqlite3ExprDelete(db, pTrigger->pWhen);
119871  sqlite3IdListDelete(db, pTrigger->pColumns);
119872  sqlite3DbFree(db, pTrigger);
119873}
119874
119875/*
119876** This function is called to drop a trigger from the database schema.
119877**
119878** This may be called directly from the parser and therefore identifies
119879** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
119880** same job as this routine except it takes a pointer to the trigger
119881** instead of the trigger name.
119882**/
119883SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
119884  Trigger *pTrigger = 0;
119885  int i;
119886  const char *zDb;
119887  const char *zName;
119888  sqlite3 *db = pParse->db;
119889
119890  if( db->mallocFailed ) goto drop_trigger_cleanup;
119891  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
119892    goto drop_trigger_cleanup;
119893  }
119894
119895  assert( pName->nSrc==1 );
119896  zDb = pName->a[0].zDatabase;
119897  zName = pName->a[0].zName;
119898  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
119899  for(i=OMIT_TEMPDB; i<db->nDb; i++){
119900    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
119901    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
119902    assert( sqlite3SchemaMutexHeld(db, j, 0) );
119903    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
119904    if( pTrigger ) break;
119905  }
119906  if( !pTrigger ){
119907    if( !noErr ){
119908      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
119909    }else{
119910      sqlite3CodeVerifyNamedSchema(pParse, zDb);
119911    }
119912    pParse->checkSchema = 1;
119913    goto drop_trigger_cleanup;
119914  }
119915  sqlite3DropTriggerPtr(pParse, pTrigger);
119916
119917drop_trigger_cleanup:
119918  sqlite3SrcListDelete(db, pName);
119919}
119920
119921/*
119922** Return a pointer to the Table structure for the table that a trigger
119923** is set on.
119924*/
119925static Table *tableOfTrigger(Trigger *pTrigger){
119926  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
119927}
119928
119929
119930/*
119931** Drop a trigger given a pointer to that trigger.
119932*/
119933SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
119934  Table   *pTable;
119935  Vdbe *v;
119936  sqlite3 *db = pParse->db;
119937  int iDb;
119938
119939  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
119940  assert( iDb>=0 && iDb<db->nDb );
119941  pTable = tableOfTrigger(pTrigger);
119942  assert( pTable );
119943  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
119944#ifndef SQLITE_OMIT_AUTHORIZATION
119945  {
119946    int code = SQLITE_DROP_TRIGGER;
119947    const char *zDb = db->aDb[iDb].zName;
119948    const char *zTab = SCHEMA_TABLE(iDb);
119949    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
119950    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
119951      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
119952      return;
119953    }
119954  }
119955#endif
119956
119957  /* Generate code to destroy the database record of the trigger.
119958  */
119959  assert( pTable!=0 );
119960  if( (v = sqlite3GetVdbe(pParse))!=0 ){
119961    sqlite3NestedParse(pParse,
119962       "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
119963       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
119964    );
119965    sqlite3ChangeCookie(pParse, iDb);
119966    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
119967  }
119968}
119969
119970/*
119971** Remove a trigger from the hash tables of the sqlite* pointer.
119972*/
119973SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
119974  Trigger *pTrigger;
119975  Hash *pHash;
119976
119977  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119978  pHash = &(db->aDb[iDb].pSchema->trigHash);
119979  pTrigger = sqlite3HashInsert(pHash, zName, 0);
119980  if( ALWAYS(pTrigger) ){
119981    if( pTrigger->pSchema==pTrigger->pTabSchema ){
119982      Table *pTab = tableOfTrigger(pTrigger);
119983      Trigger **pp;
119984      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
119985      *pp = (*pp)->pNext;
119986    }
119987    sqlite3DeleteTrigger(db, pTrigger);
119988    db->flags |= SQLITE_InternChanges;
119989  }
119990}
119991
119992/*
119993** pEList is the SET clause of an UPDATE statement.  Each entry
119994** in pEList is of the format <id>=<expr>.  If any of the entries
119995** in pEList have an <id> which matches an identifier in pIdList,
119996** then return TRUE.  If pIdList==NULL, then it is considered a
119997** wildcard that matches anything.  Likewise if pEList==NULL then
119998** it matches anything so always return true.  Return false only
119999** if there is no match.
120000*/
120001static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
120002  int e;
120003  if( pIdList==0 || NEVER(pEList==0) ) return 1;
120004  for(e=0; e<pEList->nExpr; e++){
120005    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
120006  }
120007  return 0;
120008}
120009
120010/*
120011** Return a list of all triggers on table pTab if there exists at least
120012** one trigger that must be fired when an operation of type 'op' is
120013** performed on the table, and, if that operation is an UPDATE, if at
120014** least one of the columns in pChanges is being modified.
120015*/
120016SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
120017  Parse *pParse,          /* Parse context */
120018  Table *pTab,            /* The table the contains the triggers */
120019  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
120020  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
120021  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120022){
120023  int mask = 0;
120024  Trigger *pList = 0;
120025  Trigger *p;
120026
120027  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
120028    pList = sqlite3TriggerList(pParse, pTab);
120029  }
120030  assert( pList==0 || IsVirtual(pTab)==0 );
120031  for(p=pList; p; p=p->pNext){
120032    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
120033      mask |= p->tr_tm;
120034    }
120035  }
120036  if( pMask ){
120037    *pMask = mask;
120038  }
120039  return (mask ? pList : 0);
120040}
120041
120042/*
120043** Convert the pStep->zTarget string into a SrcList and return a pointer
120044** to that SrcList.
120045**
120046** This routine adds a specific database name, if needed, to the target when
120047** forming the SrcList.  This prevents a trigger in one database from
120048** referring to a target in another database.  An exception is when the
120049** trigger is in TEMP in which case it can refer to any other database it
120050** wants.
120051*/
120052static SrcList *targetSrcList(
120053  Parse *pParse,       /* The parsing context */
120054  TriggerStep *pStep   /* The trigger containing the target token */
120055){
120056  sqlite3 *db = pParse->db;
120057  int iDb;             /* Index of the database to use */
120058  SrcList *pSrc;       /* SrcList to be returned */
120059
120060  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
120061  if( pSrc ){
120062    assert( pSrc->nSrc>0 );
120063    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
120064    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
120065    if( iDb==0 || iDb>=2 ){
120066      assert( iDb<db->nDb );
120067      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
120068    }
120069  }
120070  return pSrc;
120071}
120072
120073/*
120074** Generate VDBE code for the statements inside the body of a single
120075** trigger.
120076*/
120077static int codeTriggerProgram(
120078  Parse *pParse,            /* The parser context */
120079  TriggerStep *pStepList,   /* List of statements inside the trigger body */
120080  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
120081){
120082  TriggerStep *pStep;
120083  Vdbe *v = pParse->pVdbe;
120084  sqlite3 *db = pParse->db;
120085
120086  assert( pParse->pTriggerTab && pParse->pToplevel );
120087  assert( pStepList );
120088  assert( v!=0 );
120089  for(pStep=pStepList; pStep; pStep=pStep->pNext){
120090    /* Figure out the ON CONFLICT policy that will be used for this step
120091    ** of the trigger program. If the statement that caused this trigger
120092    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
120093    ** the ON CONFLICT policy that was specified as part of the trigger
120094    ** step statement. Example:
120095    **
120096    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
120097    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
120098    **   END;
120099    **
120100    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
120101    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
120102    */
120103    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
120104    assert( pParse->okConstFactor==0 );
120105
120106    switch( pStep->op ){
120107      case TK_UPDATE: {
120108        sqlite3Update(pParse,
120109          targetSrcList(pParse, pStep),
120110          sqlite3ExprListDup(db, pStep->pExprList, 0),
120111          sqlite3ExprDup(db, pStep->pWhere, 0),
120112          pParse->eOrconf
120113        );
120114        break;
120115      }
120116      case TK_INSERT: {
120117        sqlite3Insert(pParse,
120118          targetSrcList(pParse, pStep),
120119          sqlite3SelectDup(db, pStep->pSelect, 0),
120120          sqlite3IdListDup(db, pStep->pIdList),
120121          pParse->eOrconf
120122        );
120123        break;
120124      }
120125      case TK_DELETE: {
120126        sqlite3DeleteFrom(pParse,
120127          targetSrcList(pParse, pStep),
120128          sqlite3ExprDup(db, pStep->pWhere, 0)
120129        );
120130        break;
120131      }
120132      default: assert( pStep->op==TK_SELECT ); {
120133        SelectDest sDest;
120134        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
120135        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
120136        sqlite3Select(pParse, pSelect, &sDest);
120137        sqlite3SelectDelete(db, pSelect);
120138        break;
120139      }
120140    }
120141    if( pStep->op!=TK_SELECT ){
120142      sqlite3VdbeAddOp0(v, OP_ResetCount);
120143    }
120144  }
120145
120146  return 0;
120147}
120148
120149#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
120150/*
120151** This function is used to add VdbeComment() annotations to a VDBE
120152** program. It is not used in production code, only for debugging.
120153*/
120154static const char *onErrorText(int onError){
120155  switch( onError ){
120156    case OE_Abort:    return "abort";
120157    case OE_Rollback: return "rollback";
120158    case OE_Fail:     return "fail";
120159    case OE_Replace:  return "replace";
120160    case OE_Ignore:   return "ignore";
120161    case OE_Default:  return "default";
120162  }
120163  return "n/a";
120164}
120165#endif
120166
120167/*
120168** Parse context structure pFrom has just been used to create a sub-vdbe
120169** (trigger program). If an error has occurred, transfer error information
120170** from pFrom to pTo.
120171*/
120172static void transferParseError(Parse *pTo, Parse *pFrom){
120173  assert( pFrom->zErrMsg==0 || pFrom->nErr );
120174  assert( pTo->zErrMsg==0 || pTo->nErr );
120175  if( pTo->nErr==0 ){
120176    pTo->zErrMsg = pFrom->zErrMsg;
120177    pTo->nErr = pFrom->nErr;
120178    pTo->rc = pFrom->rc;
120179  }else{
120180    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
120181  }
120182}
120183
120184/*
120185** Create and populate a new TriggerPrg object with a sub-program
120186** implementing trigger pTrigger with ON CONFLICT policy orconf.
120187*/
120188static TriggerPrg *codeRowTrigger(
120189  Parse *pParse,       /* Current parse context */
120190  Trigger *pTrigger,   /* Trigger to code */
120191  Table *pTab,         /* The table pTrigger is attached to */
120192  int orconf           /* ON CONFLICT policy to code trigger program with */
120193){
120194  Parse *pTop = sqlite3ParseToplevel(pParse);
120195  sqlite3 *db = pParse->db;   /* Database handle */
120196  TriggerPrg *pPrg;           /* Value to return */
120197  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
120198  Vdbe *v;                    /* Temporary VM */
120199  NameContext sNC;            /* Name context for sub-vdbe */
120200  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
120201  Parse *pSubParse;           /* Parse context for sub-vdbe */
120202  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
120203
120204  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
120205  assert( pTop->pVdbe );
120206
120207  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
120208  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
120209  ** list of the top-level Parse object sooner rather than later.  */
120210  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
120211  if( !pPrg ) return 0;
120212  pPrg->pNext = pTop->pTriggerPrg;
120213  pTop->pTriggerPrg = pPrg;
120214  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
120215  if( !pProgram ) return 0;
120216  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
120217  pPrg->pTrigger = pTrigger;
120218  pPrg->orconf = orconf;
120219  pPrg->aColmask[0] = 0xffffffff;
120220  pPrg->aColmask[1] = 0xffffffff;
120221
120222  /* Allocate and populate a new Parse context to use for coding the
120223  ** trigger sub-program.  */
120224  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
120225  if( !pSubParse ) return 0;
120226  memset(&sNC, 0, sizeof(sNC));
120227  sNC.pParse = pSubParse;
120228  pSubParse->db = db;
120229  pSubParse->pTriggerTab = pTab;
120230  pSubParse->pToplevel = pTop;
120231  pSubParse->zAuthContext = pTrigger->zName;
120232  pSubParse->eTriggerOp = pTrigger->op;
120233  pSubParse->nQueryLoop = pParse->nQueryLoop;
120234
120235  v = sqlite3GetVdbe(pSubParse);
120236  if( v ){
120237    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
120238      pTrigger->zName, onErrorText(orconf),
120239      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
120240        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
120241        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
120242        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
120243      pTab->zName
120244    ));
120245#ifndef SQLITE_OMIT_TRACE
120246    sqlite3VdbeChangeP4(v, -1,
120247      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
120248    );
120249#endif
120250
120251    /* If one was specified, code the WHEN clause. If it evaluates to false
120252    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
120253    ** OP_Halt inserted at the end of the program.  */
120254    if( pTrigger->pWhen ){
120255      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
120256      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
120257       && db->mallocFailed==0
120258      ){
120259        iEndTrigger = sqlite3VdbeMakeLabel(v);
120260        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
120261      }
120262      sqlite3ExprDelete(db, pWhen);
120263    }
120264
120265    /* Code the trigger program into the sub-vdbe. */
120266    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
120267
120268    /* Insert an OP_Halt at the end of the sub-program. */
120269    if( iEndTrigger ){
120270      sqlite3VdbeResolveLabel(v, iEndTrigger);
120271    }
120272    sqlite3VdbeAddOp0(v, OP_Halt);
120273    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
120274
120275    transferParseError(pParse, pSubParse);
120276    if( db->mallocFailed==0 ){
120277      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
120278    }
120279    pProgram->nMem = pSubParse->nMem;
120280    pProgram->nCsr = pSubParse->nTab;
120281    pProgram->nOnce = pSubParse->nOnce;
120282    pProgram->token = (void *)pTrigger;
120283    pPrg->aColmask[0] = pSubParse->oldmask;
120284    pPrg->aColmask[1] = pSubParse->newmask;
120285    sqlite3VdbeDelete(v);
120286  }
120287
120288  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
120289  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
120290  sqlite3ParserReset(pSubParse);
120291  sqlite3StackFree(db, pSubParse);
120292
120293  return pPrg;
120294}
120295
120296/*
120297** Return a pointer to a TriggerPrg object containing the sub-program for
120298** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
120299** TriggerPrg object exists, a new object is allocated and populated before
120300** being returned.
120301*/
120302static TriggerPrg *getRowTrigger(
120303  Parse *pParse,       /* Current parse context */
120304  Trigger *pTrigger,   /* Trigger to code */
120305  Table *pTab,         /* The table trigger pTrigger is attached to */
120306  int orconf           /* ON CONFLICT algorithm. */
120307){
120308  Parse *pRoot = sqlite3ParseToplevel(pParse);
120309  TriggerPrg *pPrg;
120310
120311  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
120312
120313  /* It may be that this trigger has already been coded (or is in the
120314  ** process of being coded). If this is the case, then an entry with
120315  ** a matching TriggerPrg.pTrigger field will be present somewhere
120316  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
120317  for(pPrg=pRoot->pTriggerPrg;
120318      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
120319      pPrg=pPrg->pNext
120320  );
120321
120322  /* If an existing TriggerPrg could not be located, create a new one. */
120323  if( !pPrg ){
120324    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
120325  }
120326
120327  return pPrg;
120328}
120329
120330/*
120331** Generate code for the trigger program associated with trigger p on
120332** table pTab. The reg, orconf and ignoreJump parameters passed to this
120333** function are the same as those described in the header function for
120334** sqlite3CodeRowTrigger()
120335*/
120336SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
120337  Parse *pParse,       /* Parse context */
120338  Trigger *p,          /* Trigger to code */
120339  Table *pTab,         /* The table to code triggers from */
120340  int reg,             /* Reg array containing OLD.* and NEW.* values */
120341  int orconf,          /* ON CONFLICT policy */
120342  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
120343){
120344  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
120345  TriggerPrg *pPrg;
120346  pPrg = getRowTrigger(pParse, p, pTab, orconf);
120347  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
120348
120349  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
120350  ** is a pointer to the sub-vdbe containing the trigger program.  */
120351  if( pPrg ){
120352    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
120353
120354    sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
120355                      (const char *)pPrg->pProgram, P4_SUBPROGRAM);
120356    VdbeComment(
120357        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
120358
120359    /* Set the P5 operand of the OP_Program instruction to non-zero if
120360    ** recursive invocation of this trigger program is disallowed. Recursive
120361    ** invocation is disallowed if (a) the sub-program is really a trigger,
120362    ** not a foreign key action, and (b) the flag to enable recursive triggers
120363    ** is clear.  */
120364    sqlite3VdbeChangeP5(v, (u8)bRecursive);
120365  }
120366}
120367
120368/*
120369** This is called to code the required FOR EACH ROW triggers for an operation
120370** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
120371** is given by the op parameter. The tr_tm parameter determines whether the
120372** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
120373** parameter pChanges is passed the list of columns being modified.
120374**
120375** If there are no triggers that fire at the specified time for the specified
120376** operation on pTab, this function is a no-op.
120377**
120378** The reg argument is the address of the first in an array of registers
120379** that contain the values substituted for the new.* and old.* references
120380** in the trigger program. If N is the number of columns in table pTab
120381** (a copy of pTab->nCol), then registers are populated as follows:
120382**
120383**   Register       Contains
120384**   ------------------------------------------------------
120385**   reg+0          OLD.rowid
120386**   reg+1          OLD.* value of left-most column of pTab
120387**   ...            ...
120388**   reg+N          OLD.* value of right-most column of pTab
120389**   reg+N+1        NEW.rowid
120390**   reg+N+2        OLD.* value of left-most column of pTab
120391**   ...            ...
120392**   reg+N+N+1      NEW.* value of right-most column of pTab
120393**
120394** For ON DELETE triggers, the registers containing the NEW.* values will
120395** never be accessed by the trigger program, so they are not allocated or
120396** populated by the caller (there is no data to populate them with anyway).
120397** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
120398** are never accessed, and so are not allocated by the caller. So, for an
120399** ON INSERT trigger, the value passed to this function as parameter reg
120400** is not a readable register, although registers (reg+N) through
120401** (reg+N+N+1) are.
120402**
120403** Parameter orconf is the default conflict resolution algorithm for the
120404** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
120405** is the instruction that control should jump to if a trigger program
120406** raises an IGNORE exception.
120407*/
120408SQLITE_PRIVATE void sqlite3CodeRowTrigger(
120409  Parse *pParse,       /* Parse context */
120410  Trigger *pTrigger,   /* List of triggers on table pTab */
120411  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
120412  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
120413  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
120414  Table *pTab,         /* The table to code triggers from */
120415  int reg,             /* The first in an array of registers (see above) */
120416  int orconf,          /* ON CONFLICT policy */
120417  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
120418){
120419  Trigger *p;          /* Used to iterate through pTrigger list */
120420
120421  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
120422  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
120423  assert( (op==TK_UPDATE)==(pChanges!=0) );
120424
120425  for(p=pTrigger; p; p=p->pNext){
120426
120427    /* Sanity checking:  The schema for the trigger and for the table are
120428    ** always defined.  The trigger must be in the same schema as the table
120429    ** or else it must be a TEMP trigger. */
120430    assert( p->pSchema!=0 );
120431    assert( p->pTabSchema!=0 );
120432    assert( p->pSchema==p->pTabSchema
120433         || p->pSchema==pParse->db->aDb[1].pSchema );
120434
120435    /* Determine whether we should code this trigger */
120436    if( p->op==op
120437     && p->tr_tm==tr_tm
120438     && checkColumnOverlap(p->pColumns, pChanges)
120439    ){
120440      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
120441    }
120442  }
120443}
120444
120445/*
120446** Triggers may access values stored in the old.* or new.* pseudo-table.
120447** This function returns a 32-bit bitmask indicating which columns of the
120448** old.* or new.* tables actually are used by triggers. This information
120449** may be used by the caller, for example, to avoid having to load the entire
120450** old.* record into memory when executing an UPDATE or DELETE command.
120451**
120452** Bit 0 of the returned mask is set if the left-most column of the
120453** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
120454** the second leftmost column value is required, and so on. If there
120455** are more than 32 columns in the table, and at least one of the columns
120456** with an index greater than 32 may be accessed, 0xffffffff is returned.
120457**
120458** It is not possible to determine if the old.rowid or new.rowid column is
120459** accessed by triggers. The caller must always assume that it is.
120460**
120461** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
120462** applies to the old.* table. If 1, the new.* table.
120463**
120464** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
120465** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
120466** included in the returned mask if the TRIGGER_BEFORE bit is set in the
120467** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
120468** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
120469*/
120470SQLITE_PRIVATE u32 sqlite3TriggerColmask(
120471  Parse *pParse,       /* Parse context */
120472  Trigger *pTrigger,   /* List of triggers on table pTab */
120473  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
120474  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
120475  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120476  Table *pTab,         /* The table to code triggers from */
120477  int orconf           /* Default ON CONFLICT policy for trigger steps */
120478){
120479  const int op = pChanges ? TK_UPDATE : TK_DELETE;
120480  u32 mask = 0;
120481  Trigger *p;
120482
120483  assert( isNew==1 || isNew==0 );
120484  for(p=pTrigger; p; p=p->pNext){
120485    if( p->op==op && (tr_tm&p->tr_tm)
120486     && checkColumnOverlap(p->pColumns,pChanges)
120487    ){
120488      TriggerPrg *pPrg;
120489      pPrg = getRowTrigger(pParse, p, pTab, orconf);
120490      if( pPrg ){
120491        mask |= pPrg->aColmask[isNew];
120492      }
120493    }
120494  }
120495
120496  return mask;
120497}
120498
120499#endif /* !defined(SQLITE_OMIT_TRIGGER) */
120500
120501/************** End of trigger.c *********************************************/
120502/************** Begin file update.c ******************************************/
120503/*
120504** 2001 September 15
120505**
120506** The author disclaims copyright to this source code.  In place of
120507** a legal notice, here is a blessing:
120508**
120509**    May you do good and not evil.
120510**    May you find forgiveness for yourself and forgive others.
120511**    May you share freely, never taking more than you give.
120512**
120513*************************************************************************
120514** This file contains C code routines that are called by the parser
120515** to handle UPDATE statements.
120516*/
120517/* #include "sqliteInt.h" */
120518
120519#ifndef SQLITE_OMIT_VIRTUALTABLE
120520/* Forward declaration */
120521static void updateVirtualTable(
120522  Parse *pParse,       /* The parsing context */
120523  SrcList *pSrc,       /* The virtual table to be modified */
120524  Table *pTab,         /* The virtual table */
120525  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
120526  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
120527  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
120528  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
120529  int onError          /* ON CONFLICT strategy */
120530);
120531#endif /* SQLITE_OMIT_VIRTUALTABLE */
120532
120533/*
120534** The most recently coded instruction was an OP_Column to retrieve the
120535** i-th column of table pTab. This routine sets the P4 parameter of the
120536** OP_Column to the default value, if any.
120537**
120538** The default value of a column is specified by a DEFAULT clause in the
120539** column definition. This was either supplied by the user when the table
120540** was created, or added later to the table definition by an ALTER TABLE
120541** command. If the latter, then the row-records in the table btree on disk
120542** may not contain a value for the column and the default value, taken
120543** from the P4 parameter of the OP_Column instruction, is returned instead.
120544** If the former, then all row-records are guaranteed to include a value
120545** for the column and the P4 value is not required.
120546**
120547** Column definitions created by an ALTER TABLE command may only have
120548** literal default values specified: a number, null or a string. (If a more
120549** complicated default expression value was provided, it is evaluated
120550** when the ALTER TABLE is executed and one of the literal values written
120551** into the sqlite_master table.)
120552**
120553** Therefore, the P4 parameter is only required if the default value for
120554** the column is a literal number, string or null. The sqlite3ValueFromExpr()
120555** function is capable of transforming these types of expressions into
120556** sqlite3_value objects.
120557**
120558** If parameter iReg is not negative, code an OP_RealAffinity instruction
120559** on register iReg. This is used when an equivalent integer value is
120560** stored in place of an 8-byte floating point value in order to save
120561** space.
120562*/
120563SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
120564  assert( pTab!=0 );
120565  if( !pTab->pSelect ){
120566    sqlite3_value *pValue = 0;
120567    u8 enc = ENC(sqlite3VdbeDb(v));
120568    Column *pCol = &pTab->aCol[i];
120569    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
120570    assert( i<pTab->nCol );
120571    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
120572                         pCol->affinity, &pValue);
120573    if( pValue ){
120574      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
120575    }
120576#ifndef SQLITE_OMIT_FLOATING_POINT
120577    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
120578      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
120579    }
120580#endif
120581  }
120582}
120583
120584/*
120585** Process an UPDATE statement.
120586**
120587**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
120588**          \_______/ \________/     \______/       \________________/
120589*            onError   pTabList      pChanges             pWhere
120590*/
120591SQLITE_PRIVATE void sqlite3Update(
120592  Parse *pParse,         /* The parser context */
120593  SrcList *pTabList,     /* The table in which we should change things */
120594  ExprList *pChanges,    /* Things to be changed */
120595  Expr *pWhere,          /* The WHERE clause.  May be null */
120596  int onError            /* How to handle constraint errors */
120597){
120598  int i, j;              /* Loop counters */
120599  Table *pTab;           /* The table to be updated */
120600  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
120601  WhereInfo *pWInfo;     /* Information about the WHERE clause */
120602  Vdbe *v;               /* The virtual database engine */
120603  Index *pIdx;           /* For looping over indices */
120604  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
120605  int nIdx;              /* Number of indices that need updating */
120606  int iBaseCur;          /* Base cursor number */
120607  int iDataCur;          /* Cursor for the canonical data btree */
120608  int iIdxCur;           /* Cursor for the first index */
120609  sqlite3 *db;           /* The database structure */
120610  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
120611  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
120612                         ** an expression for the i-th column of the table.
120613                         ** aXRef[i]==-1 if the i-th column is not changed. */
120614  u8 *aToOpen;           /* 1 for tables and indices to be opened */
120615  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
120616  u8 chngRowid;          /* Rowid changed in a normal table */
120617  u8 chngKey;            /* Either chngPk or chngRowid */
120618  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
120619  AuthContext sContext;  /* The authorization context */
120620  NameContext sNC;       /* The name-context to resolve expressions in */
120621  int iDb;               /* Database containing the table being updated */
120622  int okOnePass;         /* True for one-pass algorithm without the FIFO */
120623  int hasFK;             /* True if foreign key processing is required */
120624  int labelBreak;        /* Jump here to break out of UPDATE loop */
120625  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
120626
120627#ifndef SQLITE_OMIT_TRIGGER
120628  int isView;            /* True when updating a view (INSTEAD OF trigger) */
120629  Trigger *pTrigger;     /* List of triggers on pTab, if required */
120630  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120631#endif
120632  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
120633  int iEph = 0;          /* Ephemeral table holding all primary key values */
120634  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
120635  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
120636
120637  /* Register Allocations */
120638  int regRowCount = 0;   /* A count of rows changed */
120639  int regOldRowid = 0;   /* The old rowid */
120640  int regNewRowid = 0;   /* The new rowid */
120641  int regNew = 0;        /* Content of the NEW.* table in triggers */
120642  int regOld = 0;        /* Content of OLD.* table in triggers */
120643  int regRowSet = 0;     /* Rowset of rows to be updated */
120644  int regKey = 0;        /* composite PRIMARY KEY value */
120645
120646  memset(&sContext, 0, sizeof(sContext));
120647  db = pParse->db;
120648  if( pParse->nErr || db->mallocFailed ){
120649    goto update_cleanup;
120650  }
120651  assert( pTabList->nSrc==1 );
120652
120653  /* Locate the table which we want to update.
120654  */
120655  pTab = sqlite3SrcListLookup(pParse, pTabList);
120656  if( pTab==0 ) goto update_cleanup;
120657  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
120658
120659  /* Figure out if we have any triggers and if the table being
120660  ** updated is a view.
120661  */
120662#ifndef SQLITE_OMIT_TRIGGER
120663  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
120664  isView = pTab->pSelect!=0;
120665  assert( pTrigger || tmask==0 );
120666#else
120667# define pTrigger 0
120668# define isView 0
120669# define tmask 0
120670#endif
120671#ifdef SQLITE_OMIT_VIEW
120672# undef isView
120673# define isView 0
120674#endif
120675
120676  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
120677    goto update_cleanup;
120678  }
120679  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
120680    goto update_cleanup;
120681  }
120682
120683  /* Allocate a cursors for the main database table and for all indices.
120684  ** The index cursors might not be used, but if they are used they
120685  ** need to occur right after the database cursor.  So go ahead and
120686  ** allocate enough space, just in case.
120687  */
120688  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
120689  iIdxCur = iDataCur+1;
120690  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
120691  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
120692    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
120693      iDataCur = pParse->nTab;
120694      pTabList->a[0].iCursor = iDataCur;
120695    }
120696    pParse->nTab++;
120697  }
120698
120699  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
120700  ** Initialize aXRef[] and aToOpen[] to their default values.
120701  */
120702  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
120703  if( aXRef==0 ) goto update_cleanup;
120704  aRegIdx = aXRef+pTab->nCol;
120705  aToOpen = (u8*)(aRegIdx+nIdx);
120706  memset(aToOpen, 1, nIdx+1);
120707  aToOpen[nIdx+1] = 0;
120708  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
120709
120710  /* Initialize the name-context */
120711  memset(&sNC, 0, sizeof(sNC));
120712  sNC.pParse = pParse;
120713  sNC.pSrcList = pTabList;
120714
120715  /* Resolve the column names in all the expressions of the
120716  ** of the UPDATE statement.  Also find the column index
120717  ** for each column to be updated in the pChanges array.  For each
120718  ** column to be updated, make sure we have authorization to change
120719  ** that column.
120720  */
120721  chngRowid = chngPk = 0;
120722  for(i=0; i<pChanges->nExpr; i++){
120723    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
120724      goto update_cleanup;
120725    }
120726    for(j=0; j<pTab->nCol; j++){
120727      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
120728        if( j==pTab->iPKey ){
120729          chngRowid = 1;
120730          pRowidExpr = pChanges->a[i].pExpr;
120731        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
120732          chngPk = 1;
120733        }
120734        aXRef[j] = i;
120735        break;
120736      }
120737    }
120738    if( j>=pTab->nCol ){
120739      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
120740        j = -1;
120741        chngRowid = 1;
120742        pRowidExpr = pChanges->a[i].pExpr;
120743      }else{
120744        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
120745        pParse->checkSchema = 1;
120746        goto update_cleanup;
120747      }
120748    }
120749#ifndef SQLITE_OMIT_AUTHORIZATION
120750    {
120751      int rc;
120752      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
120753                            j<0 ? "ROWID" : pTab->aCol[j].zName,
120754                            db->aDb[iDb].zName);
120755      if( rc==SQLITE_DENY ){
120756        goto update_cleanup;
120757      }else if( rc==SQLITE_IGNORE ){
120758        aXRef[j] = -1;
120759      }
120760    }
120761#endif
120762  }
120763  assert( (chngRowid & chngPk)==0 );
120764  assert( chngRowid==0 || chngRowid==1 );
120765  assert( chngPk==0 || chngPk==1 );
120766  chngKey = chngRowid + chngPk;
120767
120768  /* The SET expressions are not actually used inside the WHERE loop.
120769  ** So reset the colUsed mask. Unless this is a virtual table. In that
120770  ** case, set all bits of the colUsed mask (to ensure that the virtual
120771  ** table implementation makes all columns available).
120772  */
120773  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
120774
120775  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
120776
120777  /* There is one entry in the aRegIdx[] array for each index on the table
120778  ** being updated.  Fill in aRegIdx[] with a register number that will hold
120779  ** the key for accessing each index.
120780  **
120781  ** FIXME:  Be smarter about omitting indexes that use expressions.
120782  */
120783  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
120784    int reg;
120785    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
120786      reg = ++pParse->nMem;
120787    }else{
120788      reg = 0;
120789      for(i=0; i<pIdx->nKeyCol; i++){
120790        i16 iIdxCol = pIdx->aiColumn[i];
120791        if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
120792          reg = ++pParse->nMem;
120793          break;
120794        }
120795      }
120796    }
120797    if( reg==0 ) aToOpen[j+1] = 0;
120798    aRegIdx[j] = reg;
120799  }
120800
120801  /* Begin generating code. */
120802  v = sqlite3GetVdbe(pParse);
120803  if( v==0 ) goto update_cleanup;
120804  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
120805  sqlite3BeginWriteOperation(pParse, 1, iDb);
120806
120807  /* Allocate required registers. */
120808  if( !IsVirtual(pTab) ){
120809    regRowSet = ++pParse->nMem;
120810    regOldRowid = regNewRowid = ++pParse->nMem;
120811    if( chngPk || pTrigger || hasFK ){
120812      regOld = pParse->nMem + 1;
120813      pParse->nMem += pTab->nCol;
120814    }
120815    if( chngKey || pTrigger || hasFK ){
120816      regNewRowid = ++pParse->nMem;
120817    }
120818    regNew = pParse->nMem + 1;
120819    pParse->nMem += pTab->nCol;
120820  }
120821
120822  /* Start the view context. */
120823  if( isView ){
120824    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
120825  }
120826
120827  /* If we are trying to update a view, realize that view into
120828  ** an ephemeral table.
120829  */
120830#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
120831  if( isView ){
120832    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
120833  }
120834#endif
120835
120836  /* Resolve the column names in all the expressions in the
120837  ** WHERE clause.
120838  */
120839  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
120840    goto update_cleanup;
120841  }
120842
120843#ifndef SQLITE_OMIT_VIRTUALTABLE
120844  /* Virtual tables must be handled separately */
120845  if( IsVirtual(pTab) ){
120846    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
120847                       pWhere, onError);
120848    goto update_cleanup;
120849  }
120850#endif
120851
120852  /* Begin the database scan
120853  */
120854  if( HasRowid(pTab) ){
120855    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
120856    pWInfo = sqlite3WhereBegin(
120857        pParse, pTabList, pWhere, 0, 0,
120858            WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur
120859    );
120860    if( pWInfo==0 ) goto update_cleanup;
120861    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120862
120863    /* Remember the rowid of every item to be updated.
120864    */
120865    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
120866    if( !okOnePass ){
120867      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
120868    }
120869
120870    /* End the database scan loop.
120871    */
120872    sqlite3WhereEnd(pWInfo);
120873  }else{
120874    int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
120875    i16 nPk;         /* Number of components of the PRIMARY KEY */
120876    int addrOpen;    /* Address of the OpenEphemeral instruction */
120877
120878    assert( pPk!=0 );
120879    nPk = pPk->nKeyCol;
120880    iPk = pParse->nMem+1;
120881    pParse->nMem += nPk;
120882    regKey = ++pParse->nMem;
120883    iEph = pParse->nTab++;
120884    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
120885    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
120886    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
120887    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
120888                               WHERE_ONEPASS_DESIRED, iIdxCur);
120889    if( pWInfo==0 ) goto update_cleanup;
120890    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120891    for(i=0; i<nPk; i++){
120892      assert( pPk->aiColumn[i]>=0 );
120893      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
120894                                      iPk+i);
120895    }
120896    if( okOnePass ){
120897      sqlite3VdbeChangeToNoop(v, addrOpen);
120898      nKey = nPk;
120899      regKey = iPk;
120900    }else{
120901      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
120902                        sqlite3IndexAffinityStr(db, pPk), nPk);
120903      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
120904    }
120905    sqlite3WhereEnd(pWInfo);
120906  }
120907
120908  /* Initialize the count of updated rows
120909  */
120910  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
120911    regRowCount = ++pParse->nMem;
120912    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
120913  }
120914
120915  labelBreak = sqlite3VdbeMakeLabel(v);
120916  if( !isView ){
120917    /*
120918    ** Open every index that needs updating.  Note that if any
120919    ** index could potentially invoke a REPLACE conflict resolution
120920    ** action, then we need to open all indices because we might need
120921    ** to be deleting some records.
120922    */
120923    if( onError==OE_Replace ){
120924      memset(aToOpen, 1, nIdx+1);
120925    }else{
120926      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120927        if( pIdx->onError==OE_Replace ){
120928          memset(aToOpen, 1, nIdx+1);
120929          break;
120930        }
120931      }
120932    }
120933    if( okOnePass ){
120934      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
120935      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
120936    }
120937    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
120938                               0, 0);
120939  }
120940
120941  /* Top of the update loop */
120942  if( okOnePass ){
120943    if( aToOpen[iDataCur-iBaseCur] && !isView ){
120944      assert( pPk );
120945      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
120946      VdbeCoverageNeverTaken(v);
120947    }
120948    labelContinue = labelBreak;
120949    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
120950    VdbeCoverageIf(v, pPk==0);
120951    VdbeCoverageIf(v, pPk!=0);
120952  }else if( pPk ){
120953    labelContinue = sqlite3VdbeMakeLabel(v);
120954    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
120955    addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
120956    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
120957    VdbeCoverage(v);
120958  }else{
120959    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
120960                             regOldRowid);
120961    VdbeCoverage(v);
120962    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
120963    VdbeCoverage(v);
120964  }
120965
120966  /* If the record number will change, set register regNewRowid to
120967  ** contain the new value. If the record number is not being modified,
120968  ** then regNewRowid is the same register as regOldRowid, which is
120969  ** already populated.  */
120970  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
120971  if( chngRowid ){
120972    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
120973    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
120974  }
120975
120976  /* Compute the old pre-UPDATE content of the row being changed, if that
120977  ** information is needed */
120978  if( chngPk || hasFK || pTrigger ){
120979    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
120980    oldmask |= sqlite3TriggerColmask(pParse,
120981        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
120982    );
120983    for(i=0; i<pTab->nCol; i++){
120984      if( oldmask==0xffffffff
120985       || (i<32 && (oldmask & MASKBIT32(i))!=0)
120986       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
120987      ){
120988        testcase(  oldmask!=0xffffffff && i==31 );
120989        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
120990      }else{
120991        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
120992      }
120993    }
120994    if( chngRowid==0 && pPk==0 ){
120995      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
120996    }
120997  }
120998
120999  /* Populate the array of registers beginning at regNew with the new
121000  ** row data. This array is used to check constants, create the new
121001  ** table and index records, and as the values for any new.* references
121002  ** made by triggers.
121003  **
121004  ** If there are one or more BEFORE triggers, then do not populate the
121005  ** registers associated with columns that are (a) not modified by
121006  ** this UPDATE statement and (b) not accessed by new.* references. The
121007  ** values for registers not modified by the UPDATE must be reloaded from
121008  ** the database after the BEFORE triggers are fired anyway (as the trigger
121009  ** may have modified them). So not loading those that are not going to
121010  ** be used eliminates some redundant opcodes.
121011  */
121012  newmask = sqlite3TriggerColmask(
121013      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
121014  );
121015  for(i=0; i<pTab->nCol; i++){
121016    if( i==pTab->iPKey ){
121017      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121018    }else{
121019      j = aXRef[i];
121020      if( j>=0 ){
121021        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
121022      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
121023        /* This branch loads the value of a column that will not be changed
121024        ** into a register. This is done if there are no BEFORE triggers, or
121025        ** if there are one or more BEFORE triggers that use this value via
121026        ** a new.* reference in a trigger program.
121027        */
121028        testcase( i==31 );
121029        testcase( i==32 );
121030        sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
121031      }else{
121032        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121033      }
121034    }
121035  }
121036
121037  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
121038  ** verified. One could argue that this is wrong.
121039  */
121040  if( tmask&TRIGGER_BEFORE ){
121041    sqlite3TableAffinity(v, pTab, regNew);
121042    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
121043        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
121044
121045    /* The row-trigger may have deleted the row being updated. In this
121046    ** case, jump to the next row. No updates or AFTER triggers are
121047    ** required. This behavior - what happens when the row being updated
121048    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
121049    ** documentation.
121050    */
121051    if( pPk ){
121052      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
121053      VdbeCoverage(v);
121054    }else{
121055      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121056      VdbeCoverage(v);
121057    }
121058
121059    /* If it did not delete it, the row-trigger may still have modified
121060    ** some of the columns of the row being updated. Load the values for
121061    ** all columns not modified by the update statement into their
121062    ** registers in case this has happened.
121063    */
121064    for(i=0; i<pTab->nCol; i++){
121065      if( aXRef[i]<0 && i!=pTab->iPKey ){
121066        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
121067      }
121068    }
121069  }
121070
121071  if( !isView ){
121072    int addr1 = 0;        /* Address of jump instruction */
121073    int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
121074
121075    /* Do constraint checks. */
121076    assert( regOldRowid>0 );
121077    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
121078        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
121079        aXRef);
121080
121081    /* Do FK constraint checks. */
121082    if( hasFK ){
121083      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
121084    }
121085
121086    /* Delete the index entries associated with the current record.  */
121087    if( bReplace || chngKey ){
121088      if( pPk ){
121089        addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
121090      }else{
121091        addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
121092      }
121093      VdbeCoverageNeverTaken(v);
121094    }
121095    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
121096
121097    /* If changing the rowid value, or if there are foreign key constraints
121098    ** to process, delete the old record. Otherwise, add a noop OP_Delete
121099    ** to invoke the pre-update hook.
121100    **
121101    ** That (regNew==regnewRowid+1) is true is also important for the
121102    ** pre-update hook. If the caller invokes preupdate_new(), the returned
121103    ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
121104    ** is the column index supplied by the user.
121105    */
121106    assert( regNew==regNewRowid+1 );
121107#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
121108    sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
121109        OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
121110        regNewRowid
121111    );
121112    if( !pParse->nested ){
121113      sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
121114    }
121115#else
121116    if( hasFK || chngKey || pPk!=0 ){
121117      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
121118    }
121119#endif
121120    if( bReplace || chngKey ){
121121      sqlite3VdbeJumpHere(v, addr1);
121122    }
121123
121124    if( hasFK ){
121125      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
121126    }
121127
121128    /* Insert the new index entries and the new record. */
121129    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
121130                             regNewRowid, aRegIdx, 1, 0, 0);
121131
121132    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
121133    ** handle rows (possibly in other tables) that refer via a foreign key
121134    ** to the row just updated. */
121135    if( hasFK ){
121136      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
121137    }
121138  }
121139
121140  /* Increment the row counter
121141  */
121142  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
121143    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
121144  }
121145
121146  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
121147      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
121148
121149  /* Repeat the above with the next record to be updated, until
121150  ** all record selected by the WHERE clause have been updated.
121151  */
121152  if( okOnePass ){
121153    /* Nothing to do at end-of-loop for a single-pass */
121154  }else if( pPk ){
121155    sqlite3VdbeResolveLabel(v, labelContinue);
121156    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
121157  }else{
121158    sqlite3VdbeGoto(v, labelContinue);
121159  }
121160  sqlite3VdbeResolveLabel(v, labelBreak);
121161
121162  /* Close all tables */
121163  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
121164    assert( aRegIdx );
121165    if( aToOpen[i+1] ){
121166      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
121167    }
121168  }
121169  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
121170
121171  /* Update the sqlite_sequence table by storing the content of the
121172  ** maximum rowid counter values recorded while inserting into
121173  ** autoincrement tables.
121174  */
121175  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
121176    sqlite3AutoincrementEnd(pParse);
121177  }
121178
121179  /*
121180  ** Return the number of rows that were changed. If this routine is
121181  ** generating code because of a call to sqlite3NestedParse(), do not
121182  ** invoke the callback function.
121183  */
121184  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
121185    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
121186    sqlite3VdbeSetNumCols(v, 1);
121187    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
121188  }
121189
121190update_cleanup:
121191  sqlite3AuthContextPop(&sContext);
121192  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
121193  sqlite3SrcListDelete(db, pTabList);
121194  sqlite3ExprListDelete(db, pChanges);
121195  sqlite3ExprDelete(db, pWhere);
121196  return;
121197}
121198/* Make sure "isView" and other macros defined above are undefined. Otherwise
121199** they may interfere with compilation of other functions in this file
121200** (or in another file, if this file becomes part of the amalgamation).  */
121201#ifdef isView
121202 #undef isView
121203#endif
121204#ifdef pTrigger
121205 #undef pTrigger
121206#endif
121207
121208#ifndef SQLITE_OMIT_VIRTUALTABLE
121209/*
121210** Generate code for an UPDATE of a virtual table.
121211**
121212** There are two possible strategies - the default and the special
121213** "onepass" strategy. Onepass is only used if the virtual table
121214** implementation indicates that pWhere may match at most one row.
121215**
121216** The default strategy is to create an ephemeral table that contains
121217** for each row to be changed:
121218**
121219**   (A)  The original rowid of that row.
121220**   (B)  The revised rowid for the row.
121221**   (C)  The content of every column in the row.
121222**
121223** Then loop through the contents of this ephemeral table executing a
121224** VUpdate for each row. When finished, drop the ephemeral table.
121225**
121226** The "onepass" strategy does not use an ephemeral table. Instead, it
121227** stores the same values (A, B and C above) in a register array and
121228** makes a single invocation of VUpdate.
121229*/
121230static void updateVirtualTable(
121231  Parse *pParse,       /* The parsing context */
121232  SrcList *pSrc,       /* The virtual table to be modified */
121233  Table *pTab,         /* The virtual table */
121234  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
121235  Expr *pRowid,        /* Expression used to recompute the rowid */
121236  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
121237  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
121238  int onError          /* ON CONFLICT strategy */
121239){
121240  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
121241  int ephemTab;             /* Table holding the result of the SELECT */
121242  int i;                    /* Loop counter */
121243  sqlite3 *db = pParse->db; /* Database connection */
121244  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
121245  WhereInfo *pWInfo;
121246  int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
121247  int regArg;                     /* First register in VUpdate arg array */
121248  int regRec;                     /* Register in which to assemble record */
121249  int regRowid;                   /* Register for ephem table rowid */
121250  int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
121251  int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
121252  int bOnePass;                   /* True to use onepass strategy */
121253  int addr;                       /* Address of OP_OpenEphemeral */
121254
121255  /* Allocate nArg registers to martial the arguments to VUpdate. Then
121256  ** create and open the ephemeral table in which the records created from
121257  ** these arguments will be temporarily stored. */
121258  assert( v );
121259  ephemTab = pParse->nTab++;
121260  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
121261  regArg = pParse->nMem + 1;
121262  pParse->nMem += nArg;
121263  regRec = ++pParse->nMem;
121264  regRowid = ++pParse->nMem;
121265
121266  /* Start scanning the virtual table */
121267  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
121268  if( pWInfo==0 ) return;
121269
121270  /* Populate the argument registers. */
121271  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
121272  if( pRowid ){
121273    sqlite3ExprCode(pParse, pRowid, regArg+1);
121274  }else{
121275    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
121276  }
121277  for(i=0; i<pTab->nCol; i++){
121278    if( aXRef[i]>=0 ){
121279      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
121280    }else{
121281      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
121282    }
121283  }
121284
121285  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
121286
121287  if( bOnePass ){
121288    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
121289    ** above. Also, if this is a top-level parse (not a trigger), clear the
121290    ** multi-write flag so that the VM does not open a statement journal */
121291    sqlite3VdbeChangeToNoop(v, addr);
121292    if( sqlite3IsToplevel(pParse) ){
121293      pParse->isMultiWrite = 0;
121294    }
121295  }else{
121296    /* Create a record from the argument register contents and insert it into
121297    ** the ephemeral table. */
121298    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
121299    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
121300    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
121301  }
121302
121303
121304  if( bOnePass==0 ){
121305    /* End the virtual table scan */
121306    sqlite3WhereEnd(pWInfo);
121307
121308    /* Begin scannning through the ephemeral table. */
121309    addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
121310
121311    /* Extract arguments from the current row of the ephemeral table and
121312    ** invoke the VUpdate method.  */
121313    for(i=0; i<nArg; i++){
121314      sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
121315    }
121316  }
121317  sqlite3VtabMakeWritable(pParse, pTab);
121318  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
121319  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
121320  sqlite3MayAbort(pParse);
121321
121322  /* End of the ephemeral table scan. Or, if using the onepass strategy,
121323  ** jump to here if the scan visited zero rows. */
121324  if( bOnePass==0 ){
121325    sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
121326    sqlite3VdbeJumpHere(v, addr);
121327    sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
121328  }else{
121329    sqlite3WhereEnd(pWInfo);
121330  }
121331}
121332#endif /* SQLITE_OMIT_VIRTUALTABLE */
121333
121334/************** End of update.c **********************************************/
121335/************** Begin file vacuum.c ******************************************/
121336/*
121337** 2003 April 6
121338**
121339** The author disclaims copyright to this source code.  In place of
121340** a legal notice, here is a blessing:
121341**
121342**    May you do good and not evil.
121343**    May you find forgiveness for yourself and forgive others.
121344**    May you share freely, never taking more than you give.
121345**
121346*************************************************************************
121347** This file contains code used to implement the VACUUM command.
121348**
121349** Most of the code in this file may be omitted by defining the
121350** SQLITE_OMIT_VACUUM macro.
121351*/
121352/* #include "sqliteInt.h" */
121353/* #include "vdbeInt.h" */
121354
121355#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
121356/*
121357** Finalize a prepared statement.  If there was an error, store the
121358** text of the error message in *pzErrMsg.  Return the result code.
121359*/
121360static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
121361  int rc;
121362  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
121363  if( rc ){
121364    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
121365  }
121366  return rc;
121367}
121368
121369/*
121370** Execute zSql on database db. Return an error code.
121371*/
121372static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
121373  sqlite3_stmt *pStmt;
121374  VVA_ONLY( int rc; )
121375  if( !zSql ){
121376    return SQLITE_NOMEM_BKPT;
121377  }
121378  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
121379    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
121380    return sqlite3_errcode(db);
121381  }
121382  VVA_ONLY( rc = ) sqlite3_step(pStmt);
121383  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
121384  return vacuumFinalize(db, pStmt, pzErrMsg);
121385}
121386
121387/*
121388** Execute zSql on database db. The statement returns exactly
121389** one column. Execute this as SQL on the same database.
121390*/
121391static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
121392  sqlite3_stmt *pStmt;
121393  int rc;
121394
121395  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
121396  if( rc!=SQLITE_OK ) return rc;
121397
121398  while( SQLITE_ROW==sqlite3_step(pStmt) ){
121399    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
121400    if( rc!=SQLITE_OK ){
121401      vacuumFinalize(db, pStmt, pzErrMsg);
121402      return rc;
121403    }
121404  }
121405
121406  return vacuumFinalize(db, pStmt, pzErrMsg);
121407}
121408
121409/*
121410** The VACUUM command is used to clean up the database,
121411** collapse free space, etc.  It is modelled after the VACUUM command
121412** in PostgreSQL.  The VACUUM command works as follows:
121413**
121414**   (1)  Create a new transient database file
121415**   (2)  Copy all content from the database being vacuumed into
121416**        the new transient database file
121417**   (3)  Copy content from the transient database back into the
121418**        original database.
121419**
121420** The transient database requires temporary disk space approximately
121421** equal to the size of the original database.  The copy operation of
121422** step (3) requires additional temporary disk space approximately equal
121423** to the size of the original database for the rollback journal.
121424** Hence, temporary disk space that is approximately 2x the size of the
121425** original database is required.  Every page of the database is written
121426** approximately 3 times:  Once for step (2) and twice for step (3).
121427** Two writes per page are required in step (3) because the original
121428** database content must be written into the rollback journal prior to
121429** overwriting the database with the vacuumed content.
121430**
121431** Only 1x temporary space and only 1x writes would be required if
121432** the copy of step (3) were replaced by deleting the original database
121433** and renaming the transient database as the original.  But that will
121434** not work if other processes are attached to the original database.
121435** And a power loss in between deleting the original and renaming the
121436** transient would cause the database file to appear to be deleted
121437** following reboot.
121438*/
121439SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
121440  Vdbe *v = sqlite3GetVdbe(pParse);
121441  if( v ){
121442    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
121443    sqlite3VdbeUsesBtree(v, 0);
121444  }
121445  return;
121446}
121447
121448/*
121449** This routine implements the OP_Vacuum opcode of the VDBE.
121450*/
121451SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
121452  int rc = SQLITE_OK;     /* Return code from service routines */
121453  Btree *pMain;           /* The database being vacuumed */
121454  Btree *pTemp;           /* The temporary database we vacuum into */
121455  char *zSql = 0;         /* SQL statements */
121456  int saved_flags;        /* Saved value of the db->flags */
121457  int saved_nChange;      /* Saved value of db->nChange */
121458  int saved_nTotalChange; /* Saved value of db->nTotalChange */
121459  u8 saved_mTrace;        /* Saved trace settings */
121460  Db *pDb = 0;            /* Database to detach at end of vacuum */
121461  int isMemDb;            /* True if vacuuming a :memory: database */
121462  int nRes;               /* Bytes of reserved space at the end of each page */
121463  int nDb;                /* Number of attached databases */
121464
121465  if( !db->autoCommit ){
121466    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
121467    return SQLITE_ERROR;
121468  }
121469  if( db->nVdbeActive>1 ){
121470    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
121471    return SQLITE_ERROR;
121472  }
121473
121474  /* Save the current value of the database flags so that it can be
121475  ** restored before returning. Then set the writable-schema flag, and
121476  ** disable CHECK and foreign key constraints.  */
121477  saved_flags = db->flags;
121478  saved_nChange = db->nChange;
121479  saved_nTotalChange = db->nTotalChange;
121480  saved_mTrace = db->mTrace;
121481  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
121482  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
121483  db->mTrace = 0;
121484
121485  pMain = db->aDb[0].pBt;
121486  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
121487
121488  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
121489  ** can be set to 'off' for this file, as it is not recovered if a crash
121490  ** occurs anyway. The integrity of the database is maintained by a
121491  ** (possibly synchronous) transaction opened on the main database before
121492  ** sqlite3BtreeCopyFile() is called.
121493  **
121494  ** An optimisation would be to use a non-journaled pager.
121495  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
121496  ** that actually made the VACUUM run slower.  Very little journalling
121497  ** actually occurs when doing a vacuum since the vacuum_db is initially
121498  ** empty.  Only the journal header is written.  Apparently it takes more
121499  ** time to parse and run the PRAGMA to turn journalling off than it does
121500  ** to write the journal header file.
121501  */
121502  nDb = db->nDb;
121503  if( sqlite3TempInMemory(db) ){
121504    zSql = "ATTACH ':memory:' AS vacuum_db;";
121505  }else{
121506    zSql = "ATTACH '' AS vacuum_db;";
121507  }
121508  rc = execSql(db, pzErrMsg, zSql);
121509  if( db->nDb>nDb ){
121510    pDb = &db->aDb[db->nDb-1];
121511    assert( strcmp(pDb->zName,"vacuum_db")==0 );
121512  }
121513  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121514  pTemp = db->aDb[db->nDb-1].pBt;
121515
121516  /* The call to execSql() to attach the temp database has left the file
121517  ** locked (as there was more than one active statement when the transaction
121518  ** to read the schema was concluded. Unlock it here so that this doesn't
121519  ** cause problems for the call to BtreeSetPageSize() below.  */
121520  sqlite3BtreeCommit(pTemp);
121521
121522  nRes = sqlite3BtreeGetOptimalReserve(pMain);
121523
121524  /* A VACUUM cannot change the pagesize of an encrypted database. */
121525#ifdef SQLITE_HAS_CODEC
121526  if( db->nextPagesize ){
121527    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
121528    int nKey;
121529    char *zKey;
121530    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
121531    if( nKey ) db->nextPagesize = 0;
121532  }
121533#endif
121534
121535  sqlite3BtreeSetCacheSize(pTemp, db->aDb[0].pSchema->cache_size);
121536  sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
121537  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
121538  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121539
121540  /* Begin a transaction and take an exclusive lock on the main database
121541  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
121542  ** to ensure that we do not try to change the page-size on a WAL database.
121543  */
121544  rc = execSql(db, pzErrMsg, "BEGIN;");
121545  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121546  rc = sqlite3BtreeBeginTrans(pMain, 2);
121547  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121548
121549  /* Do not attempt to change the page size for a WAL database */
121550  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
121551                                               ==PAGER_JOURNALMODE_WAL ){
121552    db->nextPagesize = 0;
121553  }
121554
121555  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
121556   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
121557   || NEVER(db->mallocFailed)
121558  ){
121559    rc = SQLITE_NOMEM_BKPT;
121560    goto end_of_vacuum;
121561  }
121562
121563#ifndef SQLITE_OMIT_AUTOVACUUM
121564  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
121565                                           sqlite3BtreeGetAutoVacuum(pMain));
121566#endif
121567
121568  /* Query the schema of the main database. Create a mirror schema
121569  ** in the temporary database.
121570  */
121571  rc = execExecSql(db, pzErrMsg,
121572      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
121573      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
121574      "   AND coalesce(rootpage,1)>0"
121575  );
121576  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121577  rc = execExecSql(db, pzErrMsg,
121578      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
121579      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
121580  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121581  rc = execExecSql(db, pzErrMsg,
121582      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
121583      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
121584  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121585
121586  /* Loop through the tables in the main database. For each, do
121587  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
121588  ** the contents to the temporary database.
121589  */
121590  assert( (db->flags & SQLITE_Vacuum)==0 );
121591  db->flags |= SQLITE_Vacuum;
121592  rc = execExecSql(db, pzErrMsg,
121593      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
121594      "|| ' SELECT * FROM main.' || quote(name) || ';'"
121595      "FROM main.sqlite_master "
121596      "WHERE type = 'table' AND name!='sqlite_sequence' "
121597      "  AND coalesce(rootpage,1)>0"
121598  );
121599  assert( (db->flags & SQLITE_Vacuum)!=0 );
121600  db->flags &= ~SQLITE_Vacuum;
121601  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121602
121603  /* Copy over the sequence table
121604  */
121605  rc = execExecSql(db, pzErrMsg,
121606      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
121607      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
121608  );
121609  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121610  rc = execExecSql(db, pzErrMsg,
121611      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
121612      "|| ' SELECT * FROM main.' || quote(name) || ';' "
121613      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
121614  );
121615  if( rc!=SQLITE_OK ) goto end_of_vacuum;
121616
121617
121618  /* Copy the triggers, views, and virtual tables from the main database
121619  ** over to the temporary database.  None of these objects has any
121620  ** associated storage, so all we have to do is copy their entries
121621  ** from the SQLITE_MASTER table.
121622  */
121623  rc = execSql(db, pzErrMsg,
121624      "INSERT INTO vacuum_db.sqlite_master "
121625      "  SELECT type, name, tbl_name, rootpage, sql"
121626      "    FROM main.sqlite_master"
121627      "   WHERE type='view' OR type='trigger'"
121628      "      OR (type='table' AND rootpage=0)"
121629  );
121630  if( rc ) goto end_of_vacuum;
121631
121632  /* At this point, there is a write transaction open on both the
121633  ** vacuum database and the main database. Assuming no error occurs,
121634  ** both transactions are closed by this block - the main database
121635  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
121636  ** call to sqlite3BtreeCommit().
121637  */
121638  {
121639    u32 meta;
121640    int i;
121641
121642    /* This array determines which meta meta values are preserved in the
121643    ** vacuum.  Even entries are the meta value number and odd entries
121644    ** are an increment to apply to the meta value after the vacuum.
121645    ** The increment is used to increase the schema cookie so that other
121646    ** connections to the same database will know to reread the schema.
121647    */
121648    static const unsigned char aCopy[] = {
121649       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
121650       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
121651       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
121652       BTREE_USER_VERSION,       0,  /* Preserve the user version */
121653       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
121654    };
121655
121656    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
121657    assert( 1==sqlite3BtreeIsInTrans(pMain) );
121658
121659    /* Copy Btree meta values */
121660    for(i=0; i<ArraySize(aCopy); i+=2){
121661      /* GetMeta() and UpdateMeta() cannot fail in this context because
121662      ** we already have page 1 loaded into cache and marked dirty. */
121663      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
121664      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
121665      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
121666    }
121667
121668    rc = sqlite3BtreeCopyFile(pMain, pTemp);
121669    if( rc!=SQLITE_OK ) goto end_of_vacuum;
121670    rc = sqlite3BtreeCommit(pTemp);
121671    if( rc!=SQLITE_OK ) goto end_of_vacuum;
121672#ifndef SQLITE_OMIT_AUTOVACUUM
121673    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
121674#endif
121675  }
121676
121677  assert( rc==SQLITE_OK );
121678  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
121679
121680end_of_vacuum:
121681  /* Restore the original value of db->flags */
121682  db->flags = saved_flags;
121683  db->nChange = saved_nChange;
121684  db->nTotalChange = saved_nTotalChange;
121685  db->mTrace = saved_mTrace;
121686  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
121687
121688  /* Currently there is an SQL level transaction open on the vacuum
121689  ** database. No locks are held on any other files (since the main file
121690  ** was committed at the btree level). So it safe to end the transaction
121691  ** by manually setting the autoCommit flag to true and detaching the
121692  ** vacuum database. The vacuum_db journal file is deleted when the pager
121693  ** is closed by the DETACH.
121694  */
121695  db->autoCommit = 1;
121696
121697  if( pDb ){
121698    sqlite3BtreeClose(pDb->pBt);
121699    pDb->pBt = 0;
121700    pDb->pSchema = 0;
121701  }
121702
121703  /* This both clears the schemas and reduces the size of the db->aDb[]
121704  ** array. */
121705  sqlite3ResetAllSchemasOfConnection(db);
121706
121707  return rc;
121708}
121709
121710#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
121711
121712/************** End of vacuum.c **********************************************/
121713/************** Begin file vtab.c ********************************************/
121714/*
121715** 2006 June 10
121716**
121717** The author disclaims copyright to this source code.  In place of
121718** a legal notice, here is a blessing:
121719**
121720**    May you do good and not evil.
121721**    May you find forgiveness for yourself and forgive others.
121722**    May you share freely, never taking more than you give.
121723**
121724*************************************************************************
121725** This file contains code used to help implement virtual tables.
121726*/
121727#ifndef SQLITE_OMIT_VIRTUALTABLE
121728/* #include "sqliteInt.h" */
121729
121730/*
121731** Before a virtual table xCreate() or xConnect() method is invoked, the
121732** sqlite3.pVtabCtx member variable is set to point to an instance of
121733** this struct allocated on the stack. It is used by the implementation of
121734** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
121735** are invoked only from within xCreate and xConnect methods.
121736*/
121737struct VtabCtx {
121738  VTable *pVTable;    /* The virtual table being constructed */
121739  Table *pTab;        /* The Table object to which the virtual table belongs */
121740  VtabCtx *pPrior;    /* Parent context (if any) */
121741  int bDeclared;      /* True after sqlite3_declare_vtab() is called */
121742};
121743
121744/*
121745** The actual function that does the work of creating a new module.
121746** This function implements the sqlite3_create_module() and
121747** sqlite3_create_module_v2() interfaces.
121748*/
121749static int createModule(
121750  sqlite3 *db,                    /* Database in which module is registered */
121751  const char *zName,              /* Name assigned to this module */
121752  const sqlite3_module *pModule,  /* The definition of the module */
121753  void *pAux,                     /* Context pointer for xCreate/xConnect */
121754  void (*xDestroy)(void *)        /* Module destructor function */
121755){
121756  int rc = SQLITE_OK;
121757  int nName;
121758
121759  sqlite3_mutex_enter(db->mutex);
121760  nName = sqlite3Strlen30(zName);
121761  if( sqlite3HashFind(&db->aModule, zName) ){
121762    rc = SQLITE_MISUSE_BKPT;
121763  }else{
121764    Module *pMod;
121765    pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
121766    if( pMod ){
121767      Module *pDel;
121768      char *zCopy = (char *)(&pMod[1]);
121769      memcpy(zCopy, zName, nName+1);
121770      pMod->zName = zCopy;
121771      pMod->pModule = pModule;
121772      pMod->pAux = pAux;
121773      pMod->xDestroy = xDestroy;
121774      pMod->pEpoTab = 0;
121775      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
121776      assert( pDel==0 || pDel==pMod );
121777      if( pDel ){
121778        sqlite3OomFault(db);
121779        sqlite3DbFree(db, pDel);
121780      }
121781    }
121782  }
121783  rc = sqlite3ApiExit(db, rc);
121784  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
121785
121786  sqlite3_mutex_leave(db->mutex);
121787  return rc;
121788}
121789
121790
121791/*
121792** External API function used to create a new virtual-table module.
121793*/
121794SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
121795  sqlite3 *db,                    /* Database in which module is registered */
121796  const char *zName,              /* Name assigned to this module */
121797  const sqlite3_module *pModule,  /* The definition of the module */
121798  void *pAux                      /* Context pointer for xCreate/xConnect */
121799){
121800#ifdef SQLITE_ENABLE_API_ARMOR
121801  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121802#endif
121803  return createModule(db, zName, pModule, pAux, 0);
121804}
121805
121806/*
121807** External API function used to create a new virtual-table module.
121808*/
121809SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
121810  sqlite3 *db,                    /* Database in which module is registered */
121811  const char *zName,              /* Name assigned to this module */
121812  const sqlite3_module *pModule,  /* The definition of the module */
121813  void *pAux,                     /* Context pointer for xCreate/xConnect */
121814  void (*xDestroy)(void *)        /* Module destructor function */
121815){
121816#ifdef SQLITE_ENABLE_API_ARMOR
121817  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121818#endif
121819  return createModule(db, zName, pModule, pAux, xDestroy);
121820}
121821
121822/*
121823** Lock the virtual table so that it cannot be disconnected.
121824** Locks nest.  Every lock should have a corresponding unlock.
121825** If an unlock is omitted, resources leaks will occur.
121826**
121827** If a disconnect is attempted while a virtual table is locked,
121828** the disconnect is deferred until all locks have been removed.
121829*/
121830SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
121831  pVTab->nRef++;
121832}
121833
121834
121835/*
121836** pTab is a pointer to a Table structure representing a virtual-table.
121837** Return a pointer to the VTable object used by connection db to access
121838** this virtual-table, if one has been created, or NULL otherwise.
121839*/
121840SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
121841  VTable *pVtab;
121842  assert( IsVirtual(pTab) );
121843  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
121844  return pVtab;
121845}
121846
121847/*
121848** Decrement the ref-count on a virtual table object. When the ref-count
121849** reaches zero, call the xDisconnect() method to delete the object.
121850*/
121851SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
121852  sqlite3 *db = pVTab->db;
121853
121854  assert( db );
121855  assert( pVTab->nRef>0 );
121856  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
121857
121858  pVTab->nRef--;
121859  if( pVTab->nRef==0 ){
121860    sqlite3_vtab *p = pVTab->pVtab;
121861    if( p ){
121862      p->pModule->xDisconnect(p);
121863    }
121864    sqlite3DbFree(db, pVTab);
121865  }
121866}
121867
121868/*
121869** Table p is a virtual table. This function moves all elements in the
121870** p->pVTable list to the sqlite3.pDisconnect lists of their associated
121871** database connections to be disconnected at the next opportunity.
121872** Except, if argument db is not NULL, then the entry associated with
121873** connection db is left in the p->pVTable list.
121874*/
121875static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
121876  VTable *pRet = 0;
121877  VTable *pVTable = p->pVTable;
121878  p->pVTable = 0;
121879
121880  /* Assert that the mutex (if any) associated with the BtShared database
121881  ** that contains table p is held by the caller. See header comments
121882  ** above function sqlite3VtabUnlockList() for an explanation of why
121883  ** this makes it safe to access the sqlite3.pDisconnect list of any
121884  ** database connection that may have an entry in the p->pVTable list.
121885  */
121886  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
121887
121888  while( pVTable ){
121889    sqlite3 *db2 = pVTable->db;
121890    VTable *pNext = pVTable->pNext;
121891    assert( db2 );
121892    if( db2==db ){
121893      pRet = pVTable;
121894      p->pVTable = pRet;
121895      pRet->pNext = 0;
121896    }else{
121897      pVTable->pNext = db2->pDisconnect;
121898      db2->pDisconnect = pVTable;
121899    }
121900    pVTable = pNext;
121901  }
121902
121903  assert( !db || pRet );
121904  return pRet;
121905}
121906
121907/*
121908** Table *p is a virtual table. This function removes the VTable object
121909** for table *p associated with database connection db from the linked
121910** list in p->pVTab. It also decrements the VTable ref count. This is
121911** used when closing database connection db to free all of its VTable
121912** objects without disturbing the rest of the Schema object (which may
121913** be being used by other shared-cache connections).
121914*/
121915SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
121916  VTable **ppVTab;
121917
121918  assert( IsVirtual(p) );
121919  assert( sqlite3BtreeHoldsAllMutexes(db) );
121920  assert( sqlite3_mutex_held(db->mutex) );
121921
121922  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
121923    if( (*ppVTab)->db==db  ){
121924      VTable *pVTab = *ppVTab;
121925      *ppVTab = pVTab->pNext;
121926      sqlite3VtabUnlock(pVTab);
121927      break;
121928    }
121929  }
121930}
121931
121932
121933/*
121934** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
121935**
121936** This function may only be called when the mutexes associated with all
121937** shared b-tree databases opened using connection db are held by the
121938** caller. This is done to protect the sqlite3.pDisconnect list. The
121939** sqlite3.pDisconnect list is accessed only as follows:
121940**
121941**   1) By this function. In this case, all BtShared mutexes and the mutex
121942**      associated with the database handle itself must be held.
121943**
121944**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
121945**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
121946**      associated with the database the virtual table is stored in is held
121947**      or, if the virtual table is stored in a non-sharable database, then
121948**      the database handle mutex is held.
121949**
121950** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
121951** by multiple threads. It is thread-safe.
121952*/
121953SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
121954  VTable *p = db->pDisconnect;
121955  db->pDisconnect = 0;
121956
121957  assert( sqlite3BtreeHoldsAllMutexes(db) );
121958  assert( sqlite3_mutex_held(db->mutex) );
121959
121960  if( p ){
121961    sqlite3ExpirePreparedStatements(db);
121962    do {
121963      VTable *pNext = p->pNext;
121964      sqlite3VtabUnlock(p);
121965      p = pNext;
121966    }while( p );
121967  }
121968}
121969
121970/*
121971** Clear any and all virtual-table information from the Table record.
121972** This routine is called, for example, just before deleting the Table
121973** record.
121974**
121975** Since it is a virtual-table, the Table structure contains a pointer
121976** to the head of a linked list of VTable structures. Each VTable
121977** structure is associated with a single sqlite3* user of the schema.
121978** The reference count of the VTable structure associated with database
121979** connection db is decremented immediately (which may lead to the
121980** structure being xDisconnected and free). Any other VTable structures
121981** in the list are moved to the sqlite3.pDisconnect list of the associated
121982** database connection.
121983*/
121984SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
121985  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
121986  if( p->azModuleArg ){
121987    int i;
121988    for(i=0; i<p->nModuleArg; i++){
121989      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
121990    }
121991    sqlite3DbFree(db, p->azModuleArg);
121992  }
121993}
121994
121995/*
121996** Add a new module argument to pTable->azModuleArg[].
121997** The string is not copied - the pointer is stored.  The
121998** string will be freed automatically when the table is
121999** deleted.
122000*/
122001static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
122002  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
122003  char **azModuleArg;
122004  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
122005  if( azModuleArg==0 ){
122006    sqlite3DbFree(db, zArg);
122007  }else{
122008    int i = pTable->nModuleArg++;
122009    azModuleArg[i] = zArg;
122010    azModuleArg[i+1] = 0;
122011    pTable->azModuleArg = azModuleArg;
122012  }
122013}
122014
122015/*
122016** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
122017** statement.  The module name has been parsed, but the optional list
122018** of parameters that follow the module name are still pending.
122019*/
122020SQLITE_PRIVATE void sqlite3VtabBeginParse(
122021  Parse *pParse,        /* Parsing context */
122022  Token *pName1,        /* Name of new table, or database name */
122023  Token *pName2,        /* Name of new table or NULL */
122024  Token *pModuleName,   /* Name of the module for the virtual table */
122025  int ifNotExists       /* No error if the table already exists */
122026){
122027  int iDb;              /* The database the table is being created in */
122028  Table *pTable;        /* The new virtual table */
122029  sqlite3 *db;          /* Database connection */
122030
122031  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
122032  pTable = pParse->pNewTable;
122033  if( pTable==0 ) return;
122034  assert( 0==pTable->pIndex );
122035
122036  db = pParse->db;
122037  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
122038  assert( iDb>=0 );
122039
122040  pTable->tabFlags |= TF_Virtual;
122041  pTable->nModuleArg = 0;
122042  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
122043  addModuleArgument(db, pTable, 0);
122044  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
122045  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
122046       || (pParse->sNameToken.z==pName1->z && pName2->z==0)
122047  );
122048  pParse->sNameToken.n = (int)(
122049      &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
122050  );
122051
122052#ifndef SQLITE_OMIT_AUTHORIZATION
122053  /* Creating a virtual table invokes the authorization callback twice.
122054  ** The first invocation, to obtain permission to INSERT a row into the
122055  ** sqlite_master table, has already been made by sqlite3StartTable().
122056  ** The second call, to obtain permission to create the table, is made now.
122057  */
122058  if( pTable->azModuleArg ){
122059    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
122060            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
122061  }
122062#endif
122063}
122064
122065/*
122066** This routine takes the module argument that has been accumulating
122067** in pParse->zArg[] and appends it to the list of arguments on the
122068** virtual table currently under construction in pParse->pTable.
122069*/
122070static void addArgumentToVtab(Parse *pParse){
122071  if( pParse->sArg.z && pParse->pNewTable ){
122072    const char *z = (const char*)pParse->sArg.z;
122073    int n = pParse->sArg.n;
122074    sqlite3 *db = pParse->db;
122075    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
122076  }
122077}
122078
122079/*
122080** The parser calls this routine after the CREATE VIRTUAL TABLE statement
122081** has been completely parsed.
122082*/
122083SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
122084  Table *pTab = pParse->pNewTable;  /* The table being constructed */
122085  sqlite3 *db = pParse->db;         /* The database connection */
122086
122087  if( pTab==0 ) return;
122088  addArgumentToVtab(pParse);
122089  pParse->sArg.z = 0;
122090  if( pTab->nModuleArg<1 ) return;
122091
122092  /* If the CREATE VIRTUAL TABLE statement is being entered for the
122093  ** first time (in other words if the virtual table is actually being
122094  ** created now instead of just being read out of sqlite_master) then
122095  ** do additional initialization work and store the statement text
122096  ** in the sqlite_master table.
122097  */
122098  if( !db->init.busy ){
122099    char *zStmt;
122100    char *zWhere;
122101    int iDb;
122102    int iReg;
122103    Vdbe *v;
122104
122105    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
122106    if( pEnd ){
122107      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
122108    }
122109    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
122110
122111    /* A slot for the record has already been allocated in the
122112    ** SQLITE_MASTER table.  We just need to update that slot with all
122113    ** the information we've collected.
122114    **
122115    ** The VM register number pParse->regRowid holds the rowid of an
122116    ** entry in the sqlite_master table tht was created for this vtab
122117    ** by sqlite3StartTable().
122118    */
122119    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122120    sqlite3NestedParse(pParse,
122121      "UPDATE %Q.%s "
122122         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
122123       "WHERE rowid=#%d",
122124      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
122125      pTab->zName,
122126      pTab->zName,
122127      zStmt,
122128      pParse->regRowid
122129    );
122130    sqlite3DbFree(db, zStmt);
122131    v = sqlite3GetVdbe(pParse);
122132    sqlite3ChangeCookie(pParse, iDb);
122133
122134    sqlite3VdbeAddOp0(v, OP_Expire);
122135    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
122136    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
122137
122138    iReg = ++pParse->nMem;
122139    sqlite3VdbeLoadString(v, iReg, pTab->zName);
122140    sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
122141  }
122142
122143  /* If we are rereading the sqlite_master table create the in-memory
122144  ** record of the table. The xConnect() method is not called until
122145  ** the first time the virtual table is used in an SQL statement. This
122146  ** allows a schema that contains virtual tables to be loaded before
122147  ** the required virtual table implementations are registered.  */
122148  else {
122149    Table *pOld;
122150    Schema *pSchema = pTab->pSchema;
122151    const char *zName = pTab->zName;
122152    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
122153    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
122154    if( pOld ){
122155      sqlite3OomFault(db);
122156      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
122157      return;
122158    }
122159    pParse->pNewTable = 0;
122160  }
122161}
122162
122163/*
122164** The parser calls this routine when it sees the first token
122165** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
122166*/
122167SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
122168  addArgumentToVtab(pParse);
122169  pParse->sArg.z = 0;
122170  pParse->sArg.n = 0;
122171}
122172
122173/*
122174** The parser calls this routine for each token after the first token
122175** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
122176*/
122177SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
122178  Token *pArg = &pParse->sArg;
122179  if( pArg->z==0 ){
122180    pArg->z = p->z;
122181    pArg->n = p->n;
122182  }else{
122183    assert(pArg->z <= p->z);
122184    pArg->n = (int)(&p->z[p->n] - pArg->z);
122185  }
122186}
122187
122188/*
122189** Invoke a virtual table constructor (either xCreate or xConnect). The
122190** pointer to the function to invoke is passed as the fourth parameter
122191** to this procedure.
122192*/
122193static int vtabCallConstructor(
122194  sqlite3 *db,
122195  Table *pTab,
122196  Module *pMod,
122197  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
122198  char **pzErr
122199){
122200  VtabCtx sCtx;
122201  VTable *pVTable;
122202  int rc;
122203  const char *const*azArg = (const char *const*)pTab->azModuleArg;
122204  int nArg = pTab->nModuleArg;
122205  char *zErr = 0;
122206  char *zModuleName;
122207  int iDb;
122208  VtabCtx *pCtx;
122209
122210  /* Check that the virtual-table is not already being initialized */
122211  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
122212    if( pCtx->pTab==pTab ){
122213      *pzErr = sqlite3MPrintf(db,
122214          "vtable constructor called recursively: %s", pTab->zName
122215      );
122216      return SQLITE_LOCKED;
122217    }
122218  }
122219
122220  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
122221  if( !zModuleName ){
122222    return SQLITE_NOMEM_BKPT;
122223  }
122224
122225  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
122226  if( !pVTable ){
122227    sqlite3DbFree(db, zModuleName);
122228    return SQLITE_NOMEM_BKPT;
122229  }
122230  pVTable->db = db;
122231  pVTable->pMod = pMod;
122232
122233  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122234  pTab->azModuleArg[1] = db->aDb[iDb].zName;
122235
122236  /* Invoke the virtual table constructor */
122237  assert( &db->pVtabCtx );
122238  assert( xConstruct );
122239  sCtx.pTab = pTab;
122240  sCtx.pVTable = pVTable;
122241  sCtx.pPrior = db->pVtabCtx;
122242  sCtx.bDeclared = 0;
122243  db->pVtabCtx = &sCtx;
122244  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
122245  db->pVtabCtx = sCtx.pPrior;
122246  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
122247  assert( sCtx.pTab==pTab );
122248
122249  if( SQLITE_OK!=rc ){
122250    if( zErr==0 ){
122251      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
122252    }else {
122253      *pzErr = sqlite3MPrintf(db, "%s", zErr);
122254      sqlite3_free(zErr);
122255    }
122256    sqlite3DbFree(db, pVTable);
122257  }else if( ALWAYS(pVTable->pVtab) ){
122258    /* Justification of ALWAYS():  A correct vtab constructor must allocate
122259    ** the sqlite3_vtab object if successful.  */
122260    memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
122261    pVTable->pVtab->pModule = pMod->pModule;
122262    pVTable->nRef = 1;
122263    if( sCtx.bDeclared==0 ){
122264      const char *zFormat = "vtable constructor did not declare schema: %s";
122265      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
122266      sqlite3VtabUnlock(pVTable);
122267      rc = SQLITE_ERROR;
122268    }else{
122269      int iCol;
122270      u8 oooHidden = 0;
122271      /* If everything went according to plan, link the new VTable structure
122272      ** into the linked list headed by pTab->pVTable. Then loop through the
122273      ** columns of the table to see if any of them contain the token "hidden".
122274      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
122275      ** the type string.  */
122276      pVTable->pNext = pTab->pVTable;
122277      pTab->pVTable = pVTable;
122278
122279      for(iCol=0; iCol<pTab->nCol; iCol++){
122280        char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
122281        int nType;
122282        int i = 0;
122283        nType = sqlite3Strlen30(zType);
122284        for(i=0; i<nType; i++){
122285          if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
122286           && (i==0 || zType[i-1]==' ')
122287           && (zType[i+6]=='\0' || zType[i+6]==' ')
122288          ){
122289            break;
122290          }
122291        }
122292        if( i<nType ){
122293          int j;
122294          int nDel = 6 + (zType[i+6] ? 1 : 0);
122295          for(j=i; (j+nDel)<=nType; j++){
122296            zType[j] = zType[j+nDel];
122297          }
122298          if( zType[i]=='\0' && i>0 ){
122299            assert(zType[i-1]==' ');
122300            zType[i-1] = '\0';
122301          }
122302          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
122303          oooHidden = TF_OOOHidden;
122304        }else{
122305          pTab->tabFlags |= oooHidden;
122306        }
122307      }
122308    }
122309  }
122310
122311  sqlite3DbFree(db, zModuleName);
122312  return rc;
122313}
122314
122315/*
122316** This function is invoked by the parser to call the xConnect() method
122317** of the virtual table pTab. If an error occurs, an error code is returned
122318** and an error left in pParse.
122319**
122320** This call is a no-op if table pTab is not a virtual table.
122321*/
122322SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
122323  sqlite3 *db = pParse->db;
122324  const char *zMod;
122325  Module *pMod;
122326  int rc;
122327
122328  assert( pTab );
122329  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
122330    return SQLITE_OK;
122331  }
122332
122333  /* Locate the required virtual table module */
122334  zMod = pTab->azModuleArg[0];
122335  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
122336
122337  if( !pMod ){
122338    const char *zModule = pTab->azModuleArg[0];
122339    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
122340    rc = SQLITE_ERROR;
122341  }else{
122342    char *zErr = 0;
122343    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
122344    if( rc!=SQLITE_OK ){
122345      sqlite3ErrorMsg(pParse, "%s", zErr);
122346    }
122347    sqlite3DbFree(db, zErr);
122348  }
122349
122350  return rc;
122351}
122352/*
122353** Grow the db->aVTrans[] array so that there is room for at least one
122354** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
122355*/
122356static int growVTrans(sqlite3 *db){
122357  const int ARRAY_INCR = 5;
122358
122359  /* Grow the sqlite3.aVTrans array if required */
122360  if( (db->nVTrans%ARRAY_INCR)==0 ){
122361    VTable **aVTrans;
122362    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
122363    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
122364    if( !aVTrans ){
122365      return SQLITE_NOMEM_BKPT;
122366    }
122367    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
122368    db->aVTrans = aVTrans;
122369  }
122370
122371  return SQLITE_OK;
122372}
122373
122374/*
122375** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
122376** have already been reserved using growVTrans().
122377*/
122378static void addToVTrans(sqlite3 *db, VTable *pVTab){
122379  /* Add pVtab to the end of sqlite3.aVTrans */
122380  db->aVTrans[db->nVTrans++] = pVTab;
122381  sqlite3VtabLock(pVTab);
122382}
122383
122384/*
122385** This function is invoked by the vdbe to call the xCreate method
122386** of the virtual table named zTab in database iDb.
122387**
122388** If an error occurs, *pzErr is set to point an an English language
122389** description of the error and an SQLITE_XXX error code is returned.
122390** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
122391*/
122392SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
122393  int rc = SQLITE_OK;
122394  Table *pTab;
122395  Module *pMod;
122396  const char *zMod;
122397
122398  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
122399  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
122400
122401  /* Locate the required virtual table module */
122402  zMod = pTab->azModuleArg[0];
122403  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
122404
122405  /* If the module has been registered and includes a Create method,
122406  ** invoke it now. If the module has not been registered, return an
122407  ** error. Otherwise, do nothing.
122408  */
122409  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
122410    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
122411    rc = SQLITE_ERROR;
122412  }else{
122413    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
122414  }
122415
122416  /* Justification of ALWAYS():  The xConstructor method is required to
122417  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
122418  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
122419    rc = growVTrans(db);
122420    if( rc==SQLITE_OK ){
122421      addToVTrans(db, sqlite3GetVTable(db, pTab));
122422    }
122423  }
122424
122425  return rc;
122426}
122427
122428/*
122429** This function is used to set the schema of a virtual table.  It is only
122430** valid to call this function from within the xCreate() or xConnect() of a
122431** virtual table module.
122432*/
122433SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
122434  VtabCtx *pCtx;
122435  Parse *pParse;
122436  int rc = SQLITE_OK;
122437  Table *pTab;
122438  char *zErr = 0;
122439
122440#ifdef SQLITE_ENABLE_API_ARMOR
122441  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
122442    return SQLITE_MISUSE_BKPT;
122443  }
122444#endif
122445  sqlite3_mutex_enter(db->mutex);
122446  pCtx = db->pVtabCtx;
122447  if( !pCtx || pCtx->bDeclared ){
122448    sqlite3Error(db, SQLITE_MISUSE);
122449    sqlite3_mutex_leave(db->mutex);
122450    return SQLITE_MISUSE_BKPT;
122451  }
122452  pTab = pCtx->pTab;
122453  assert( (pTab->tabFlags & TF_Virtual)!=0 );
122454
122455  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
122456  if( pParse==0 ){
122457    rc = SQLITE_NOMEM_BKPT;
122458  }else{
122459    pParse->declareVtab = 1;
122460    pParse->db = db;
122461    pParse->nQueryLoop = 1;
122462
122463    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
122464     && pParse->pNewTable
122465     && !db->mallocFailed
122466     && !pParse->pNewTable->pSelect
122467     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
122468    ){
122469      if( !pTab->aCol ){
122470        Table *pNew = pParse->pNewTable;
122471        Index *pIdx;
122472        pTab->aCol = pNew->aCol;
122473        pTab->nCol = pNew->nCol;
122474        pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
122475        pNew->nCol = 0;
122476        pNew->aCol = 0;
122477        assert( pTab->pIndex==0 );
122478        if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
122479          rc = SQLITE_ERROR;
122480        }
122481        pIdx = pNew->pIndex;
122482        if( pIdx ){
122483          assert( pIdx->pNext==0 );
122484          pTab->pIndex = pIdx;
122485          pNew->pIndex = 0;
122486          pIdx->pTable = pTab;
122487        }
122488      }
122489      pCtx->bDeclared = 1;
122490    }else{
122491      sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
122492      sqlite3DbFree(db, zErr);
122493      rc = SQLITE_ERROR;
122494    }
122495    pParse->declareVtab = 0;
122496
122497    if( pParse->pVdbe ){
122498      sqlite3VdbeFinalize(pParse->pVdbe);
122499    }
122500    sqlite3DeleteTable(db, pParse->pNewTable);
122501    sqlite3ParserReset(pParse);
122502    sqlite3StackFree(db, pParse);
122503  }
122504
122505  assert( (rc&0xff)==rc );
122506  rc = sqlite3ApiExit(db, rc);
122507  sqlite3_mutex_leave(db->mutex);
122508  return rc;
122509}
122510
122511/*
122512** This function is invoked by the vdbe to call the xDestroy method
122513** of the virtual table named zTab in database iDb. This occurs
122514** when a DROP TABLE is mentioned.
122515**
122516** This call is a no-op if zTab is not a virtual table.
122517*/
122518SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
122519  int rc = SQLITE_OK;
122520  Table *pTab;
122521
122522  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
122523  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
122524    VTable *p;
122525    int (*xDestroy)(sqlite3_vtab *);
122526    for(p=pTab->pVTable; p; p=p->pNext){
122527      assert( p->pVtab );
122528      if( p->pVtab->nRef>0 ){
122529        return SQLITE_LOCKED;
122530      }
122531    }
122532    p = vtabDisconnectAll(db, pTab);
122533    xDestroy = p->pMod->pModule->xDestroy;
122534    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
122535    rc = xDestroy(p->pVtab);
122536    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
122537    if( rc==SQLITE_OK ){
122538      assert( pTab->pVTable==p && p->pNext==0 );
122539      p->pVtab = 0;
122540      pTab->pVTable = 0;
122541      sqlite3VtabUnlock(p);
122542    }
122543  }
122544
122545  return rc;
122546}
122547
122548/*
122549** This function invokes either the xRollback or xCommit method
122550** of each of the virtual tables in the sqlite3.aVTrans array. The method
122551** called is identified by the second argument, "offset", which is
122552** the offset of the method to call in the sqlite3_module structure.
122553**
122554** The array is cleared after invoking the callbacks.
122555*/
122556static void callFinaliser(sqlite3 *db, int offset){
122557  int i;
122558  if( db->aVTrans ){
122559    VTable **aVTrans = db->aVTrans;
122560    db->aVTrans = 0;
122561    for(i=0; i<db->nVTrans; i++){
122562      VTable *pVTab = aVTrans[i];
122563      sqlite3_vtab *p = pVTab->pVtab;
122564      if( p ){
122565        int (*x)(sqlite3_vtab *);
122566        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
122567        if( x ) x(p);
122568      }
122569      pVTab->iSavepoint = 0;
122570      sqlite3VtabUnlock(pVTab);
122571    }
122572    sqlite3DbFree(db, aVTrans);
122573    db->nVTrans = 0;
122574  }
122575}
122576
122577/*
122578** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
122579** array. Return the error code for the first error that occurs, or
122580** SQLITE_OK if all xSync operations are successful.
122581**
122582** If an error message is available, leave it in p->zErrMsg.
122583*/
122584SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
122585  int i;
122586  int rc = SQLITE_OK;
122587  VTable **aVTrans = db->aVTrans;
122588
122589  db->aVTrans = 0;
122590  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
122591    int (*x)(sqlite3_vtab *);
122592    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
122593    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
122594      rc = x(pVtab);
122595      sqlite3VtabImportErrmsg(p, pVtab);
122596    }
122597  }
122598  db->aVTrans = aVTrans;
122599  return rc;
122600}
122601
122602/*
122603** Invoke the xRollback method of all virtual tables in the
122604** sqlite3.aVTrans array. Then clear the array itself.
122605*/
122606SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
122607  callFinaliser(db, offsetof(sqlite3_module,xRollback));
122608  return SQLITE_OK;
122609}
122610
122611/*
122612** Invoke the xCommit method of all virtual tables in the
122613** sqlite3.aVTrans array. Then clear the array itself.
122614*/
122615SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
122616  callFinaliser(db, offsetof(sqlite3_module,xCommit));
122617  return SQLITE_OK;
122618}
122619
122620/*
122621** If the virtual table pVtab supports the transaction interface
122622** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
122623** not currently open, invoke the xBegin method now.
122624**
122625** If the xBegin call is successful, place the sqlite3_vtab pointer
122626** in the sqlite3.aVTrans array.
122627*/
122628SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
122629  int rc = SQLITE_OK;
122630  const sqlite3_module *pModule;
122631
122632  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
122633  ** than zero, then this function is being called from within a
122634  ** virtual module xSync() callback. It is illegal to write to
122635  ** virtual module tables in this case, so return SQLITE_LOCKED.
122636  */
122637  if( sqlite3VtabInSync(db) ){
122638    return SQLITE_LOCKED;
122639  }
122640  if( !pVTab ){
122641    return SQLITE_OK;
122642  }
122643  pModule = pVTab->pVtab->pModule;
122644
122645  if( pModule->xBegin ){
122646    int i;
122647
122648    /* If pVtab is already in the aVTrans array, return early */
122649    for(i=0; i<db->nVTrans; i++){
122650      if( db->aVTrans[i]==pVTab ){
122651        return SQLITE_OK;
122652      }
122653    }
122654
122655    /* Invoke the xBegin method. If successful, add the vtab to the
122656    ** sqlite3.aVTrans[] array. */
122657    rc = growVTrans(db);
122658    if( rc==SQLITE_OK ){
122659      rc = pModule->xBegin(pVTab->pVtab);
122660      if( rc==SQLITE_OK ){
122661        int iSvpt = db->nStatement + db->nSavepoint;
122662        addToVTrans(db, pVTab);
122663        if( iSvpt && pModule->xSavepoint ){
122664          pVTab->iSavepoint = iSvpt;
122665          rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
122666        }
122667      }
122668    }
122669  }
122670  return rc;
122671}
122672
122673/*
122674** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
122675** virtual tables that currently have an open transaction. Pass iSavepoint
122676** as the second argument to the virtual table method invoked.
122677**
122678** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
122679** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
122680** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
122681** an open transaction is invoked.
122682**
122683** If any virtual table method returns an error code other than SQLITE_OK,
122684** processing is abandoned and the error returned to the caller of this
122685** function immediately. If all calls to virtual table methods are successful,
122686** SQLITE_OK is returned.
122687*/
122688SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
122689  int rc = SQLITE_OK;
122690
122691  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
122692  assert( iSavepoint>=-1 );
122693  if( db->aVTrans ){
122694    int i;
122695    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
122696      VTable *pVTab = db->aVTrans[i];
122697      const sqlite3_module *pMod = pVTab->pMod->pModule;
122698      if( pVTab->pVtab && pMod->iVersion>=2 ){
122699        int (*xMethod)(sqlite3_vtab *, int);
122700        switch( op ){
122701          case SAVEPOINT_BEGIN:
122702            xMethod = pMod->xSavepoint;
122703            pVTab->iSavepoint = iSavepoint+1;
122704            break;
122705          case SAVEPOINT_ROLLBACK:
122706            xMethod = pMod->xRollbackTo;
122707            break;
122708          default:
122709            xMethod = pMod->xRelease;
122710            break;
122711        }
122712        if( xMethod && pVTab->iSavepoint>iSavepoint ){
122713          rc = xMethod(pVTab->pVtab, iSavepoint);
122714        }
122715      }
122716    }
122717  }
122718  return rc;
122719}
122720
122721/*
122722** The first parameter (pDef) is a function implementation.  The
122723** second parameter (pExpr) is the first argument to this function.
122724** If pExpr is a column in a virtual table, then let the virtual
122725** table implementation have an opportunity to overload the function.
122726**
122727** This routine is used to allow virtual table implementations to
122728** overload MATCH, LIKE, GLOB, and REGEXP operators.
122729**
122730** Return either the pDef argument (indicating no change) or a
122731** new FuncDef structure that is marked as ephemeral using the
122732** SQLITE_FUNC_EPHEM flag.
122733*/
122734SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
122735  sqlite3 *db,    /* Database connection for reporting malloc problems */
122736  FuncDef *pDef,  /* Function to possibly overload */
122737  int nArg,       /* Number of arguments to the function */
122738  Expr *pExpr     /* First argument to the function */
122739){
122740  Table *pTab;
122741  sqlite3_vtab *pVtab;
122742  sqlite3_module *pMod;
122743  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
122744  void *pArg = 0;
122745  FuncDef *pNew;
122746  int rc = 0;
122747  char *zLowerName;
122748  unsigned char *z;
122749
122750
122751  /* Check to see the left operand is a column in a virtual table */
122752  if( NEVER(pExpr==0) ) return pDef;
122753  if( pExpr->op!=TK_COLUMN ) return pDef;
122754  pTab = pExpr->pTab;
122755  if( NEVER(pTab==0) ) return pDef;
122756  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
122757  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
122758  assert( pVtab!=0 );
122759  assert( pVtab->pModule!=0 );
122760  pMod = (sqlite3_module *)pVtab->pModule;
122761  if( pMod->xFindFunction==0 ) return pDef;
122762
122763  /* Call the xFindFunction method on the virtual table implementation
122764  ** to see if the implementation wants to overload this function
122765  */
122766  zLowerName = sqlite3DbStrDup(db, pDef->zName);
122767  if( zLowerName ){
122768    for(z=(unsigned char*)zLowerName; *z; z++){
122769      *z = sqlite3UpperToLower[*z];
122770    }
122771    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
122772    sqlite3DbFree(db, zLowerName);
122773  }
122774  if( rc==0 ){
122775    return pDef;
122776  }
122777
122778  /* Create a new ephemeral function definition for the overloaded
122779  ** function */
122780  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
122781                             + sqlite3Strlen30(pDef->zName) + 1);
122782  if( pNew==0 ){
122783    return pDef;
122784  }
122785  *pNew = *pDef;
122786  pNew->zName = (const char*)&pNew[1];
122787  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
122788  pNew->xSFunc = xSFunc;
122789  pNew->pUserData = pArg;
122790  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
122791  return pNew;
122792}
122793
122794/*
122795** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
122796** array so that an OP_VBegin will get generated for it.  Add pTab to the
122797** array if it is missing.  If pTab is already in the array, this routine
122798** is a no-op.
122799*/
122800SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
122801  Parse *pToplevel = sqlite3ParseToplevel(pParse);
122802  int i, n;
122803  Table **apVtabLock;
122804
122805  assert( IsVirtual(pTab) );
122806  for(i=0; i<pToplevel->nVtabLock; i++){
122807    if( pTab==pToplevel->apVtabLock[i] ) return;
122808  }
122809  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
122810  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
122811  if( apVtabLock ){
122812    pToplevel->apVtabLock = apVtabLock;
122813    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
122814  }else{
122815    sqlite3OomFault(pToplevel->db);
122816  }
122817}
122818
122819/*
122820** Check to see if virtual table module pMod can be have an eponymous
122821** virtual table instance.  If it can, create one if one does not already
122822** exist. Return non-zero if the eponymous virtual table instance exists
122823** when this routine returns, and return zero if it does not exist.
122824**
122825** An eponymous virtual table instance is one that is named after its
122826** module, and more importantly, does not require a CREATE VIRTUAL TABLE
122827** statement in order to come into existance.  Eponymous virtual table
122828** instances always exist.  They cannot be DROP-ed.
122829**
122830** Any virtual table module for which xConnect and xCreate are the same
122831** method can have an eponymous virtual table instance.
122832*/
122833SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
122834  const sqlite3_module *pModule = pMod->pModule;
122835  Table *pTab;
122836  char *zErr = 0;
122837  int rc;
122838  sqlite3 *db = pParse->db;
122839  if( pMod->pEpoTab ) return 1;
122840  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
122841  pTab = sqlite3DbMallocZero(db, sizeof(Table));
122842  if( pTab==0 ) return 0;
122843  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
122844  if( pTab->zName==0 ){
122845    sqlite3DbFree(db, pTab);
122846    return 0;
122847  }
122848  pMod->pEpoTab = pTab;
122849  pTab->nRef = 1;
122850  pTab->pSchema = db->aDb[0].pSchema;
122851  pTab->tabFlags |= TF_Virtual;
122852  pTab->nModuleArg = 0;
122853  pTab->iPKey = -1;
122854  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122855  addModuleArgument(db, pTab, 0);
122856  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122857  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
122858  if( rc ){
122859    sqlite3ErrorMsg(pParse, "%s", zErr);
122860    sqlite3DbFree(db, zErr);
122861    sqlite3VtabEponymousTableClear(db, pMod);
122862    return 0;
122863  }
122864  return 1;
122865}
122866
122867/*
122868** Erase the eponymous virtual table instance associated with
122869** virtual table module pMod, if it exists.
122870*/
122871SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
122872  Table *pTab = pMod->pEpoTab;
122873  if( pTab!=0 ){
122874    /* Mark the table as Ephemeral prior to deleting it, so that the
122875    ** sqlite3DeleteTable() routine will know that it is not stored in
122876    ** the schema. */
122877    pTab->tabFlags |= TF_Ephemeral;
122878    sqlite3DeleteTable(db, pTab);
122879    pMod->pEpoTab = 0;
122880  }
122881}
122882
122883/*
122884** Return the ON CONFLICT resolution mode in effect for the virtual
122885** table update operation currently in progress.
122886**
122887** The results of this routine are undefined unless it is called from
122888** within an xUpdate method.
122889*/
122890SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
122891  static const unsigned char aMap[] = {
122892    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
122893  };
122894#ifdef SQLITE_ENABLE_API_ARMOR
122895  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122896#endif
122897  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
122898  assert( OE_Ignore==4 && OE_Replace==5 );
122899  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
122900  return (int)aMap[db->vtabOnConflict-1];
122901}
122902
122903/*
122904** Call from within the xCreate() or xConnect() methods to provide
122905** the SQLite core with additional information about the behavior
122906** of the virtual table being implemented.
122907*/
122908SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
122909  va_list ap;
122910  int rc = SQLITE_OK;
122911
122912#ifdef SQLITE_ENABLE_API_ARMOR
122913  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122914#endif
122915  sqlite3_mutex_enter(db->mutex);
122916  va_start(ap, op);
122917  switch( op ){
122918    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
122919      VtabCtx *p = db->pVtabCtx;
122920      if( !p ){
122921        rc = SQLITE_MISUSE_BKPT;
122922      }else{
122923        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
122924        p->pVTable->bConstraint = (u8)va_arg(ap, int);
122925      }
122926      break;
122927    }
122928    default:
122929      rc = SQLITE_MISUSE_BKPT;
122930      break;
122931  }
122932  va_end(ap);
122933
122934  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
122935  sqlite3_mutex_leave(db->mutex);
122936  return rc;
122937}
122938
122939#endif /* SQLITE_OMIT_VIRTUALTABLE */
122940
122941/************** End of vtab.c ************************************************/
122942/************** Begin file wherecode.c ***************************************/
122943/*
122944** 2015-06-06
122945**
122946** The author disclaims copyright to this source code.  In place of
122947** a legal notice, here is a blessing:
122948**
122949**    May you do good and not evil.
122950**    May you find forgiveness for yourself and forgive others.
122951**    May you share freely, never taking more than you give.
122952**
122953*************************************************************************
122954** This module contains C code that generates VDBE code used to process
122955** the WHERE clause of SQL statements.
122956**
122957** This file was split off from where.c on 2015-06-06 in order to reduce the
122958** size of where.c and make it easier to edit.  This file contains the routines
122959** that actually generate the bulk of the WHERE loop code.  The original where.c
122960** file retains the code that does query planning and analysis.
122961*/
122962/* #include "sqliteInt.h" */
122963/************** Include whereInt.h in the middle of wherecode.c **************/
122964/************** Begin file whereInt.h ****************************************/
122965/*
122966** 2013-11-12
122967**
122968** The author disclaims copyright to this source code.  In place of
122969** a legal notice, here is a blessing:
122970**
122971**    May you do good and not evil.
122972**    May you find forgiveness for yourself and forgive others.
122973**    May you share freely, never taking more than you give.
122974**
122975*************************************************************************
122976**
122977** This file contains structure and macro definitions for the query
122978** planner logic in "where.c".  These definitions are broken out into
122979** a separate source file for easier editing.
122980*/
122981
122982/*
122983** Trace output macros
122984*/
122985#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
122986/***/ int sqlite3WhereTrace;
122987#endif
122988#if defined(SQLITE_DEBUG) \
122989    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
122990# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
122991# define WHERETRACE_ENABLED 1
122992#else
122993# define WHERETRACE(K,X)
122994#endif
122995
122996/* Forward references
122997*/
122998typedef struct WhereClause WhereClause;
122999typedef struct WhereMaskSet WhereMaskSet;
123000typedef struct WhereOrInfo WhereOrInfo;
123001typedef struct WhereAndInfo WhereAndInfo;
123002typedef struct WhereLevel WhereLevel;
123003typedef struct WhereLoop WhereLoop;
123004typedef struct WherePath WherePath;
123005typedef struct WhereTerm WhereTerm;
123006typedef struct WhereLoopBuilder WhereLoopBuilder;
123007typedef struct WhereScan WhereScan;
123008typedef struct WhereOrCost WhereOrCost;
123009typedef struct WhereOrSet WhereOrSet;
123010
123011/*
123012** This object contains information needed to implement a single nested
123013** loop in WHERE clause.
123014**
123015** Contrast this object with WhereLoop.  This object describes the
123016** implementation of the loop.  WhereLoop describes the algorithm.
123017** This object contains a pointer to the WhereLoop algorithm as one of
123018** its elements.
123019**
123020** The WhereInfo object contains a single instance of this object for
123021** each term in the FROM clause (which is to say, for each of the
123022** nested loops as implemented).  The order of WhereLevel objects determines
123023** the loop nested order, with WhereInfo.a[0] being the outer loop and
123024** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
123025*/
123026struct WhereLevel {
123027  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
123028  int iTabCur;          /* The VDBE cursor used to access the table */
123029  int iIdxCur;          /* The VDBE cursor used to access pIdx */
123030  int addrBrk;          /* Jump here to break out of the loop */
123031  int addrNxt;          /* Jump here to start the next IN combination */
123032  int addrSkip;         /* Jump here for next iteration of skip-scan */
123033  int addrCont;         /* Jump here to continue with the next loop cycle */
123034  int addrFirst;        /* First instruction of interior of the loop */
123035  int addrBody;         /* Beginning of the body of this loop */
123036#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123037  u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
123038  int addrLikeRep;      /* LIKE range processing address */
123039#endif
123040  u8 iFrom;             /* Which entry in the FROM clause */
123041  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
123042  int p1, p2;           /* Operands of the opcode used to ends the loop */
123043  union {               /* Information that depends on pWLoop->wsFlags */
123044    struct {
123045      int nIn;              /* Number of entries in aInLoop[] */
123046      struct InLoop {
123047        int iCur;              /* The VDBE cursor used by this IN operator */
123048        int addrInTop;         /* Top of the IN loop */
123049        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
123050      } *aInLoop;           /* Information about each nested IN operator */
123051    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
123052    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
123053  } u;
123054  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
123055  Bitmask notReady;          /* FROM entries not usable at this level */
123056#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123057  int addrVisit;        /* Address at which row is visited */
123058#endif
123059};
123060
123061/*
123062** Each instance of this object represents an algorithm for evaluating one
123063** term of a join.  Every term of the FROM clause will have at least
123064** one corresponding WhereLoop object (unless INDEXED BY constraints
123065** prevent a query solution - which is an error) and many terms of the
123066** FROM clause will have multiple WhereLoop objects, each describing a
123067** potential way of implementing that FROM-clause term, together with
123068** dependencies and cost estimates for using the chosen algorithm.
123069**
123070** Query planning consists of building up a collection of these WhereLoop
123071** objects, then computing a particular sequence of WhereLoop objects, with
123072** one WhereLoop object per FROM clause term, that satisfy all dependencies
123073** and that minimize the overall cost.
123074*/
123075struct WhereLoop {
123076  Bitmask prereq;       /* Bitmask of other loops that must run first */
123077  Bitmask maskSelf;     /* Bitmask identifying table iTab */
123078#ifdef SQLITE_DEBUG
123079  char cId;             /* Symbolic ID of this loop for debugging use */
123080#endif
123081  u8 iTab;              /* Position in FROM clause of table for this loop */
123082  u8 iSortIdx;          /* Sorting index number.  0==None */
123083  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
123084  LogEst rRun;          /* Cost of running each loop */
123085  LogEst nOut;          /* Estimated number of output rows */
123086  union {
123087    struct {               /* Information for internal btree tables */
123088      u16 nEq;               /* Number of equality constraints */
123089      Index *pIndex;         /* Index used, or NULL */
123090    } btree;
123091    struct {               /* Information for virtual tables */
123092      int idxNum;            /* Index number */
123093      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
123094      i8 isOrdered;          /* True if satisfies ORDER BY */
123095      u16 omitMask;          /* Terms that may be omitted */
123096      char *idxStr;          /* Index identifier string */
123097    } vtab;
123098  } u;
123099  u32 wsFlags;          /* WHERE_* flags describing the plan */
123100  u16 nLTerm;           /* Number of entries in aLTerm[] */
123101  u16 nSkip;            /* Number of NULL aLTerm[] entries */
123102  /**** whereLoopXfer() copies fields above ***********************/
123103# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
123104  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
123105  WhereTerm **aLTerm;   /* WhereTerms used */
123106  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
123107  WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
123108};
123109
123110/* This object holds the prerequisites and the cost of running a
123111** subquery on one operand of an OR operator in the WHERE clause.
123112** See WhereOrSet for additional information
123113*/
123114struct WhereOrCost {
123115  Bitmask prereq;     /* Prerequisites */
123116  LogEst rRun;        /* Cost of running this subquery */
123117  LogEst nOut;        /* Number of outputs for this subquery */
123118};
123119
123120/* The WhereOrSet object holds a set of possible WhereOrCosts that
123121** correspond to the subquery(s) of OR-clause processing.  Only the
123122** best N_OR_COST elements are retained.
123123*/
123124#define N_OR_COST 3
123125struct WhereOrSet {
123126  u16 n;                      /* Number of valid a[] entries */
123127  WhereOrCost a[N_OR_COST];   /* Set of best costs */
123128};
123129
123130/*
123131** Each instance of this object holds a sequence of WhereLoop objects
123132** that implement some or all of a query plan.
123133**
123134** Think of each WhereLoop object as a node in a graph with arcs
123135** showing dependencies and costs for travelling between nodes.  (That is
123136** not a completely accurate description because WhereLoop costs are a
123137** vector, not a scalar, and because dependencies are many-to-one, not
123138** one-to-one as are graph nodes.  But it is a useful visualization aid.)
123139** Then a WherePath object is a path through the graph that visits some
123140** or all of the WhereLoop objects once.
123141**
123142** The "solver" works by creating the N best WherePath objects of length
123143** 1.  Then using those as a basis to compute the N best WherePath objects
123144** of length 2.  And so forth until the length of WherePaths equals the
123145** number of nodes in the FROM clause.  The best (lowest cost) WherePath
123146** at the end is the chosen query plan.
123147*/
123148struct WherePath {
123149  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
123150  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
123151  LogEst nRow;          /* Estimated number of rows generated by this path */
123152  LogEst rCost;         /* Total cost of this path */
123153  LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
123154  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
123155  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
123156};
123157
123158/*
123159** The query generator uses an array of instances of this structure to
123160** help it analyze the subexpressions of the WHERE clause.  Each WHERE
123161** clause subexpression is separated from the others by AND operators,
123162** usually, or sometimes subexpressions separated by OR.
123163**
123164** All WhereTerms are collected into a single WhereClause structure.
123165** The following identity holds:
123166**
123167**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
123168**
123169** When a term is of the form:
123170**
123171**              X <op> <expr>
123172**
123173** where X is a column name and <op> is one of certain operators,
123174** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
123175** cursor number and column number for X.  WhereTerm.eOperator records
123176** the <op> using a bitmask encoding defined by WO_xxx below.  The
123177** use of a bitmask encoding for the operator allows us to search
123178** quickly for terms that match any of several different operators.
123179**
123180** A WhereTerm might also be two or more subterms connected by OR:
123181**
123182**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
123183**
123184** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
123185** and the WhereTerm.u.pOrInfo field points to auxiliary information that
123186** is collected about the OR clause.
123187**
123188** If a term in the WHERE clause does not match either of the two previous
123189** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
123190** to the original subexpression content and wtFlags is set up appropriately
123191** but no other fields in the WhereTerm object are meaningful.
123192**
123193** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
123194** but they do so indirectly.  A single WhereMaskSet structure translates
123195** cursor number into bits and the translated bit is stored in the prereq
123196** fields.  The translation is used in order to maximize the number of
123197** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
123198** spread out over the non-negative integers.  For example, the cursor
123199** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
123200** translates these sparse cursor numbers into consecutive integers
123201** beginning with 0 in order to make the best possible use of the available
123202** bits in the Bitmask.  So, in the example above, the cursor numbers
123203** would be mapped into integers 0 through 7.
123204**
123205** The number of terms in a join is limited by the number of bits
123206** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
123207** is only able to process joins with 64 or fewer tables.
123208*/
123209struct WhereTerm {
123210  Expr *pExpr;            /* Pointer to the subexpression that is this term */
123211  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
123212  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
123213  union {
123214    int leftColumn;         /* Column number of X in "X <op> <expr>" */
123215    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
123216    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
123217  } u;
123218  LogEst truthProb;       /* Probability of truth for this expression */
123219  u16 eOperator;          /* A WO_xx value describing <op> */
123220  u16 wtFlags;            /* TERM_xxx bit flags.  See below */
123221  u8 nChild;              /* Number of children that must disable us */
123222  u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
123223  WhereClause *pWC;       /* The clause this term is part of */
123224  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
123225  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
123226};
123227
123228/*
123229** Allowed values of WhereTerm.wtFlags
123230*/
123231#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
123232#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
123233#define TERM_CODED      0x04   /* This term is already coded */
123234#define TERM_COPIED     0x08   /* Has a child */
123235#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
123236#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
123237#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
123238#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123239#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
123240#else
123241#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
123242#endif
123243#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
123244#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
123245#define TERM_LIKE       0x400  /* The original LIKE operator */
123246#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
123247
123248/*
123249** An instance of the WhereScan object is used as an iterator for locating
123250** terms in the WHERE clause that are useful to the query planner.
123251*/
123252struct WhereScan {
123253  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
123254  WhereClause *pWC;          /* WhereClause currently being scanned */
123255  const char *zCollName;     /* Required collating sequence, if not NULL */
123256  Expr *pIdxExpr;            /* Search for this index expression */
123257  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
123258  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
123259  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
123260  u32 opMask;                /* Acceptable operators */
123261  int k;                     /* Resume scanning at this->pWC->a[this->k] */
123262  int aiCur[11];             /* Cursors in the equivalence class */
123263  i16 aiColumn[11];          /* Corresponding column number in the eq-class */
123264};
123265
123266/*
123267** An instance of the following structure holds all information about a
123268** WHERE clause.  Mostly this is a container for one or more WhereTerms.
123269**
123270** Explanation of pOuter:  For a WHERE clause of the form
123271**
123272**           a AND ((b AND c) OR (d AND e)) AND f
123273**
123274** There are separate WhereClause objects for the whole clause and for
123275** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
123276** subclauses points to the WhereClause object for the whole clause.
123277*/
123278struct WhereClause {
123279  WhereInfo *pWInfo;       /* WHERE clause processing context */
123280  WhereClause *pOuter;     /* Outer conjunction */
123281  u8 op;                   /* Split operator.  TK_AND or TK_OR */
123282  int nTerm;               /* Number of terms */
123283  int nSlot;               /* Number of entries in a[] */
123284  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
123285#if defined(SQLITE_SMALL_STACK)
123286  WhereTerm aStatic[1];    /* Initial static space for a[] */
123287#else
123288  WhereTerm aStatic[8];    /* Initial static space for a[] */
123289#endif
123290};
123291
123292/*
123293** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
123294** a dynamically allocated instance of the following structure.
123295*/
123296struct WhereOrInfo {
123297  WhereClause wc;          /* Decomposition into subterms */
123298  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
123299};
123300
123301/*
123302** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
123303** a dynamically allocated instance of the following structure.
123304*/
123305struct WhereAndInfo {
123306  WhereClause wc;          /* The subexpression broken out */
123307};
123308
123309/*
123310** An instance of the following structure keeps track of a mapping
123311** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
123312**
123313** The VDBE cursor numbers are small integers contained in
123314** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
123315** clause, the cursor numbers might not begin with 0 and they might
123316** contain gaps in the numbering sequence.  But we want to make maximum
123317** use of the bits in our bitmasks.  This structure provides a mapping
123318** from the sparse cursor numbers into consecutive integers beginning
123319** with 0.
123320**
123321** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
123322** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
123323**
123324** For example, if the WHERE clause expression used these VDBE
123325** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
123326** would map those cursor numbers into bits 0 through 5.
123327**
123328** Note that the mapping is not necessarily ordered.  In the example
123329** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
123330** 57->5, 73->4.  Or one of 719 other combinations might be used. It
123331** does not really matter.  What is important is that sparse cursor
123332** numbers all get mapped into bit numbers that begin with 0 and contain
123333** no gaps.
123334*/
123335struct WhereMaskSet {
123336  int n;                        /* Number of assigned cursor values */
123337  int ix[BMS];                  /* Cursor assigned to each bit */
123338};
123339
123340/*
123341** Initialize a WhereMaskSet object
123342*/
123343#define initMaskSet(P)  (P)->n=0
123344
123345/*
123346** This object is a convenience wrapper holding all information needed
123347** to construct WhereLoop objects for a particular query.
123348*/
123349struct WhereLoopBuilder {
123350  WhereInfo *pWInfo;        /* Information about this WHERE */
123351  WhereClause *pWC;         /* WHERE clause terms */
123352  ExprList *pOrderBy;       /* ORDER BY clause */
123353  WhereLoop *pNew;          /* Template WhereLoop */
123354  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
123355#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123356  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
123357  int nRecValid;            /* Number of valid fields currently in pRec */
123358#endif
123359};
123360
123361/*
123362** The WHERE clause processing routine has two halves.  The
123363** first part does the start of the WHERE loop and the second
123364** half does the tail of the WHERE loop.  An instance of
123365** this structure is returned by the first half and passed
123366** into the second half to give some continuity.
123367**
123368** An instance of this object holds the complete state of the query
123369** planner.
123370*/
123371struct WhereInfo {
123372  Parse *pParse;            /* Parsing and code generating context */
123373  SrcList *pTabList;        /* List of tables in the join */
123374  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
123375  ExprList *pDistinctSet;   /* DISTINCT over all these values */
123376  WhereLoop *pLoops;        /* List of all WhereLoop objects */
123377  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
123378  LogEst nRowOut;           /* Estimated number of output rows */
123379  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
123380  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
123381  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
123382  u8 sorted;                /* True if really sorted (not just grouped) */
123383  u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
123384  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
123385  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
123386  u8 nLevel;                /* Number of nested loop */
123387  u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
123388  int iTop;                 /* The very beginning of the WHERE loop */
123389  int iContinue;            /* Jump here to continue with next record */
123390  int iBreak;               /* Jump here to break out of the loop */
123391  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
123392  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
123393  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
123394  WhereClause sWC;          /* Decomposition of the WHERE clause */
123395  WhereLevel a[1];          /* Information about each nest loop in WHERE */
123396};
123397
123398/*
123399** Private interfaces - callable only by other where.c routines.
123400**
123401** where.c:
123402*/
123403SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
123404#ifdef WHERETRACE_ENABLED
123405SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
123406#endif
123407SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
123408  WhereClause *pWC,     /* The WHERE clause to be searched */
123409  int iCur,             /* Cursor number of LHS */
123410  int iColumn,          /* Column number of LHS */
123411  Bitmask notReady,     /* RHS must not overlap with this mask */
123412  u32 op,               /* Mask of WO_xx values describing operator */
123413  Index *pIdx           /* Must be compatible with this index, if not NULL */
123414);
123415
123416/* wherecode.c: */
123417#ifndef SQLITE_OMIT_EXPLAIN
123418SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
123419  Parse *pParse,                  /* Parse context */
123420  SrcList *pTabList,              /* Table list this loop refers to */
123421  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
123422  int iLevel,                     /* Value for "level" column of output */
123423  int iFrom,                      /* Value for "from" column of output */
123424  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
123425);
123426#else
123427# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
123428#endif /* SQLITE_OMIT_EXPLAIN */
123429#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123430SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
123431  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
123432  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
123433  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
123434  int addrExplain                 /* Address of OP_Explain (or 0) */
123435);
123436#else
123437# define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
123438#endif
123439SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
123440  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
123441  int iLevel,          /* Which level of pWInfo->a[] should be coded */
123442  Bitmask notReady     /* Which tables are currently available */
123443);
123444
123445/* whereexpr.c: */
123446SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
123447SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
123448SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
123449SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
123450SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
123451SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
123452SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
123453
123454
123455
123456
123457
123458/*
123459** Bitmasks for the operators on WhereTerm objects.  These are all
123460** operators that are of interest to the query planner.  An
123461** OR-ed combination of these values can be used when searching for
123462** particular WhereTerms within a WhereClause.
123463**
123464** Value constraints:
123465**     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
123466**     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
123467**     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
123468**     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
123469**     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
123470**     WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
123471*/
123472#define WO_IN     0x0001
123473#define WO_EQ     0x0002
123474#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
123475#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
123476#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
123477#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
123478#define WO_MATCH  0x0040
123479#define WO_IS     0x0080
123480#define WO_ISNULL 0x0100
123481#define WO_OR     0x0200       /* Two or more OR-connected terms */
123482#define WO_AND    0x0400       /* Two or more AND-connected terms */
123483#define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
123484#define WO_NOOP   0x1000       /* This term does not restrict search space */
123485
123486#define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
123487#define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
123488
123489/*
123490** These are definitions of bits in the WhereLoop.wsFlags field.
123491** The particular combination of bits in each WhereLoop help to
123492** determine the algorithm that WhereLoop represents.
123493*/
123494#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
123495#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
123496#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
123497#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
123498#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
123499#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
123500#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
123501#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
123502#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
123503#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
123504#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
123505#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
123506#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
123507#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
123508#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
123509#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
123510#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
123511#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
123512#define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
123513
123514/************** End of whereInt.h ********************************************/
123515/************** Continuing where we left off in wherecode.c ******************/
123516
123517#ifndef SQLITE_OMIT_EXPLAIN
123518/*
123519** This routine is a helper for explainIndexRange() below
123520**
123521** pStr holds the text of an expression that we are building up one term
123522** at a time.  This routine adds a new term to the end of the expression.
123523** Terms are separated by AND so add the "AND" text for second and subsequent
123524** terms only.
123525*/
123526static void explainAppendTerm(
123527  StrAccum *pStr,             /* The text expression being built */
123528  int iTerm,                  /* Index of this term.  First is zero */
123529  const char *zColumn,        /* Name of the column */
123530  const char *zOp             /* Name of the operator */
123531){
123532  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
123533  sqlite3StrAccumAppendAll(pStr, zColumn);
123534  sqlite3StrAccumAppend(pStr, zOp, 1);
123535  sqlite3StrAccumAppend(pStr, "?", 1);
123536}
123537
123538/*
123539** Return the name of the i-th column of the pIdx index.
123540*/
123541static const char *explainIndexColumnName(Index *pIdx, int i){
123542  i = pIdx->aiColumn[i];
123543  if( i==XN_EXPR ) return "<expr>";
123544  if( i==XN_ROWID ) return "rowid";
123545  return pIdx->pTable->aCol[i].zName;
123546}
123547
123548/*
123549** Argument pLevel describes a strategy for scanning table pTab. This
123550** function appends text to pStr that describes the subset of table
123551** rows scanned by the strategy in the form of an SQL expression.
123552**
123553** For example, if the query:
123554**
123555**   SELECT * FROM t1 WHERE a=1 AND b>2;
123556**
123557** is run and there is an index on (a, b), then this function returns a
123558** string similar to:
123559**
123560**   "a=? AND b>?"
123561*/
123562static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
123563  Index *pIndex = pLoop->u.btree.pIndex;
123564  u16 nEq = pLoop->u.btree.nEq;
123565  u16 nSkip = pLoop->nSkip;
123566  int i, j;
123567
123568  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
123569  sqlite3StrAccumAppend(pStr, " (", 2);
123570  for(i=0; i<nEq; i++){
123571    const char *z = explainIndexColumnName(pIndex, i);
123572    if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
123573    sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
123574  }
123575
123576  j = i;
123577  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
123578    const char *z = explainIndexColumnName(pIndex, i);
123579    explainAppendTerm(pStr, i++, z, ">");
123580  }
123581  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
123582    const char *z = explainIndexColumnName(pIndex, j);
123583    explainAppendTerm(pStr, i, z, "<");
123584  }
123585  sqlite3StrAccumAppend(pStr, ")", 1);
123586}
123587
123588/*
123589** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
123590** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
123591** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
123592** is added to the output to describe the table scan strategy in pLevel.
123593**
123594** If an OP_Explain opcode is added to the VM, its address is returned.
123595** Otherwise, if no OP_Explain is coded, zero is returned.
123596*/
123597SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
123598  Parse *pParse,                  /* Parse context */
123599  SrcList *pTabList,              /* Table list this loop refers to */
123600  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
123601  int iLevel,                     /* Value for "level" column of output */
123602  int iFrom,                      /* Value for "from" column of output */
123603  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
123604){
123605  int ret = 0;
123606#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
123607  if( pParse->explain==2 )
123608#endif
123609  {
123610    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
123611    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
123612    sqlite3 *db = pParse->db;     /* Database handle */
123613    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
123614    int isSearch;                 /* True for a SEARCH. False for SCAN. */
123615    WhereLoop *pLoop;             /* The controlling WhereLoop object */
123616    u32 flags;                    /* Flags that describe this loop */
123617    char *zMsg;                   /* Text to add to EQP output */
123618    StrAccum str;                 /* EQP output string */
123619    char zBuf[100];               /* Initial space for EQP output string */
123620
123621    pLoop = pLevel->pWLoop;
123622    flags = pLoop->wsFlags;
123623    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
123624
123625    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
123626            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
123627            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
123628
123629    sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
123630    sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
123631    if( pItem->pSelect ){
123632      sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
123633    }else{
123634      sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
123635    }
123636
123637    if( pItem->zAlias ){
123638      sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
123639    }
123640    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
123641      const char *zFmt = 0;
123642      Index *pIdx;
123643
123644      assert( pLoop->u.btree.pIndex!=0 );
123645      pIdx = pLoop->u.btree.pIndex;
123646      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
123647      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
123648        if( isSearch ){
123649          zFmt = "PRIMARY KEY";
123650        }
123651      }else if( flags & WHERE_PARTIALIDX ){
123652        zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
123653      }else if( flags & WHERE_AUTO_INDEX ){
123654        zFmt = "AUTOMATIC COVERING INDEX";
123655      }else if( flags & WHERE_IDX_ONLY ){
123656        zFmt = "COVERING INDEX %s";
123657      }else{
123658        zFmt = "INDEX %s";
123659      }
123660      if( zFmt ){
123661        sqlite3StrAccumAppend(&str, " USING ", 7);
123662        sqlite3XPrintf(&str, zFmt, pIdx->zName);
123663        explainIndexRange(&str, pLoop);
123664      }
123665    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
123666      const char *zRangeOp;
123667      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
123668        zRangeOp = "=";
123669      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
123670        zRangeOp = ">? AND rowid<";
123671      }else if( flags&WHERE_BTM_LIMIT ){
123672        zRangeOp = ">";
123673      }else{
123674        assert( flags&WHERE_TOP_LIMIT);
123675        zRangeOp = "<";
123676      }
123677      sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
123678    }
123679#ifndef SQLITE_OMIT_VIRTUALTABLE
123680    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
123681      sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
123682                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
123683    }
123684#endif
123685#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
123686    if( pLoop->nOut>=10 ){
123687      sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
123688    }else{
123689      sqlite3StrAccumAppend(&str, " (~1 row)", 9);
123690    }
123691#endif
123692    zMsg = sqlite3StrAccumFinish(&str);
123693    ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
123694  }
123695  return ret;
123696}
123697#endif /* SQLITE_OMIT_EXPLAIN */
123698
123699#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123700/*
123701** Configure the VM passed as the first argument with an
123702** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
123703** implement level pLvl. Argument pSrclist is a pointer to the FROM
123704** clause that the scan reads data from.
123705**
123706** If argument addrExplain is not 0, it must be the address of an
123707** OP_Explain instruction that describes the same loop.
123708*/
123709SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
123710  Vdbe *v,                        /* Vdbe to add scanstatus entry to */
123711  SrcList *pSrclist,              /* FROM clause pLvl reads data from */
123712  WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
123713  int addrExplain                 /* Address of OP_Explain (or 0) */
123714){
123715  const char *zObj = 0;
123716  WhereLoop *pLoop = pLvl->pWLoop;
123717  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
123718    zObj = pLoop->u.btree.pIndex->zName;
123719  }else{
123720    zObj = pSrclist->a[pLvl->iFrom].zName;
123721  }
123722  sqlite3VdbeScanStatus(
123723      v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
123724  );
123725}
123726#endif
123727
123728
123729/*
123730** Disable a term in the WHERE clause.  Except, do not disable the term
123731** if it controls a LEFT OUTER JOIN and it did not originate in the ON
123732** or USING clause of that join.
123733**
123734** Consider the term t2.z='ok' in the following queries:
123735**
123736**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
123737**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
123738**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
123739**
123740** The t2.z='ok' is disabled in the in (2) because it originates
123741** in the ON clause.  The term is disabled in (3) because it is not part
123742** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
123743**
123744** Disabling a term causes that term to not be tested in the inner loop
123745** of the join.  Disabling is an optimization.  When terms are satisfied
123746** by indices, we disable them to prevent redundant tests in the inner
123747** loop.  We would get the correct results if nothing were ever disabled,
123748** but joins might run a little slower.  The trick is to disable as much
123749** as we can without disabling too much.  If we disabled in (1), we'd get
123750** the wrong answer.  See ticket #813.
123751**
123752** If all the children of a term are disabled, then that term is also
123753** automatically disabled.  In this way, terms get disabled if derived
123754** virtual terms are tested first.  For example:
123755**
123756**      x GLOB 'abc*' AND x>='abc' AND x<'acd'
123757**      \___________/     \______/     \_____/
123758**         parent          child1       child2
123759**
123760** Only the parent term was in the original WHERE clause.  The child1
123761** and child2 terms were added by the LIKE optimization.  If both of
123762** the virtual child terms are valid, then testing of the parent can be
123763** skipped.
123764**
123765** Usually the parent term is marked as TERM_CODED.  But if the parent
123766** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
123767** The TERM_LIKECOND marking indicates that the term should be coded inside
123768** a conditional such that is only evaluated on the second pass of a
123769** LIKE-optimization loop, when scanning BLOBs instead of strings.
123770*/
123771static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
123772  int nLoop = 0;
123773  while( pTerm
123774      && (pTerm->wtFlags & TERM_CODED)==0
123775      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
123776      && (pLevel->notReady & pTerm->prereqAll)==0
123777  ){
123778    if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
123779      pTerm->wtFlags |= TERM_LIKECOND;
123780    }else{
123781      pTerm->wtFlags |= TERM_CODED;
123782    }
123783    if( pTerm->iParent<0 ) break;
123784    pTerm = &pTerm->pWC->a[pTerm->iParent];
123785    pTerm->nChild--;
123786    if( pTerm->nChild!=0 ) break;
123787    nLoop++;
123788  }
123789}
123790
123791/*
123792** Code an OP_Affinity opcode to apply the column affinity string zAff
123793** to the n registers starting at base.
123794**
123795** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
123796** beginning and end of zAff are ignored.  If all entries in zAff are
123797** SQLITE_AFF_BLOB, then no code gets generated.
123798**
123799** This routine makes its own copy of zAff so that the caller is free
123800** to modify zAff after this routine returns.
123801*/
123802static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
123803  Vdbe *v = pParse->pVdbe;
123804  if( zAff==0 ){
123805    assert( pParse->db->mallocFailed );
123806    return;
123807  }
123808  assert( v!=0 );
123809
123810  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
123811  ** and end of the affinity string.
123812  */
123813  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
123814    n--;
123815    base++;
123816    zAff++;
123817  }
123818  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
123819    n--;
123820  }
123821
123822  /* Code the OP_Affinity opcode if there is anything left to do. */
123823  if( n>0 ){
123824    sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
123825    sqlite3ExprCacheAffinityChange(pParse, base, n);
123826  }
123827}
123828
123829
123830/*
123831** Generate code for a single equality term of the WHERE clause.  An equality
123832** term can be either X=expr or X IN (...).   pTerm is the term to be
123833** coded.
123834**
123835** The current value for the constraint is left in register iReg.
123836**
123837** For a constraint of the form X=expr, the expression is evaluated and its
123838** result is left on the stack.  For constraints of the form X IN (...)
123839** this routine sets up a loop that will iterate over all values of X.
123840*/
123841static int codeEqualityTerm(
123842  Parse *pParse,      /* The parsing context */
123843  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
123844  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
123845  int iEq,            /* Index of the equality term within this level */
123846  int bRev,           /* True for reverse-order IN operations */
123847  int iTarget         /* Attempt to leave results in this register */
123848){
123849  Expr *pX = pTerm->pExpr;
123850  Vdbe *v = pParse->pVdbe;
123851  int iReg;                  /* Register holding results */
123852
123853  assert( iTarget>0 );
123854  if( pX->op==TK_EQ || pX->op==TK_IS ){
123855    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
123856  }else if( pX->op==TK_ISNULL ){
123857    iReg = iTarget;
123858    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
123859#ifndef SQLITE_OMIT_SUBQUERY
123860  }else{
123861    int eType;
123862    int iTab;
123863    struct InLoop *pIn;
123864    WhereLoop *pLoop = pLevel->pWLoop;
123865
123866    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
123867      && pLoop->u.btree.pIndex!=0
123868      && pLoop->u.btree.pIndex->aSortOrder[iEq]
123869    ){
123870      testcase( iEq==0 );
123871      testcase( bRev );
123872      bRev = !bRev;
123873    }
123874    assert( pX->op==TK_IN );
123875    iReg = iTarget;
123876    eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
123877    if( eType==IN_INDEX_INDEX_DESC ){
123878      testcase( bRev );
123879      bRev = !bRev;
123880    }
123881    iTab = pX->iTable;
123882    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
123883    VdbeCoverageIf(v, bRev);
123884    VdbeCoverageIf(v, !bRev);
123885    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
123886    pLoop->wsFlags |= WHERE_IN_ABLE;
123887    if( pLevel->u.in.nIn==0 ){
123888      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
123889    }
123890    pLevel->u.in.nIn++;
123891    pLevel->u.in.aInLoop =
123892       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
123893                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
123894    pIn = pLevel->u.in.aInLoop;
123895    if( pIn ){
123896      pIn += pLevel->u.in.nIn - 1;
123897      pIn->iCur = iTab;
123898      if( eType==IN_INDEX_ROWID ){
123899        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
123900      }else{
123901        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
123902      }
123903      pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
123904      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
123905    }else{
123906      pLevel->u.in.nIn = 0;
123907    }
123908#endif
123909  }
123910  disableTerm(pLevel, pTerm);
123911  return iReg;
123912}
123913
123914/*
123915** Generate code that will evaluate all == and IN constraints for an
123916** index scan.
123917**
123918** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
123919** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
123920** The index has as many as three equality constraints, but in this
123921** example, the third "c" value is an inequality.  So only two
123922** constraints are coded.  This routine will generate code to evaluate
123923** a==5 and b IN (1,2,3).  The current values for a and b will be stored
123924** in consecutive registers and the index of the first register is returned.
123925**
123926** In the example above nEq==2.  But this subroutine works for any value
123927** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
123928** The only thing it does is allocate the pLevel->iMem memory cell and
123929** compute the affinity string.
123930**
123931** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
123932** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
123933** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
123934** occurs after the nEq quality constraints.
123935**
123936** This routine allocates a range of nEq+nExtraReg memory cells and returns
123937** the index of the first memory cell in that range. The code that
123938** calls this routine will use that memory range to store keys for
123939** start and termination conditions of the loop.
123940** key value of the loop.  If one or more IN operators appear, then
123941** this routine allocates an additional nEq memory cells for internal
123942** use.
123943**
123944** Before returning, *pzAff is set to point to a buffer containing a
123945** copy of the column affinity string of the index allocated using
123946** sqlite3DbMalloc(). Except, entries in the copy of the string associated
123947** with equality constraints that use BLOB or NONE affinity are set to
123948** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
123949**
123950**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
123951**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
123952**
123953** In the example above, the index on t1(a) has TEXT affinity. But since
123954** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
123955** no conversion should be attempted before using a t2.b value as part of
123956** a key to search the index. Hence the first byte in the returned affinity
123957** string in this example would be set to SQLITE_AFF_BLOB.
123958*/
123959static int codeAllEqualityTerms(
123960  Parse *pParse,        /* Parsing context */
123961  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
123962  int bRev,             /* Reverse the order of IN operators */
123963  int nExtraReg,        /* Number of extra registers to allocate */
123964  char **pzAff          /* OUT: Set to point to affinity string */
123965){
123966  u16 nEq;                      /* The number of == or IN constraints to code */
123967  u16 nSkip;                    /* Number of left-most columns to skip */
123968  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
123969  Index *pIdx;                  /* The index being used for this loop */
123970  WhereTerm *pTerm;             /* A single constraint term */
123971  WhereLoop *pLoop;             /* The WhereLoop object */
123972  int j;                        /* Loop counter */
123973  int regBase;                  /* Base register */
123974  int nReg;                     /* Number of registers to allocate */
123975  char *zAff;                   /* Affinity string to return */
123976
123977  /* This module is only called on query plans that use an index. */
123978  pLoop = pLevel->pWLoop;
123979  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
123980  nEq = pLoop->u.btree.nEq;
123981  nSkip = pLoop->nSkip;
123982  pIdx = pLoop->u.btree.pIndex;
123983  assert( pIdx!=0 );
123984
123985  /* Figure out how many memory cells we will need then allocate them.
123986  */
123987  regBase = pParse->nMem + 1;
123988  nReg = pLoop->u.btree.nEq + nExtraReg;
123989  pParse->nMem += nReg;
123990
123991  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
123992  assert( zAff!=0 || pParse->db->mallocFailed );
123993
123994  if( nSkip ){
123995    int iIdxCur = pLevel->iIdxCur;
123996    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
123997    VdbeCoverageIf(v, bRev==0);
123998    VdbeCoverageIf(v, bRev!=0);
123999    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
124000    j = sqlite3VdbeAddOp0(v, OP_Goto);
124001    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
124002                            iIdxCur, 0, regBase, nSkip);
124003    VdbeCoverageIf(v, bRev==0);
124004    VdbeCoverageIf(v, bRev!=0);
124005    sqlite3VdbeJumpHere(v, j);
124006    for(j=0; j<nSkip; j++){
124007      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
124008      testcase( pIdx->aiColumn[j]==XN_EXPR );
124009      VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
124010    }
124011  }
124012
124013  /* Evaluate the equality constraints
124014  */
124015  assert( zAff==0 || (int)strlen(zAff)>=nEq );
124016  for(j=nSkip; j<nEq; j++){
124017    int r1;
124018    pTerm = pLoop->aLTerm[j];
124019    assert( pTerm!=0 );
124020    /* The following testcase is true for indices with redundant columns.
124021    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
124022    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
124023    testcase( pTerm->wtFlags & TERM_VIRTUAL );
124024    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
124025    if( r1!=regBase+j ){
124026      if( nReg==1 ){
124027        sqlite3ReleaseTempReg(pParse, regBase);
124028        regBase = r1;
124029      }else{
124030        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
124031      }
124032    }
124033    testcase( pTerm->eOperator & WO_ISNULL );
124034    testcase( pTerm->eOperator & WO_IN );
124035    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
124036      Expr *pRight = pTerm->pExpr->pRight;
124037      if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
124038        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
124039        VdbeCoverage(v);
124040      }
124041      if( zAff ){
124042        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
124043          zAff[j] = SQLITE_AFF_BLOB;
124044        }
124045        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
124046          zAff[j] = SQLITE_AFF_BLOB;
124047        }
124048      }
124049    }
124050  }
124051  *pzAff = zAff;
124052  return regBase;
124053}
124054
124055#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124056/*
124057** If the most recently coded instruction is a constant range constraint
124058** (a string literal) that originated from the LIKE optimization, then
124059** set P3 and P5 on the OP_String opcode so that the string will be cast
124060** to a BLOB at appropriate times.
124061**
124062** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
124063** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
124064** scan loop run twice, once for strings and a second time for BLOBs.
124065** The OP_String opcodes on the second pass convert the upper and lower
124066** bound string constants to blobs.  This routine makes the necessary changes
124067** to the OP_String opcodes for that to happen.
124068**
124069** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
124070** only the one pass through the string space is required, so this routine
124071** becomes a no-op.
124072*/
124073static void whereLikeOptimizationStringFixup(
124074  Vdbe *v,                /* prepared statement under construction */
124075  WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
124076  WhereTerm *pTerm        /* The upper or lower bound just coded */
124077){
124078  if( pTerm->wtFlags & TERM_LIKEOPT ){
124079    VdbeOp *pOp;
124080    assert( pLevel->iLikeRepCntr>0 );
124081    pOp = sqlite3VdbeGetOp(v, -1);
124082    assert( pOp!=0 );
124083    assert( pOp->opcode==OP_String8
124084            || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
124085    pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
124086    pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
124087  }
124088}
124089#else
124090# define whereLikeOptimizationStringFixup(A,B,C)
124091#endif
124092
124093#ifdef SQLITE_ENABLE_CURSOR_HINTS
124094/*
124095** Information is passed from codeCursorHint() down to individual nodes of
124096** the expression tree (by sqlite3WalkExpr()) using an instance of this
124097** structure.
124098*/
124099struct CCurHint {
124100  int iTabCur;    /* Cursor for the main table */
124101  int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
124102  Index *pIdx;    /* The index used to access the table */
124103};
124104
124105/*
124106** This function is called for every node of an expression that is a candidate
124107** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
124108** the table CCurHint.iTabCur, verify that the same column can be
124109** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
124110*/
124111static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
124112  struct CCurHint *pHint = pWalker->u.pCCurHint;
124113  assert( pHint->pIdx!=0 );
124114  if( pExpr->op==TK_COLUMN
124115   && pExpr->iTable==pHint->iTabCur
124116   && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
124117  ){
124118    pWalker->eCode = 1;
124119  }
124120  return WRC_Continue;
124121}
124122
124123/*
124124** Test whether or not expression pExpr, which was part of a WHERE clause,
124125** should be included in the cursor-hint for a table that is on the rhs
124126** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
124127** expression is not suitable.
124128**
124129** An expression is unsuitable if it might evaluate to non NULL even if
124130** a TK_COLUMN node that does affect the value of the expression is set
124131** to NULL. For example:
124132**
124133**   col IS NULL
124134**   col IS NOT NULL
124135**   coalesce(col, 1)
124136**   CASE WHEN col THEN 0 ELSE 1 END
124137*/
124138static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
124139  if( pExpr->op==TK_IS
124140   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
124141   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
124142  ){
124143    pWalker->eCode = 1;
124144  }else if( pExpr->op==TK_FUNCTION ){
124145    int d1;
124146    char d2[3];
124147    if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
124148      pWalker->eCode = 1;
124149    }
124150  }
124151
124152  return WRC_Continue;
124153}
124154
124155
124156/*
124157** This function is called on every node of an expression tree used as an
124158** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
124159** that accesses any table other than the one identified by
124160** CCurHint.iTabCur, then do the following:
124161**
124162**   1) allocate a register and code an OP_Column instruction to read
124163**      the specified column into the new register, and
124164**
124165**   2) transform the expression node to a TK_REGISTER node that reads
124166**      from the newly populated register.
124167**
124168** Also, if the node is a TK_COLUMN that does access the table idenified
124169** by pCCurHint.iTabCur, and an index is being used (which we will
124170** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
124171** an access of the index rather than the original table.
124172*/
124173static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
124174  int rc = WRC_Continue;
124175  struct CCurHint *pHint = pWalker->u.pCCurHint;
124176  if( pExpr->op==TK_COLUMN ){
124177    if( pExpr->iTable!=pHint->iTabCur ){
124178      Vdbe *v = pWalker->pParse->pVdbe;
124179      int reg = ++pWalker->pParse->nMem;   /* Register for column value */
124180      sqlite3ExprCodeGetColumnOfTable(
124181          v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
124182      );
124183      pExpr->op = TK_REGISTER;
124184      pExpr->iTable = reg;
124185    }else if( pHint->pIdx!=0 ){
124186      pExpr->iTable = pHint->iIdxCur;
124187      pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
124188      assert( pExpr->iColumn>=0 );
124189    }
124190  }else if( pExpr->op==TK_AGG_FUNCTION ){
124191    /* An aggregate function in the WHERE clause of a query means this must
124192    ** be a correlated sub-query, and expression pExpr is an aggregate from
124193    ** the parent context. Do not walk the function arguments in this case.
124194    **
124195    ** todo: It should be possible to replace this node with a TK_REGISTER
124196    ** expression, as the result of the expression must be stored in a
124197    ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
124198    rc = WRC_Prune;
124199  }
124200  return rc;
124201}
124202
124203/*
124204** Insert an OP_CursorHint instruction if it is appropriate to do so.
124205*/
124206static void codeCursorHint(
124207  struct SrcList_item *pTabItem,  /* FROM clause item */
124208  WhereInfo *pWInfo,    /* The where clause */
124209  WhereLevel *pLevel,   /* Which loop to provide hints for */
124210  WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
124211){
124212  Parse *pParse = pWInfo->pParse;
124213  sqlite3 *db = pParse->db;
124214  Vdbe *v = pParse->pVdbe;
124215  Expr *pExpr = 0;
124216  WhereLoop *pLoop = pLevel->pWLoop;
124217  int iCur;
124218  WhereClause *pWC;
124219  WhereTerm *pTerm;
124220  int i, j;
124221  struct CCurHint sHint;
124222  Walker sWalker;
124223
124224  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
124225  iCur = pLevel->iTabCur;
124226  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
124227  sHint.iTabCur = iCur;
124228  sHint.iIdxCur = pLevel->iIdxCur;
124229  sHint.pIdx = pLoop->u.btree.pIndex;
124230  memset(&sWalker, 0, sizeof(sWalker));
124231  sWalker.pParse = pParse;
124232  sWalker.u.pCCurHint = &sHint;
124233  pWC = &pWInfo->sWC;
124234  for(i=0; i<pWC->nTerm; i++){
124235    pTerm = &pWC->a[i];
124236    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
124237    if( pTerm->prereqAll & pLevel->notReady ) continue;
124238
124239    /* Any terms specified as part of the ON(...) clause for any LEFT
124240    ** JOIN for which the current table is not the rhs are omitted
124241    ** from the cursor-hint.
124242    **
124243    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
124244    ** that were specified as part of the WHERE clause must be excluded.
124245    ** This is to address the following:
124246    **
124247    **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
124248    **
124249    ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
124250    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
124251    ** pushed down to the cursor, this row is filtered out, causing
124252    ** SQLite to synthesize a row of NULL values. Which does match the
124253    ** WHERE clause, and so the query returns a row. Which is incorrect.
124254    **
124255    ** For the same reason, WHERE terms such as:
124256    **
124257    **   WHERE 1 = (t2.c IS NULL)
124258    **
124259    ** are also excluded. See codeCursorHintIsOrFunction() for details.
124260    */
124261    if( pTabItem->fg.jointype & JT_LEFT ){
124262      Expr *pExpr = pTerm->pExpr;
124263      if( !ExprHasProperty(pExpr, EP_FromJoin)
124264       || pExpr->iRightJoinTable!=pTabItem->iCursor
124265      ){
124266        sWalker.eCode = 0;
124267        sWalker.xExprCallback = codeCursorHintIsOrFunction;
124268        sqlite3WalkExpr(&sWalker, pTerm->pExpr);
124269        if( sWalker.eCode ) continue;
124270      }
124271    }else{
124272      if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
124273    }
124274
124275    /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
124276    ** the cursor.  These terms are not needed as hints for a pure range
124277    ** scan (that has no == terms) so omit them. */
124278    if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
124279      for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
124280      if( j<pLoop->nLTerm ) continue;
124281    }
124282
124283    /* No subqueries or non-deterministic functions allowed */
124284    if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
124285
124286    /* For an index scan, make sure referenced columns are actually in
124287    ** the index. */
124288    if( sHint.pIdx!=0 ){
124289      sWalker.eCode = 0;
124290      sWalker.xExprCallback = codeCursorHintCheckExpr;
124291      sqlite3WalkExpr(&sWalker, pTerm->pExpr);
124292      if( sWalker.eCode ) continue;
124293    }
124294
124295    /* If we survive all prior tests, that means this term is worth hinting */
124296    pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
124297  }
124298  if( pExpr!=0 ){
124299    sWalker.xExprCallback = codeCursorHintFixExpr;
124300    sqlite3WalkExpr(&sWalker, pExpr);
124301    sqlite3VdbeAddOp4(v, OP_CursorHint,
124302                      (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
124303                      (const char*)pExpr, P4_EXPR);
124304  }
124305}
124306#else
124307# define codeCursorHint(A,B,C,D)  /* No-op */
124308#endif /* SQLITE_ENABLE_CURSOR_HINTS */
124309
124310/*
124311** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
124312** a rowid value just read from cursor iIdxCur, open on index pIdx. This
124313** function generates code to do a deferred seek of cursor iCur to the
124314** rowid stored in register iRowid.
124315**
124316** Normally, this is just:
124317**
124318**   OP_Seek $iCur $iRowid
124319**
124320** However, if the scan currently being coded is a branch of an OR-loop and
124321** the statement currently being coded is a SELECT, then P3 of the OP_Seek
124322** is set to iIdxCur and P4 is set to point to an array of integers
124323** containing one entry for each column of the table cursor iCur is open
124324** on. For each table column, if the column is the i'th column of the
124325** index, then the corresponding array entry is set to (i+1). If the column
124326** does not appear in the index at all, the array entry is set to 0.
124327*/
124328static void codeDeferredSeek(
124329  WhereInfo *pWInfo,              /* Where clause context */
124330  Index *pIdx,                    /* Index scan is using */
124331  int iCur,                       /* Cursor for IPK b-tree */
124332  int iIdxCur                     /* Index cursor */
124333){
124334  Parse *pParse = pWInfo->pParse; /* Parse context */
124335  Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
124336
124337  assert( iIdxCur>0 );
124338  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
124339
124340  sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
124341  if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
124342   && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
124343  ){
124344    int i;
124345    Table *pTab = pIdx->pTable;
124346    int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
124347    if( ai ){
124348      ai[0] = pTab->nCol;
124349      for(i=0; i<pIdx->nColumn-1; i++){
124350        assert( pIdx->aiColumn[i]<pTab->nCol );
124351        if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
124352      }
124353      sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
124354    }
124355  }
124356}
124357
124358/*
124359** Generate code for the start of the iLevel-th loop in the WHERE clause
124360** implementation described by pWInfo.
124361*/
124362SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
124363  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
124364  int iLevel,          /* Which level of pWInfo->a[] should be coded */
124365  Bitmask notReady     /* Which tables are currently available */
124366){
124367  int j, k;            /* Loop counters */
124368  int iCur;            /* The VDBE cursor for the table */
124369  int addrNxt;         /* Where to jump to continue with the next IN case */
124370  int omitTable;       /* True if we use the index only */
124371  int bRev;            /* True if we need to scan in reverse order */
124372  WhereLevel *pLevel;  /* The where level to be coded */
124373  WhereLoop *pLoop;    /* The WhereLoop object being coded */
124374  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
124375  WhereTerm *pTerm;               /* A WHERE clause term */
124376  Parse *pParse;                  /* Parsing context */
124377  sqlite3 *db;                    /* Database connection */
124378  Vdbe *v;                        /* The prepared stmt under constructions */
124379  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
124380  int addrBrk;                    /* Jump here to break out of the loop */
124381  int addrCont;                   /* Jump here to continue with next cycle */
124382  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
124383  int iReleaseReg = 0;      /* Temp register to free before returning */
124384
124385  pParse = pWInfo->pParse;
124386  v = pParse->pVdbe;
124387  pWC = &pWInfo->sWC;
124388  db = pParse->db;
124389  pLevel = &pWInfo->a[iLevel];
124390  pLoop = pLevel->pWLoop;
124391  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
124392  iCur = pTabItem->iCursor;
124393  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
124394  bRev = (pWInfo->revMask>>iLevel)&1;
124395  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
124396           && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
124397  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
124398
124399  /* Create labels for the "break" and "continue" instructions
124400  ** for the current loop.  Jump to addrBrk to break out of a loop.
124401  ** Jump to cont to go immediately to the next iteration of the
124402  ** loop.
124403  **
124404  ** When there is an IN operator, we also have a "addrNxt" label that
124405  ** means to continue with the next IN value combination.  When
124406  ** there are no IN operators in the constraints, the "addrNxt" label
124407  ** is the same as "addrBrk".
124408  */
124409  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
124410  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
124411
124412  /* If this is the right table of a LEFT OUTER JOIN, allocate and
124413  ** initialize a memory cell that records if this table matches any
124414  ** row of the left table of the join.
124415  */
124416  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
124417    pLevel->iLeftJoin = ++pParse->nMem;
124418    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
124419    VdbeComment((v, "init LEFT JOIN no-match flag"));
124420  }
124421
124422  /* Special case of a FROM clause subquery implemented as a co-routine */
124423  if( pTabItem->fg.viaCoroutine ){
124424    int regYield = pTabItem->regReturn;
124425    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
124426    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
124427    VdbeCoverage(v);
124428    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
124429    pLevel->op = OP_Goto;
124430  }else
124431
124432#ifndef SQLITE_OMIT_VIRTUALTABLE
124433  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
124434    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
124435    **          to access the data.
124436    */
124437    int iReg;   /* P3 Value for OP_VFilter */
124438    int addrNotFound;
124439    int nConstraint = pLoop->nLTerm;
124440    int iIn;    /* Counter for IN constraints */
124441
124442    sqlite3ExprCachePush(pParse);
124443    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
124444    addrNotFound = pLevel->addrBrk;
124445    for(j=0; j<nConstraint; j++){
124446      int iTarget = iReg+j+2;
124447      pTerm = pLoop->aLTerm[j];
124448      if( NEVER(pTerm==0) ) continue;
124449      if( pTerm->eOperator & WO_IN ){
124450        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
124451        addrNotFound = pLevel->addrNxt;
124452      }else{
124453        sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
124454      }
124455    }
124456    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
124457    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
124458    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
124459                      pLoop->u.vtab.idxStr,
124460                      pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
124461    VdbeCoverage(v);
124462    pLoop->u.vtab.needFree = 0;
124463    pLevel->p1 = iCur;
124464    pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
124465    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124466    iIn = pLevel->u.in.nIn;
124467    for(j=nConstraint-1; j>=0; j--){
124468      pTerm = pLoop->aLTerm[j];
124469      if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
124470        disableTerm(pLevel, pTerm);
124471      }else if( (pTerm->eOperator & WO_IN)!=0 ){
124472        Expr *pCompare;  /* The comparison operator */
124473        Expr *pRight;    /* RHS of the comparison */
124474        VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
124475
124476        /* Reload the constraint value into reg[iReg+j+2].  The same value
124477        ** was loaded into the same register prior to the OP_VFilter, but
124478        ** the xFilter implementation might have changed the datatype or
124479        ** encoding of the value in the register, so it *must* be reloaded. */
124480        assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
124481        if( !db->mallocFailed ){
124482          assert( iIn>0 );
124483          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
124484          assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
124485          assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
124486          assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
124487          testcase( pOp->opcode==OP_Rowid );
124488          sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
124489        }
124490
124491        /* Generate code that will continue to the next row if
124492        ** the IN constraint is not satisfied */
124493        pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
124494        assert( pCompare!=0 || db->mallocFailed );
124495        if( pCompare ){
124496          pCompare->pLeft = pTerm->pExpr->pLeft;
124497          pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
124498          if( pRight ){
124499            pRight->iTable = iReg+j+2;
124500            sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
124501          }
124502          pCompare->pLeft = 0;
124503          sqlite3ExprDelete(db, pCompare);
124504        }
124505      }
124506    }
124507    /* These registers need to be preserved in case there is an IN operator
124508    ** loop.  So we could deallocate the registers here (and potentially
124509    ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
124510    ** simpler and safer to simply not reuse the registers.
124511    **
124512    **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
124513    */
124514    sqlite3ExprCachePop(pParse);
124515  }else
124516#endif /* SQLITE_OMIT_VIRTUALTABLE */
124517
124518  if( (pLoop->wsFlags & WHERE_IPK)!=0
124519   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
124520  ){
124521    /* Case 2:  We can directly reference a single row using an
124522    **          equality comparison against the ROWID field.  Or
124523    **          we reference multiple rows using a "rowid IN (...)"
124524    **          construct.
124525    */
124526    assert( pLoop->u.btree.nEq==1 );
124527    pTerm = pLoop->aLTerm[0];
124528    assert( pTerm!=0 );
124529    assert( pTerm->pExpr!=0 );
124530    assert( omitTable==0 );
124531    testcase( pTerm->wtFlags & TERM_VIRTUAL );
124532    iReleaseReg = ++pParse->nMem;
124533    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
124534    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
124535    addrNxt = pLevel->addrNxt;
124536    sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
124537    VdbeCoverage(v);
124538    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
124539    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124540    VdbeComment((v, "pk"));
124541    pLevel->op = OP_Noop;
124542  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
124543         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
124544  ){
124545    /* Case 3:  We have an inequality comparison against the ROWID field.
124546    */
124547    int testOp = OP_Noop;
124548    int start;
124549    int memEndValue = 0;
124550    WhereTerm *pStart, *pEnd;
124551
124552    assert( omitTable==0 );
124553    j = 0;
124554    pStart = pEnd = 0;
124555    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
124556    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
124557    assert( pStart!=0 || pEnd!=0 );
124558    if( bRev ){
124559      pTerm = pStart;
124560      pStart = pEnd;
124561      pEnd = pTerm;
124562    }
124563    codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
124564    if( pStart ){
124565      Expr *pX;             /* The expression that defines the start bound */
124566      int r1, rTemp;        /* Registers for holding the start boundary */
124567
124568      /* The following constant maps TK_xx codes into corresponding
124569      ** seek opcodes.  It depends on a particular ordering of TK_xx
124570      */
124571      const u8 aMoveOp[] = {
124572           /* TK_GT */  OP_SeekGT,
124573           /* TK_LE */  OP_SeekLE,
124574           /* TK_LT */  OP_SeekLT,
124575           /* TK_GE */  OP_SeekGE
124576      };
124577      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
124578      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
124579      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
124580
124581      assert( (pStart->wtFlags & TERM_VNULL)==0 );
124582      testcase( pStart->wtFlags & TERM_VIRTUAL );
124583      pX = pStart->pExpr;
124584      assert( pX!=0 );
124585      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
124586      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
124587      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
124588      VdbeComment((v, "pk"));
124589      VdbeCoverageIf(v, pX->op==TK_GT);
124590      VdbeCoverageIf(v, pX->op==TK_LE);
124591      VdbeCoverageIf(v, pX->op==TK_LT);
124592      VdbeCoverageIf(v, pX->op==TK_GE);
124593      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
124594      sqlite3ReleaseTempReg(pParse, rTemp);
124595      disableTerm(pLevel, pStart);
124596    }else{
124597      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
124598      VdbeCoverageIf(v, bRev==0);
124599      VdbeCoverageIf(v, bRev!=0);
124600    }
124601    if( pEnd ){
124602      Expr *pX;
124603      pX = pEnd->pExpr;
124604      assert( pX!=0 );
124605      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
124606      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
124607      testcase( pEnd->wtFlags & TERM_VIRTUAL );
124608      memEndValue = ++pParse->nMem;
124609      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
124610      if( pX->op==TK_LT || pX->op==TK_GT ){
124611        testOp = bRev ? OP_Le : OP_Ge;
124612      }else{
124613        testOp = bRev ? OP_Lt : OP_Gt;
124614      }
124615      disableTerm(pLevel, pEnd);
124616    }
124617    start = sqlite3VdbeCurrentAddr(v);
124618    pLevel->op = bRev ? OP_Prev : OP_Next;
124619    pLevel->p1 = iCur;
124620    pLevel->p2 = start;
124621    assert( pLevel->p5==0 );
124622    if( testOp!=OP_Noop ){
124623      iRowidReg = ++pParse->nMem;
124624      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
124625      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124626      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
124627      VdbeCoverageIf(v, testOp==OP_Le);
124628      VdbeCoverageIf(v, testOp==OP_Lt);
124629      VdbeCoverageIf(v, testOp==OP_Ge);
124630      VdbeCoverageIf(v, testOp==OP_Gt);
124631      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
124632    }
124633  }else if( pLoop->wsFlags & WHERE_INDEXED ){
124634    /* Case 4: A scan using an index.
124635    **
124636    **         The WHERE clause may contain zero or more equality
124637    **         terms ("==" or "IN" operators) that refer to the N
124638    **         left-most columns of the index. It may also contain
124639    **         inequality constraints (>, <, >= or <=) on the indexed
124640    **         column that immediately follows the N equalities. Only
124641    **         the right-most column can be an inequality - the rest must
124642    **         use the "==" and "IN" operators. For example, if the
124643    **         index is on (x,y,z), then the following clauses are all
124644    **         optimized:
124645    **
124646    **            x=5
124647    **            x=5 AND y=10
124648    **            x=5 AND y<10
124649    **            x=5 AND y>5 AND y<10
124650    **            x=5 AND y=5 AND z<=10
124651    **
124652    **         The z<10 term of the following cannot be used, only
124653    **         the x=5 term:
124654    **
124655    **            x=5 AND z<10
124656    **
124657    **         N may be zero if there are inequality constraints.
124658    **         If there are no inequality constraints, then N is at
124659    **         least one.
124660    **
124661    **         This case is also used when there are no WHERE clause
124662    **         constraints but an index is selected anyway, in order
124663    **         to force the output order to conform to an ORDER BY.
124664    */
124665    static const u8 aStartOp[] = {
124666      0,
124667      0,
124668      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
124669      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
124670      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
124671      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
124672      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
124673      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
124674    };
124675    static const u8 aEndOp[] = {
124676      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
124677      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
124678      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
124679      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
124680    };
124681    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
124682    int regBase;                 /* Base register holding constraint values */
124683    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
124684    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
124685    int startEq;                 /* True if range start uses ==, >= or <= */
124686    int endEq;                   /* True if range end uses ==, >= or <= */
124687    int start_constraints;       /* Start of range is constrained */
124688    int nConstraint;             /* Number of constraint terms */
124689    Index *pIdx;                 /* The index we will be using */
124690    int iIdxCur;                 /* The VDBE cursor for the index */
124691    int nExtraReg = 0;           /* Number of extra registers needed */
124692    int op;                      /* Instruction opcode */
124693    char *zStartAff;             /* Affinity for start of range constraint */
124694    char cEndAff = 0;            /* Affinity for end of range constraint */
124695    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
124696    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
124697
124698    pIdx = pLoop->u.btree.pIndex;
124699    iIdxCur = pLevel->iIdxCur;
124700    assert( nEq>=pLoop->nSkip );
124701
124702    /* If this loop satisfies a sort order (pOrderBy) request that
124703    ** was passed to this function to implement a "SELECT min(x) ..."
124704    ** query, then the caller will only allow the loop to run for
124705    ** a single iteration. This means that the first row returned
124706    ** should not have a NULL value stored in 'x'. If column 'x' is
124707    ** the first one after the nEq equality constraints in the index,
124708    ** this requires some special handling.
124709    */
124710    assert( pWInfo->pOrderBy==0
124711         || pWInfo->pOrderBy->nExpr==1
124712         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
124713    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
124714     && pWInfo->nOBSat>0
124715     && (pIdx->nKeyCol>nEq)
124716    ){
124717      assert( pLoop->nSkip==0 );
124718      bSeekPastNull = 1;
124719      nExtraReg = 1;
124720    }
124721
124722    /* Find any inequality constraint terms for the start and end
124723    ** of the range.
124724    */
124725    j = nEq;
124726    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
124727      pRangeStart = pLoop->aLTerm[j++];
124728      nExtraReg = 1;
124729      /* Like optimization range constraints always occur in pairs */
124730      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
124731              (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
124732    }
124733    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
124734      pRangeEnd = pLoop->aLTerm[j++];
124735      nExtraReg = 1;
124736#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124737      if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
124738        assert( pRangeStart!=0 );                     /* LIKE opt constraints */
124739        assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
124740        pLevel->iLikeRepCntr = (u32)++pParse->nMem;
124741        sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
124742        VdbeComment((v, "LIKE loop counter"));
124743        pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
124744        /* iLikeRepCntr actually stores 2x the counter register number.  The
124745        ** bottom bit indicates whether the search order is ASC or DESC. */
124746        testcase( bRev );
124747        testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
124748        assert( (bRev & ~1)==0 );
124749        pLevel->iLikeRepCntr <<=1;
124750        pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
124751      }
124752#endif
124753      if( pRangeStart==0
124754       && (j = pIdx->aiColumn[nEq])>=0
124755       && pIdx->pTable->aCol[j].notNull==0
124756      ){
124757        bSeekPastNull = 1;
124758      }
124759    }
124760    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
124761
124762    /* If we are doing a reverse order scan on an ascending index, or
124763    ** a forward order scan on a descending index, interchange the
124764    ** start and end terms (pRangeStart and pRangeEnd).
124765    */
124766    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
124767     || (bRev && pIdx->nKeyCol==nEq)
124768    ){
124769      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
124770      SWAP(u8, bSeekPastNull, bStopAtNull);
124771    }
124772
124773    /* Generate code to evaluate all constraint terms using == or IN
124774    ** and store the values of those terms in an array of registers
124775    ** starting at regBase.
124776    */
124777    codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
124778    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
124779    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
124780    if( zStartAff ) cEndAff = zStartAff[nEq];
124781    addrNxt = pLevel->addrNxt;
124782
124783    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
124784    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
124785    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
124786    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
124787    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
124788    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
124789    start_constraints = pRangeStart || nEq>0;
124790
124791    /* Seek the index cursor to the start of the range. */
124792    nConstraint = nEq;
124793    if( pRangeStart ){
124794      Expr *pRight = pRangeStart->pExpr->pRight;
124795      sqlite3ExprCode(pParse, pRight, regBase+nEq);
124796      whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
124797      if( (pRangeStart->wtFlags & TERM_VNULL)==0
124798       && sqlite3ExprCanBeNull(pRight)
124799      ){
124800        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124801        VdbeCoverage(v);
124802      }
124803      if( zStartAff ){
124804        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
124805          /* Since the comparison is to be performed with no conversions
124806          ** applied to the operands, set the affinity to apply to pRight to
124807          ** SQLITE_AFF_BLOB.  */
124808          zStartAff[nEq] = SQLITE_AFF_BLOB;
124809        }
124810        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
124811          zStartAff[nEq] = SQLITE_AFF_BLOB;
124812        }
124813      }
124814      nConstraint++;
124815      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
124816      bSeekPastNull = 0;
124817    }else if( bSeekPastNull ){
124818      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124819      nConstraint++;
124820      startEq = 0;
124821      start_constraints = 1;
124822    }
124823    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
124824    if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
124825      /* The skip-scan logic inside the call to codeAllEqualityConstraints()
124826      ** above has already left the cursor sitting on the correct row,
124827      ** so no further seeking is needed */
124828    }else{
124829      op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
124830      assert( op!=0 );
124831      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124832      VdbeCoverage(v);
124833      VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
124834      VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
124835      VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
124836      VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
124837      VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
124838      VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
124839    }
124840
124841    /* Load the value for the inequality constraint at the end of the
124842    ** range (if any).
124843    */
124844    nConstraint = nEq;
124845    if( pRangeEnd ){
124846      Expr *pRight = pRangeEnd->pExpr->pRight;
124847      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
124848      sqlite3ExprCode(pParse, pRight, regBase+nEq);
124849      whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
124850      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
124851       && sqlite3ExprCanBeNull(pRight)
124852      ){
124853        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124854        VdbeCoverage(v);
124855      }
124856      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
124857       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
124858      ){
124859        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
124860      }
124861      nConstraint++;
124862      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
124863    }else if( bStopAtNull ){
124864      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124865      endEq = 0;
124866      nConstraint++;
124867    }
124868    sqlite3DbFree(db, zStartAff);
124869
124870    /* Top of the loop body */
124871    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124872
124873    /* Check if the index cursor is past the end of the range. */
124874    if( nConstraint ){
124875      op = aEndOp[bRev*2 + endEq];
124876      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124877      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
124878      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
124879      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
124880      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
124881    }
124882
124883    /* Seek the table cursor, if required */
124884    disableTerm(pLevel, pRangeStart);
124885    disableTerm(pLevel, pRangeEnd);
124886    if( omitTable ){
124887      /* pIdx is a covering index.  No need to access the main table. */
124888    }else if( HasRowid(pIdx->pTable) ){
124889      if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
124890        iRowidReg = ++pParse->nMem;
124891        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
124892        sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124893        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
124894        VdbeCoverage(v);
124895      }else{
124896        codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
124897      }
124898    }else if( iCur!=iIdxCur ){
124899      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
124900      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
124901      for(j=0; j<pPk->nKeyCol; j++){
124902        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
124903        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
124904      }
124905      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
124906                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
124907    }
124908
124909    /* Record the instruction used to terminate the loop. Disable
124910    ** WHERE clause terms made redundant by the index range scan.
124911    */
124912    if( pLoop->wsFlags & WHERE_ONEROW ){
124913      pLevel->op = OP_Noop;
124914    }else if( bRev ){
124915      pLevel->op = OP_Prev;
124916    }else{
124917      pLevel->op = OP_Next;
124918    }
124919    pLevel->p1 = iIdxCur;
124920    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
124921    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
124922      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
124923    }else{
124924      assert( pLevel->p5==0 );
124925    }
124926  }else
124927
124928#ifndef SQLITE_OMIT_OR_OPTIMIZATION
124929  if( pLoop->wsFlags & WHERE_MULTI_OR ){
124930    /* Case 5:  Two or more separately indexed terms connected by OR
124931    **
124932    ** Example:
124933    **
124934    **   CREATE TABLE t1(a,b,c,d);
124935    **   CREATE INDEX i1 ON t1(a);
124936    **   CREATE INDEX i2 ON t1(b);
124937    **   CREATE INDEX i3 ON t1(c);
124938    **
124939    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
124940    **
124941    ** In the example, there are three indexed terms connected by OR.
124942    ** The top of the loop looks like this:
124943    **
124944    **          Null       1                # Zero the rowset in reg 1
124945    **
124946    ** Then, for each indexed term, the following. The arguments to
124947    ** RowSetTest are such that the rowid of the current row is inserted
124948    ** into the RowSet. If it is already present, control skips the
124949    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
124950    **
124951    **        sqlite3WhereBegin(<term>)
124952    **          RowSetTest                  # Insert rowid into rowset
124953    **          Gosub      2 A
124954    **        sqlite3WhereEnd()
124955    **
124956    ** Following the above, code to terminate the loop. Label A, the target
124957    ** of the Gosub above, jumps to the instruction right after the Goto.
124958    **
124959    **          Null       1                # Zero the rowset in reg 1
124960    **          Goto       B                # The loop is finished.
124961    **
124962    **       A: <loop body>                 # Return data, whatever.
124963    **
124964    **          Return     2                # Jump back to the Gosub
124965    **
124966    **       B: <after the loop>
124967    **
124968    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
124969    ** use an ephemeral index instead of a RowSet to record the primary
124970    ** keys of the rows we have already seen.
124971    **
124972    */
124973    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
124974    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
124975    Index *pCov = 0;             /* Potential covering index (or NULL) */
124976    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
124977
124978    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
124979    int regRowset = 0;                        /* Register for RowSet object */
124980    int regRowid = 0;                         /* Register holding rowid */
124981    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
124982    int iRetInit;                             /* Address of regReturn init */
124983    int untestedTerms = 0;             /* Some terms not completely tested */
124984    int ii;                            /* Loop counter */
124985    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
124986    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
124987    Table *pTab = pTabItem->pTab;
124988
124989    pTerm = pLoop->aLTerm[0];
124990    assert( pTerm!=0 );
124991    assert( pTerm->eOperator & WO_OR );
124992    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
124993    pOrWc = &pTerm->u.pOrInfo->wc;
124994    pLevel->op = OP_Return;
124995    pLevel->p1 = regReturn;
124996
124997    /* Set up a new SrcList in pOrTab containing the table being scanned
124998    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
124999    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
125000    */
125001    if( pWInfo->nLevel>1 ){
125002      int nNotReady;                 /* The number of notReady tables */
125003      struct SrcList_item *origSrc;     /* Original list of tables */
125004      nNotReady = pWInfo->nLevel - iLevel - 1;
125005      pOrTab = sqlite3StackAllocRaw(db,
125006                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
125007      if( pOrTab==0 ) return notReady;
125008      pOrTab->nAlloc = (u8)(nNotReady + 1);
125009      pOrTab->nSrc = pOrTab->nAlloc;
125010      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
125011      origSrc = pWInfo->pTabList->a;
125012      for(k=1; k<=nNotReady; k++){
125013        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
125014      }
125015    }else{
125016      pOrTab = pWInfo->pTabList;
125017    }
125018
125019    /* Initialize the rowset register to contain NULL. An SQL NULL is
125020    ** equivalent to an empty rowset.  Or, create an ephemeral index
125021    ** capable of holding primary keys in the case of a WITHOUT ROWID.
125022    **
125023    ** Also initialize regReturn to contain the address of the instruction
125024    ** immediately following the OP_Return at the bottom of the loop. This
125025    ** is required in a few obscure LEFT JOIN cases where control jumps
125026    ** over the top of the loop into the body of it. In this case the
125027    ** correct response for the end-of-loop code (the OP_Return) is to
125028    ** fall through to the next instruction, just as an OP_Next does if
125029    ** called on an uninitialized cursor.
125030    */
125031    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
125032      if( HasRowid(pTab) ){
125033        regRowset = ++pParse->nMem;
125034        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
125035      }else{
125036        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125037        regRowset = pParse->nTab++;
125038        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
125039        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
125040      }
125041      regRowid = ++pParse->nMem;
125042    }
125043    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
125044
125045    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
125046    ** Then for every term xN, evaluate as the subexpression: xN AND z
125047    ** That way, terms in y that are factored into the disjunction will
125048    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
125049    **
125050    ** Actually, each subexpression is converted to "xN AND w" where w is
125051    ** the "interesting" terms of z - terms that did not originate in the
125052    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
125053    ** indices.
125054    **
125055    ** This optimization also only applies if the (x1 OR x2 OR ...) term
125056    ** is not contained in the ON clause of a LEFT JOIN.
125057    ** See ticket http://www.sqlite.org/src/info/f2369304e4
125058    */
125059    if( pWC->nTerm>1 ){
125060      int iTerm;
125061      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
125062        Expr *pExpr = pWC->a[iTerm].pExpr;
125063        if( &pWC->a[iTerm] == pTerm ) continue;
125064        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
125065        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
125066        testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
125067        if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
125068        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
125069        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
125070        pExpr = sqlite3ExprDup(db, pExpr, 0);
125071        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
125072      }
125073      if( pAndExpr ){
125074        pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
125075      }
125076    }
125077
125078    /* Run a separate WHERE clause for each term of the OR clause.  After
125079    ** eliminating duplicates from other WHERE clauses, the action for each
125080    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
125081    */
125082    wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
125083    for(ii=0; ii<pOrWc->nTerm; ii++){
125084      WhereTerm *pOrTerm = &pOrWc->a[ii];
125085      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
125086        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
125087        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
125088        int jmp1 = 0;                   /* Address of jump operation */
125089        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
125090          pAndExpr->pLeft = pOrExpr;
125091          pOrExpr = pAndExpr;
125092        }
125093        /* Loop through table entries that match term pOrTerm. */
125094        WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
125095        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
125096                                      wctrlFlags, iCovCur);
125097        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
125098        if( pSubWInfo ){
125099          WhereLoop *pSubLoop;
125100          int addrExplain = sqlite3WhereExplainOneScan(
125101              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
125102          );
125103          sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
125104
125105          /* This is the sub-WHERE clause body.  First skip over
125106          ** duplicate rows from prior sub-WHERE clauses, and record the
125107          ** rowid (or PRIMARY KEY) for the current row so that the same
125108          ** row will be skipped in subsequent sub-WHERE clauses.
125109          */
125110          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
125111            int r;
125112            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
125113            if( HasRowid(pTab) ){
125114              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
125115              jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
125116                                           r,iSet);
125117              VdbeCoverage(v);
125118            }else{
125119              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125120              int nPk = pPk->nKeyCol;
125121              int iPk;
125122
125123              /* Read the PK into an array of temp registers. */
125124              r = sqlite3GetTempRange(pParse, nPk);
125125              for(iPk=0; iPk<nPk; iPk++){
125126                int iCol = pPk->aiColumn[iPk];
125127                sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
125128              }
125129
125130              /* Check if the temp table already contains this key. If so,
125131              ** the row has already been included in the result set and
125132              ** can be ignored (by jumping past the Gosub below). Otherwise,
125133              ** insert the key into the temp table and proceed with processing
125134              ** the row.
125135              **
125136              ** Use some of the same optimizations as OP_RowSetTest: If iSet
125137              ** is zero, assume that the key cannot already be present in
125138              ** the temp table. And if iSet is -1, assume that there is no
125139              ** need to insert the key into the temp table, as it will never
125140              ** be tested for.  */
125141              if( iSet ){
125142                jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
125143                VdbeCoverage(v);
125144              }
125145              if( iSet>=0 ){
125146                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
125147                sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
125148                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
125149              }
125150
125151              /* Release the array of temp registers */
125152              sqlite3ReleaseTempRange(pParse, r, nPk);
125153            }
125154          }
125155
125156          /* Invoke the main loop body as a subroutine */
125157          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
125158
125159          /* Jump here (skipping the main loop body subroutine) if the
125160          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
125161          if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
125162
125163          /* The pSubWInfo->untestedTerms flag means that this OR term
125164          ** contained one or more AND term from a notReady table.  The
125165          ** terms from the notReady table could not be tested and will
125166          ** need to be tested later.
125167          */
125168          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
125169
125170          /* If all of the OR-connected terms are optimized using the same
125171          ** index, and the index is opened using the same cursor number
125172          ** by each call to sqlite3WhereBegin() made by this loop, it may
125173          ** be possible to use that index as a covering index.
125174          **
125175          ** If the call to sqlite3WhereBegin() above resulted in a scan that
125176          ** uses an index, and this is either the first OR-connected term
125177          ** processed or the index is the same as that used by all previous
125178          ** terms, set pCov to the candidate covering index. Otherwise, set
125179          ** pCov to NULL to indicate that no candidate covering index will
125180          ** be available.
125181          */
125182          pSubLoop = pSubWInfo->a[0].pWLoop;
125183          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
125184          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
125185           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
125186           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
125187          ){
125188            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
125189            pCov = pSubLoop->u.btree.pIndex;
125190          }else{
125191            pCov = 0;
125192          }
125193
125194          /* Finish the loop through table entries that match term pOrTerm. */
125195          sqlite3WhereEnd(pSubWInfo);
125196        }
125197      }
125198    }
125199    pLevel->u.pCovidx = pCov;
125200    if( pCov ) pLevel->iIdxCur = iCovCur;
125201    if( pAndExpr ){
125202      pAndExpr->pLeft = 0;
125203      sqlite3ExprDelete(db, pAndExpr);
125204    }
125205    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
125206    sqlite3VdbeGoto(v, pLevel->addrBrk);
125207    sqlite3VdbeResolveLabel(v, iLoopBody);
125208
125209    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
125210    if( !untestedTerms ) disableTerm(pLevel, pTerm);
125211  }else
125212#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
125213
125214  {
125215    /* Case 6:  There is no usable index.  We must do a complete
125216    **          scan of the entire table.
125217    */
125218    static const u8 aStep[] = { OP_Next, OP_Prev };
125219    static const u8 aStart[] = { OP_Rewind, OP_Last };
125220    assert( bRev==0 || bRev==1 );
125221    if( pTabItem->fg.isRecursive ){
125222      /* Tables marked isRecursive have only a single row that is stored in
125223      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
125224      pLevel->op = OP_Noop;
125225    }else{
125226      codeCursorHint(pTabItem, pWInfo, pLevel, 0);
125227      pLevel->op = aStep[bRev];
125228      pLevel->p1 = iCur;
125229      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
125230      VdbeCoverageIf(v, bRev==0);
125231      VdbeCoverageIf(v, bRev!=0);
125232      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
125233    }
125234  }
125235
125236#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
125237  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
125238#endif
125239
125240  /* Insert code to test every subexpression that can be completely
125241  ** computed using the current set of tables.
125242  */
125243  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
125244    Expr *pE;
125245    int skipLikeAddr = 0;
125246    testcase( pTerm->wtFlags & TERM_VIRTUAL );
125247    testcase( pTerm->wtFlags & TERM_CODED );
125248    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125249    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
125250      testcase( pWInfo->untestedTerms==0
125251               && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
125252      pWInfo->untestedTerms = 1;
125253      continue;
125254    }
125255    pE = pTerm->pExpr;
125256    assert( pE!=0 );
125257    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
125258      continue;
125259    }
125260    if( pTerm->wtFlags & TERM_LIKECOND ){
125261      /* If the TERM_LIKECOND flag is set, that means that the range search
125262      ** is sufficient to guarantee that the LIKE operator is true, so we
125263      ** can skip the call to the like(A,B) function.  But this only works
125264      ** for strings.  So do not skip the call to the function on the pass
125265      ** that compares BLOBs. */
125266#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
125267      continue;
125268#else
125269      u32 x = pLevel->iLikeRepCntr;
125270      assert( x>0 );
125271      skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
125272      VdbeCoverage(v);
125273#endif
125274    }
125275    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
125276    if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
125277    pTerm->wtFlags |= TERM_CODED;
125278  }
125279
125280  /* Insert code to test for implied constraints based on transitivity
125281  ** of the "==" operator.
125282  **
125283  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
125284  ** and we are coding the t1 loop and the t2 loop has not yet coded,
125285  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
125286  ** the implied "t1.a=123" constraint.
125287  */
125288  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
125289    Expr *pE, *pEAlt;
125290    WhereTerm *pAlt;
125291    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125292    if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
125293    if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
125294    if( pTerm->leftCursor!=iCur ) continue;
125295    if( pLevel->iLeftJoin ) continue;
125296    pE = pTerm->pExpr;
125297    assert( !ExprHasProperty(pE, EP_FromJoin) );
125298    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
125299    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
125300                    WO_EQ|WO_IN|WO_IS, 0);
125301    if( pAlt==0 ) continue;
125302    if( pAlt->wtFlags & (TERM_CODED) ) continue;
125303    testcase( pAlt->eOperator & WO_EQ );
125304    testcase( pAlt->eOperator & WO_IS );
125305    testcase( pAlt->eOperator & WO_IN );
125306    VdbeModuleComment((v, "begin transitive constraint"));
125307    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
125308    if( pEAlt ){
125309      *pEAlt = *pAlt->pExpr;
125310      pEAlt->pLeft = pE->pLeft;
125311      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
125312      sqlite3StackFree(db, pEAlt);
125313    }
125314  }
125315
125316  /* For a LEFT OUTER JOIN, generate code that will record the fact that
125317  ** at least one row of the right table has matched the left table.
125318  */
125319  if( pLevel->iLeftJoin ){
125320    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
125321    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
125322    VdbeComment((v, "record LEFT JOIN hit"));
125323    sqlite3ExprCacheClear(pParse);
125324    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
125325      testcase( pTerm->wtFlags & TERM_VIRTUAL );
125326      testcase( pTerm->wtFlags & TERM_CODED );
125327      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125328      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
125329        assert( pWInfo->untestedTerms );
125330        continue;
125331      }
125332      assert( pTerm->pExpr );
125333      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
125334      pTerm->wtFlags |= TERM_CODED;
125335    }
125336  }
125337
125338  return pLevel->notReady;
125339}
125340
125341/************** End of wherecode.c *******************************************/
125342/************** Begin file whereexpr.c ***************************************/
125343/*
125344** 2015-06-08
125345**
125346** The author disclaims copyright to this source code.  In place of
125347** a legal notice, here is a blessing:
125348**
125349**    May you do good and not evil.
125350**    May you find forgiveness for yourself and forgive others.
125351**    May you share freely, never taking more than you give.
125352**
125353*************************************************************************
125354** This module contains C code that generates VDBE code used to process
125355** the WHERE clause of SQL statements.
125356**
125357** This file was originally part of where.c but was split out to improve
125358** readability and editabiliity.  This file contains utility routines for
125359** analyzing Expr objects in the WHERE clause.
125360*/
125361/* #include "sqliteInt.h" */
125362/* #include "whereInt.h" */
125363
125364/* Forward declarations */
125365static void exprAnalyze(SrcList*, WhereClause*, int);
125366
125367/*
125368** Deallocate all memory associated with a WhereOrInfo object.
125369*/
125370static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
125371  sqlite3WhereClauseClear(&p->wc);
125372  sqlite3DbFree(db, p);
125373}
125374
125375/*
125376** Deallocate all memory associated with a WhereAndInfo object.
125377*/
125378static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
125379  sqlite3WhereClauseClear(&p->wc);
125380  sqlite3DbFree(db, p);
125381}
125382
125383/*
125384** Add a single new WhereTerm entry to the WhereClause object pWC.
125385** The new WhereTerm object is constructed from Expr p and with wtFlags.
125386** The index in pWC->a[] of the new WhereTerm is returned on success.
125387** 0 is returned if the new WhereTerm could not be added due to a memory
125388** allocation error.  The memory allocation failure will be recorded in
125389** the db->mallocFailed flag so that higher-level functions can detect it.
125390**
125391** This routine will increase the size of the pWC->a[] array as necessary.
125392**
125393** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
125394** for freeing the expression p is assumed by the WhereClause object pWC.
125395** This is true even if this routine fails to allocate a new WhereTerm.
125396**
125397** WARNING:  This routine might reallocate the space used to store
125398** WhereTerms.  All pointers to WhereTerms should be invalidated after
125399** calling this routine.  Such pointers may be reinitialized by referencing
125400** the pWC->a[] array.
125401*/
125402static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
125403  WhereTerm *pTerm;
125404  int idx;
125405  testcase( wtFlags & TERM_VIRTUAL );
125406  if( pWC->nTerm>=pWC->nSlot ){
125407    WhereTerm *pOld = pWC->a;
125408    sqlite3 *db = pWC->pWInfo->pParse->db;
125409    pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
125410    if( pWC->a==0 ){
125411      if( wtFlags & TERM_DYNAMIC ){
125412        sqlite3ExprDelete(db, p);
125413      }
125414      pWC->a = pOld;
125415      return 0;
125416    }
125417    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
125418    if( pOld!=pWC->aStatic ){
125419      sqlite3DbFree(db, pOld);
125420    }
125421    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
125422    memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
125423  }
125424  pTerm = &pWC->a[idx = pWC->nTerm++];
125425  if( p && ExprHasProperty(p, EP_Unlikely) ){
125426    pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
125427  }else{
125428    pTerm->truthProb = 1;
125429  }
125430  pTerm->pExpr = sqlite3ExprSkipCollate(p);
125431  pTerm->wtFlags = wtFlags;
125432  pTerm->pWC = pWC;
125433  pTerm->iParent = -1;
125434  return idx;
125435}
125436
125437/*
125438** Return TRUE if the given operator is one of the operators that is
125439** allowed for an indexable WHERE clause term.  The allowed operators are
125440** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
125441*/
125442static int allowedOp(int op){
125443  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
125444  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
125445  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
125446  assert( TK_GE==TK_EQ+4 );
125447  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
125448}
125449
125450/*
125451** Commute a comparison operator.  Expressions of the form "X op Y"
125452** are converted into "Y op X".
125453**
125454** If left/right precedence rules come into play when determining the
125455** collating sequence, then COLLATE operators are adjusted to ensure
125456** that the collating sequence does not change.  For example:
125457** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
125458** the left hand side of a comparison overrides any collation sequence
125459** attached to the right. For the same reason the EP_Collate flag
125460** is not commuted.
125461*/
125462static void exprCommute(Parse *pParse, Expr *pExpr){
125463  u16 expRight = (pExpr->pRight->flags & EP_Collate);
125464  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
125465  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
125466  if( expRight==expLeft ){
125467    /* Either X and Y both have COLLATE operator or neither do */
125468    if( expRight ){
125469      /* Both X and Y have COLLATE operators.  Make sure X is always
125470      ** used by clearing the EP_Collate flag from Y. */
125471      pExpr->pRight->flags &= ~EP_Collate;
125472    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
125473      /* Neither X nor Y have COLLATE operators, but X has a non-default
125474      ** collating sequence.  So add the EP_Collate marker on X to cause
125475      ** it to be searched first. */
125476      pExpr->pLeft->flags |= EP_Collate;
125477    }
125478  }
125479  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
125480  if( pExpr->op>=TK_GT ){
125481    assert( TK_LT==TK_GT+2 );
125482    assert( TK_GE==TK_LE+2 );
125483    assert( TK_GT>TK_EQ );
125484    assert( TK_GT<TK_LE );
125485    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
125486    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
125487  }
125488}
125489
125490/*
125491** Translate from TK_xx operator to WO_xx bitmask.
125492*/
125493static u16 operatorMask(int op){
125494  u16 c;
125495  assert( allowedOp(op) );
125496  if( op==TK_IN ){
125497    c = WO_IN;
125498  }else if( op==TK_ISNULL ){
125499    c = WO_ISNULL;
125500  }else if( op==TK_IS ){
125501    c = WO_IS;
125502  }else{
125503    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
125504    c = (u16)(WO_EQ<<(op-TK_EQ));
125505  }
125506  assert( op!=TK_ISNULL || c==WO_ISNULL );
125507  assert( op!=TK_IN || c==WO_IN );
125508  assert( op!=TK_EQ || c==WO_EQ );
125509  assert( op!=TK_LT || c==WO_LT );
125510  assert( op!=TK_LE || c==WO_LE );
125511  assert( op!=TK_GT || c==WO_GT );
125512  assert( op!=TK_GE || c==WO_GE );
125513  assert( op!=TK_IS || c==WO_IS );
125514  return c;
125515}
125516
125517
125518#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
125519/*
125520** Check to see if the given expression is a LIKE or GLOB operator that
125521** can be optimized using inequality constraints.  Return TRUE if it is
125522** so and false if not.
125523**
125524** In order for the operator to be optimizible, the RHS must be a string
125525** literal that does not begin with a wildcard.  The LHS must be a column
125526** that may only be NULL, a string, or a BLOB, never a number. (This means
125527** that virtual tables cannot participate in the LIKE optimization.)  The
125528** collating sequence for the column on the LHS must be appropriate for
125529** the operator.
125530*/
125531static int isLikeOrGlob(
125532  Parse *pParse,    /* Parsing and code generating context */
125533  Expr *pExpr,      /* Test this expression */
125534  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
125535  int *pisComplete, /* True if the only wildcard is % in the last character */
125536  int *pnoCase      /* True if uppercase is equivalent to lowercase */
125537){
125538  const char *z = 0;         /* String on RHS of LIKE operator */
125539  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
125540  ExprList *pList;           /* List of operands to the LIKE operator */
125541  int c;                     /* One character in z[] */
125542  int cnt;                   /* Number of non-wildcard prefix characters */
125543  char wc[3];                /* Wildcard characters */
125544  sqlite3 *db = pParse->db;  /* Database connection */
125545  sqlite3_value *pVal = 0;
125546  int op;                    /* Opcode of pRight */
125547  int rc;                    /* Result code to return */
125548
125549  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
125550    return 0;
125551  }
125552#ifdef SQLITE_EBCDIC
125553  if( *pnoCase ) return 0;
125554#endif
125555  pList = pExpr->x.pList;
125556  pLeft = pList->a[1].pExpr;
125557  if( pLeft->op!=TK_COLUMN
125558   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
125559   || IsVirtual(pLeft->pTab)  /* Value might be numeric */
125560  ){
125561    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
125562    ** be the name of an indexed column with TEXT affinity. */
125563    return 0;
125564  }
125565  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
125566
125567  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
125568  op = pRight->op;
125569  if( op==TK_VARIABLE ){
125570    Vdbe *pReprepare = pParse->pReprepare;
125571    int iCol = pRight->iColumn;
125572    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
125573    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
125574      z = (char *)sqlite3_value_text(pVal);
125575    }
125576    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
125577    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
125578  }else if( op==TK_STRING ){
125579    z = pRight->u.zToken;
125580  }
125581  if( z ){
125582    cnt = 0;
125583    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
125584      cnt++;
125585    }
125586    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
125587      Expr *pPrefix;
125588      *pisComplete = c==wc[0] && z[cnt+1]==0;
125589      pPrefix = sqlite3Expr(db, TK_STRING, z);
125590      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
125591      *ppPrefix = pPrefix;
125592      if( op==TK_VARIABLE ){
125593        Vdbe *v = pParse->pVdbe;
125594        sqlite3VdbeSetVarmask(v, pRight->iColumn);
125595        if( *pisComplete && pRight->u.zToken[1] ){
125596          /* If the rhs of the LIKE expression is a variable, and the current
125597          ** value of the variable means there is no need to invoke the LIKE
125598          ** function, then no OP_Variable will be added to the program.
125599          ** This causes problems for the sqlite3_bind_parameter_name()
125600          ** API. To work around them, add a dummy OP_Variable here.
125601          */
125602          int r1 = sqlite3GetTempReg(pParse);
125603          sqlite3ExprCodeTarget(pParse, pRight, r1);
125604          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
125605          sqlite3ReleaseTempReg(pParse, r1);
125606        }
125607      }
125608    }else{
125609      z = 0;
125610    }
125611  }
125612
125613  rc = (z!=0);
125614  sqlite3ValueFree(pVal);
125615  return rc;
125616}
125617#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
125618
125619
125620#ifndef SQLITE_OMIT_VIRTUALTABLE
125621/*
125622** Check to see if the given expression is of the form
125623**
125624**         column OP expr
125625**
125626** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
125627** column of a virtual table.
125628**
125629** If it is then return TRUE.  If not, return FALSE.
125630*/
125631static int isMatchOfColumn(
125632  Expr *pExpr,                    /* Test this expression */
125633  unsigned char *peOp2            /* OUT: 0 for MATCH, or else an op2 value */
125634){
125635  struct Op2 {
125636    const char *zOp;
125637    unsigned char eOp2;
125638  } aOp[] = {
125639    { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
125640    { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
125641    { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
125642    { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
125643  };
125644  ExprList *pList;
125645  Expr *pCol;                     /* Column reference */
125646  int i;
125647
125648  if( pExpr->op!=TK_FUNCTION ){
125649    return 0;
125650  }
125651  pList = pExpr->x.pList;
125652  if( pList==0 || pList->nExpr!=2 ){
125653    return 0;
125654  }
125655  pCol = pList->a[1].pExpr;
125656  if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
125657    return 0;
125658  }
125659  for(i=0; i<ArraySize(aOp); i++){
125660    if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
125661      *peOp2 = aOp[i].eOp2;
125662      return 1;
125663    }
125664  }
125665  return 0;
125666}
125667#endif /* SQLITE_OMIT_VIRTUALTABLE */
125668
125669/*
125670** If the pBase expression originated in the ON or USING clause of
125671** a join, then transfer the appropriate markings over to derived.
125672*/
125673static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
125674  if( pDerived ){
125675    pDerived->flags |= pBase->flags & EP_FromJoin;
125676    pDerived->iRightJoinTable = pBase->iRightJoinTable;
125677  }
125678}
125679
125680/*
125681** Mark term iChild as being a child of term iParent
125682*/
125683static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
125684  pWC->a[iChild].iParent = iParent;
125685  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
125686  pWC->a[iParent].nChild++;
125687}
125688
125689/*
125690** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
125691** a conjunction, then return just pTerm when N==0.  If N is exceeds
125692** the number of available subterms, return NULL.
125693*/
125694static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
125695  if( pTerm->eOperator!=WO_AND ){
125696    return N==0 ? pTerm : 0;
125697  }
125698  if( N<pTerm->u.pAndInfo->wc.nTerm ){
125699    return &pTerm->u.pAndInfo->wc.a[N];
125700  }
125701  return 0;
125702}
125703
125704/*
125705** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
125706** two subterms are in disjunction - they are OR-ed together.
125707**
125708** If these two terms are both of the form:  "A op B" with the same
125709** A and B values but different operators and if the operators are
125710** compatible (if one is = and the other is <, for example) then
125711** add a new virtual AND term to pWC that is the combination of the
125712** two.
125713**
125714** Some examples:
125715**
125716**    x<y OR x=y    -->     x<=y
125717**    x=y OR x=y    -->     x=y
125718**    x<=y OR x<y   -->     x<=y
125719**
125720** The following is NOT generated:
125721**
125722**    x<y OR x>y    -->     x!=y
125723*/
125724static void whereCombineDisjuncts(
125725  SrcList *pSrc,         /* the FROM clause */
125726  WhereClause *pWC,      /* The complete WHERE clause */
125727  WhereTerm *pOne,       /* First disjunct */
125728  WhereTerm *pTwo        /* Second disjunct */
125729){
125730  u16 eOp = pOne->eOperator | pTwo->eOperator;
125731  sqlite3 *db;           /* Database connection (for malloc) */
125732  Expr *pNew;            /* New virtual expression */
125733  int op;                /* Operator for the combined expression */
125734  int idxNew;            /* Index in pWC of the next virtual term */
125735
125736  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
125737  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
125738  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
125739   && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
125740  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
125741  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
125742  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
125743  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
125744  /* If we reach this point, it means the two subterms can be combined */
125745  if( (eOp & (eOp-1))!=0 ){
125746    if( eOp & (WO_LT|WO_LE) ){
125747      eOp = WO_LE;
125748    }else{
125749      assert( eOp & (WO_GT|WO_GE) );
125750      eOp = WO_GE;
125751    }
125752  }
125753  db = pWC->pWInfo->pParse->db;
125754  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
125755  if( pNew==0 ) return;
125756  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
125757  pNew->op = op;
125758  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
125759  exprAnalyze(pSrc, pWC, idxNew);
125760}
125761
125762#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
125763/*
125764** Analyze a term that consists of two or more OR-connected
125765** subterms.  So in:
125766**
125767**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
125768**                          ^^^^^^^^^^^^^^^^^^^^
125769**
125770** This routine analyzes terms such as the middle term in the above example.
125771** A WhereOrTerm object is computed and attached to the term under
125772** analysis, regardless of the outcome of the analysis.  Hence:
125773**
125774**     WhereTerm.wtFlags   |=  TERM_ORINFO
125775**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
125776**
125777** The term being analyzed must have two or more of OR-connected subterms.
125778** A single subterm might be a set of AND-connected sub-subterms.
125779** Examples of terms under analysis:
125780**
125781**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
125782**     (B)     x=expr1 OR expr2=x OR x=expr3
125783**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
125784**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
125785**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
125786**     (F)     x>A OR (x=A AND y>=B)
125787**
125788** CASE 1:
125789**
125790** If all subterms are of the form T.C=expr for some single column of C and
125791** a single table T (as shown in example B above) then create a new virtual
125792** term that is an equivalent IN expression.  In other words, if the term
125793** being analyzed is:
125794**
125795**      x = expr1  OR  expr2 = x  OR  x = expr3
125796**
125797** then create a new virtual term like this:
125798**
125799**      x IN (expr1,expr2,expr3)
125800**
125801** CASE 2:
125802**
125803** If there are exactly two disjuncts and one side has x>A and the other side
125804** has x=A (for the same x and A) then add a new virtual conjunct term to the
125805** WHERE clause of the form "x>=A".  Example:
125806**
125807**      x>A OR (x=A AND y>B)    adds:    x>=A
125808**
125809** The added conjunct can sometimes be helpful in query planning.
125810**
125811** CASE 3:
125812**
125813** If all subterms are indexable by a single table T, then set
125814**
125815**     WhereTerm.eOperator              =  WO_OR
125816**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
125817**
125818** A subterm is "indexable" if it is of the form
125819** "T.C <op> <expr>" where C is any column of table T and
125820** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
125821** A subterm is also indexable if it is an AND of two or more
125822** subsubterms at least one of which is indexable.  Indexable AND
125823** subterms have their eOperator set to WO_AND and they have
125824** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
125825**
125826** From another point of view, "indexable" means that the subterm could
125827** potentially be used with an index if an appropriate index exists.
125828** This analysis does not consider whether or not the index exists; that
125829** is decided elsewhere.  This analysis only looks at whether subterms
125830** appropriate for indexing exist.
125831**
125832** All examples A through E above satisfy case 3.  But if a term
125833** also satisfies case 1 (such as B) we know that the optimizer will
125834** always prefer case 1, so in that case we pretend that case 3 is not
125835** satisfied.
125836**
125837** It might be the case that multiple tables are indexable.  For example,
125838** (E) above is indexable on tables P, Q, and R.
125839**
125840** Terms that satisfy case 3 are candidates for lookup by using
125841** separate indices to find rowids for each subterm and composing
125842** the union of all rowids using a RowSet object.  This is similar
125843** to "bitmap indices" in other database engines.
125844**
125845** OTHERWISE:
125846**
125847** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
125848** zero.  This term is not useful for search.
125849*/
125850static void exprAnalyzeOrTerm(
125851  SrcList *pSrc,            /* the FROM clause */
125852  WhereClause *pWC,         /* the complete WHERE clause */
125853  int idxTerm               /* Index of the OR-term to be analyzed */
125854){
125855  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
125856  Parse *pParse = pWInfo->pParse;         /* Parser context */
125857  sqlite3 *db = pParse->db;               /* Database connection */
125858  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
125859  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
125860  int i;                                  /* Loop counters */
125861  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
125862  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
125863  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
125864  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
125865  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
125866
125867  /*
125868  ** Break the OR clause into its separate subterms.  The subterms are
125869  ** stored in a WhereClause structure containing within the WhereOrInfo
125870  ** object that is attached to the original OR clause term.
125871  */
125872  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
125873  assert( pExpr->op==TK_OR );
125874  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
125875  if( pOrInfo==0 ) return;
125876  pTerm->wtFlags |= TERM_ORINFO;
125877  pOrWc = &pOrInfo->wc;
125878  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
125879  sqlite3WhereClauseInit(pOrWc, pWInfo);
125880  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
125881  sqlite3WhereExprAnalyze(pSrc, pOrWc);
125882  if( db->mallocFailed ) return;
125883  assert( pOrWc->nTerm>=2 );
125884
125885  /*
125886  ** Compute the set of tables that might satisfy cases 1 or 3.
125887  */
125888  indexable = ~(Bitmask)0;
125889  chngToIN = ~(Bitmask)0;
125890  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
125891    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
125892      WhereAndInfo *pAndInfo;
125893      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
125894      chngToIN = 0;
125895      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
125896      if( pAndInfo ){
125897        WhereClause *pAndWC;
125898        WhereTerm *pAndTerm;
125899        int j;
125900        Bitmask b = 0;
125901        pOrTerm->u.pAndInfo = pAndInfo;
125902        pOrTerm->wtFlags |= TERM_ANDINFO;
125903        pOrTerm->eOperator = WO_AND;
125904        pAndWC = &pAndInfo->wc;
125905        memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
125906        sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
125907        sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
125908        sqlite3WhereExprAnalyze(pSrc, pAndWC);
125909        pAndWC->pOuter = pWC;
125910        if( !db->mallocFailed ){
125911          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
125912            assert( pAndTerm->pExpr );
125913            if( allowedOp(pAndTerm->pExpr->op)
125914             || pAndTerm->eOperator==WO_MATCH
125915            ){
125916              b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
125917            }
125918          }
125919        }
125920        indexable &= b;
125921      }
125922    }else if( pOrTerm->wtFlags & TERM_COPIED ){
125923      /* Skip this term for now.  We revisit it when we process the
125924      ** corresponding TERM_VIRTUAL term */
125925    }else{
125926      Bitmask b;
125927      b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
125928      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
125929        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
125930        b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
125931      }
125932      indexable &= b;
125933      if( (pOrTerm->eOperator & WO_EQ)==0 ){
125934        chngToIN = 0;
125935      }else{
125936        chngToIN &= b;
125937      }
125938    }
125939  }
125940
125941  /*
125942  ** Record the set of tables that satisfy case 3.  The set might be
125943  ** empty.
125944  */
125945  pOrInfo->indexable = indexable;
125946  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
125947
125948  /* For a two-way OR, attempt to implementation case 2.
125949  */
125950  if( indexable && pOrWc->nTerm==2 ){
125951    int iOne = 0;
125952    WhereTerm *pOne;
125953    while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
125954      int iTwo = 0;
125955      WhereTerm *pTwo;
125956      while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
125957        whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
125958      }
125959    }
125960  }
125961
125962  /*
125963  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
125964  ** we have to do some additional checking to see if case 1 really
125965  ** is satisfied.
125966  **
125967  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
125968  ** that there is no possibility of transforming the OR clause into an
125969  ** IN operator because one or more terms in the OR clause contain
125970  ** something other than == on a column in the single table.  The 1-bit
125971  ** case means that every term of the OR clause is of the form
125972  ** "table.column=expr" for some single table.  The one bit that is set
125973  ** will correspond to the common table.  We still need to check to make
125974  ** sure the same column is used on all terms.  The 2-bit case is when
125975  ** the all terms are of the form "table1.column=table2.column".  It
125976  ** might be possible to form an IN operator with either table1.column
125977  ** or table2.column as the LHS if either is common to every term of
125978  ** the OR clause.
125979  **
125980  ** Note that terms of the form "table.column1=table.column2" (the
125981  ** same table on both sizes of the ==) cannot be optimized.
125982  */
125983  if( chngToIN ){
125984    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
125985    int iColumn = -1;         /* Column index on lhs of IN operator */
125986    int iCursor = -1;         /* Table cursor common to all terms */
125987    int j = 0;                /* Loop counter */
125988
125989    /* Search for a table and column that appears on one side or the
125990    ** other of the == operator in every subterm.  That table and column
125991    ** will be recorded in iCursor and iColumn.  There might not be any
125992    ** such table and column.  Set okToChngToIN if an appropriate table
125993    ** and column is found but leave okToChngToIN false if not found.
125994    */
125995    for(j=0; j<2 && !okToChngToIN; j++){
125996      pOrTerm = pOrWc->a;
125997      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
125998        assert( pOrTerm->eOperator & WO_EQ );
125999        pOrTerm->wtFlags &= ~TERM_OR_OK;
126000        if( pOrTerm->leftCursor==iCursor ){
126001          /* This is the 2-bit case and we are on the second iteration and
126002          ** current term is from the first iteration.  So skip this term. */
126003          assert( j==1 );
126004          continue;
126005        }
126006        if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
126007                                            pOrTerm->leftCursor))==0 ){
126008          /* This term must be of the form t1.a==t2.b where t2 is in the
126009          ** chngToIN set but t1 is not.  This term will be either preceded
126010          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
126011          ** and use its inversion. */
126012          testcase( pOrTerm->wtFlags & TERM_COPIED );
126013          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
126014          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
126015          continue;
126016        }
126017        iColumn = pOrTerm->u.leftColumn;
126018        iCursor = pOrTerm->leftCursor;
126019        break;
126020      }
126021      if( i<0 ){
126022        /* No candidate table+column was found.  This can only occur
126023        ** on the second iteration */
126024        assert( j==1 );
126025        assert( IsPowerOfTwo(chngToIN) );
126026        assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
126027        break;
126028      }
126029      testcase( j==1 );
126030
126031      /* We have found a candidate table and column.  Check to see if that
126032      ** table and column is common to every term in the OR clause */
126033      okToChngToIN = 1;
126034      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
126035        assert( pOrTerm->eOperator & WO_EQ );
126036        if( pOrTerm->leftCursor!=iCursor ){
126037          pOrTerm->wtFlags &= ~TERM_OR_OK;
126038        }else if( pOrTerm->u.leftColumn!=iColumn ){
126039          okToChngToIN = 0;
126040        }else{
126041          int affLeft, affRight;
126042          /* If the right-hand side is also a column, then the affinities
126043          ** of both right and left sides must be such that no type
126044          ** conversions are required on the right.  (Ticket #2249)
126045          */
126046          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
126047          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
126048          if( affRight!=0 && affRight!=affLeft ){
126049            okToChngToIN = 0;
126050          }else{
126051            pOrTerm->wtFlags |= TERM_OR_OK;
126052          }
126053        }
126054      }
126055    }
126056
126057    /* At this point, okToChngToIN is true if original pTerm satisfies
126058    ** case 1.  In that case, construct a new virtual term that is
126059    ** pTerm converted into an IN operator.
126060    */
126061    if( okToChngToIN ){
126062      Expr *pDup;            /* A transient duplicate expression */
126063      ExprList *pList = 0;   /* The RHS of the IN operator */
126064      Expr *pLeft = 0;       /* The LHS of the IN operator */
126065      Expr *pNew;            /* The complete IN operator */
126066
126067      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
126068        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
126069        assert( pOrTerm->eOperator & WO_EQ );
126070        assert( pOrTerm->leftCursor==iCursor );
126071        assert( pOrTerm->u.leftColumn==iColumn );
126072        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
126073        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
126074        pLeft = pOrTerm->pExpr->pLeft;
126075      }
126076      assert( pLeft!=0 );
126077      pDup = sqlite3ExprDup(db, pLeft, 0);
126078      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
126079      if( pNew ){
126080        int idxNew;
126081        transferJoinMarkings(pNew, pExpr);
126082        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
126083        pNew->x.pList = pList;
126084        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
126085        testcase( idxNew==0 );
126086        exprAnalyze(pSrc, pWC, idxNew);
126087        pTerm = &pWC->a[idxTerm];
126088        markTermAsChild(pWC, idxNew, idxTerm);
126089      }else{
126090        sqlite3ExprListDelete(db, pList);
126091      }
126092      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
126093    }
126094  }
126095}
126096#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
126097
126098/*
126099** We already know that pExpr is a binary operator where both operands are
126100** column references.  This routine checks to see if pExpr is an equivalence
126101** relation:
126102**   1.  The SQLITE_Transitive optimization must be enabled
126103**   2.  Must be either an == or an IS operator
126104**   3.  Not originating in the ON clause of an OUTER JOIN
126105**   4.  The affinities of A and B must be compatible
126106**   5a. Both operands use the same collating sequence OR
126107**   5b. The overall collating sequence is BINARY
126108** If this routine returns TRUE, that means that the RHS can be substituted
126109** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
126110** This is an optimization.  No harm comes from returning 0.  But if 1 is
126111** returned when it should not be, then incorrect answers might result.
126112*/
126113static int termIsEquivalence(Parse *pParse, Expr *pExpr){
126114  char aff1, aff2;
126115  CollSeq *pColl;
126116  const char *zColl1, *zColl2;
126117  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
126118  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
126119  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
126120  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
126121  aff2 = sqlite3ExprAffinity(pExpr->pRight);
126122  if( aff1!=aff2
126123   && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
126124  ){
126125    return 0;
126126  }
126127  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
126128  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
126129  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
126130  zColl1 = pColl ? pColl->zName : 0;
126131  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
126132  zColl2 = pColl ? pColl->zName : 0;
126133  return sqlite3_stricmp(zColl1, zColl2)==0;
126134}
126135
126136/*
126137** Recursively walk the expressions of a SELECT statement and generate
126138** a bitmask indicating which tables are used in that expression
126139** tree.
126140*/
126141static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
126142  Bitmask mask = 0;
126143  while( pS ){
126144    SrcList *pSrc = pS->pSrc;
126145    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
126146    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
126147    mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
126148    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
126149    mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
126150    if( ALWAYS(pSrc!=0) ){
126151      int i;
126152      for(i=0; i<pSrc->nSrc; i++){
126153        mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
126154        mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
126155      }
126156    }
126157    pS = pS->pPrior;
126158  }
126159  return mask;
126160}
126161
126162/*
126163** Expression pExpr is one operand of a comparison operator that might
126164** be useful for indexing.  This routine checks to see if pExpr appears
126165** in any index.  Return TRUE (1) if pExpr is an indexed term and return
126166** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
126167** number of the table that is indexed and *piColumn to the column number
126168** of the column that is indexed, or -2 if an expression is being indexed.
126169**
126170** If pExpr is a TK_COLUMN column reference, then this routine always returns
126171** true even if that particular column is not indexed, because the column
126172** might be added to an automatic index later.
126173*/
126174static int exprMightBeIndexed(
126175  SrcList *pFrom,        /* The FROM clause */
126176  Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
126177  Expr *pExpr,           /* An operand of a comparison operator */
126178  int *piCur,            /* Write the referenced table cursor number here */
126179  int *piColumn          /* Write the referenced table column number here */
126180){
126181  Index *pIdx;
126182  int i;
126183  int iCur;
126184  if( pExpr->op==TK_COLUMN ){
126185    *piCur = pExpr->iTable;
126186    *piColumn = pExpr->iColumn;
126187    return 1;
126188  }
126189  if( mPrereq==0 ) return 0;                 /* No table references */
126190  if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
126191  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
126192  iCur = pFrom->a[i].iCursor;
126193  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
126194    if( pIdx->aColExpr==0 ) continue;
126195    for(i=0; i<pIdx->nKeyCol; i++){
126196      if( pIdx->aiColumn[i]!=(-2) ) continue;
126197      if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
126198        *piCur = iCur;
126199        *piColumn = -2;
126200        return 1;
126201      }
126202    }
126203  }
126204  return 0;
126205}
126206
126207/*
126208** The input to this routine is an WhereTerm structure with only the
126209** "pExpr" field filled in.  The job of this routine is to analyze the
126210** subexpression and populate all the other fields of the WhereTerm
126211** structure.
126212**
126213** If the expression is of the form "<expr> <op> X" it gets commuted
126214** to the standard form of "X <op> <expr>".
126215**
126216** If the expression is of the form "X <op> Y" where both X and Y are
126217** columns, then the original expression is unchanged and a new virtual
126218** term of the form "Y <op> X" is added to the WHERE clause and
126219** analyzed separately.  The original term is marked with TERM_COPIED
126220** and the new term is marked with TERM_DYNAMIC (because it's pExpr
126221** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
126222** is a commuted copy of a prior term.)  The original term has nChild=1
126223** and the copy has idxParent set to the index of the original term.
126224*/
126225static void exprAnalyze(
126226  SrcList *pSrc,            /* the FROM clause */
126227  WhereClause *pWC,         /* the WHERE clause */
126228  int idxTerm               /* Index of the term to be analyzed */
126229){
126230  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
126231  WhereTerm *pTerm;                /* The term to be analyzed */
126232  WhereMaskSet *pMaskSet;          /* Set of table index masks */
126233  Expr *pExpr;                     /* The expression to be analyzed */
126234  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
126235  Bitmask prereqAll;               /* Prerequesites of pExpr */
126236  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
126237  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
126238  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
126239  int noCase = 0;                  /* uppercase equivalent to lowercase */
126240  int op;                          /* Top-level operator.  pExpr->op */
126241  Parse *pParse = pWInfo->pParse;  /* Parsing context */
126242  sqlite3 *db = pParse->db;        /* Database connection */
126243  unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
126244
126245  if( db->mallocFailed ){
126246    return;
126247  }
126248  pTerm = &pWC->a[idxTerm];
126249  pMaskSet = &pWInfo->sMaskSet;
126250  pExpr = pTerm->pExpr;
126251  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
126252  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
126253  op = pExpr->op;
126254  if( op==TK_IN ){
126255    assert( pExpr->pRight==0 );
126256    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
126257      pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
126258    }else{
126259      pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
126260    }
126261  }else if( op==TK_ISNULL ){
126262    pTerm->prereqRight = 0;
126263  }else{
126264    pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
126265  }
126266  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
126267  if( ExprHasProperty(pExpr, EP_FromJoin) ){
126268    Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
126269    prereqAll |= x;
126270    extraRight = x-1;  /* ON clause terms may not be used with an index
126271                       ** on left table of a LEFT JOIN.  Ticket #3015 */
126272  }
126273  pTerm->prereqAll = prereqAll;
126274  pTerm->leftCursor = -1;
126275  pTerm->iParent = -1;
126276  pTerm->eOperator = 0;
126277  if( allowedOp(op) ){
126278    int iCur, iColumn;
126279    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
126280    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
126281    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
126282    if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
126283      pTerm->leftCursor = iCur;
126284      pTerm->u.leftColumn = iColumn;
126285      pTerm->eOperator = operatorMask(op) & opMask;
126286    }
126287    if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
126288    if( pRight
126289     && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
126290    ){
126291      WhereTerm *pNew;
126292      Expr *pDup;
126293      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
126294      if( pTerm->leftCursor>=0 ){
126295        int idxNew;
126296        pDup = sqlite3ExprDup(db, pExpr, 0);
126297        if( db->mallocFailed ){
126298          sqlite3ExprDelete(db, pDup);
126299          return;
126300        }
126301        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
126302        if( idxNew==0 ) return;
126303        pNew = &pWC->a[idxNew];
126304        markTermAsChild(pWC, idxNew, idxTerm);
126305        if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
126306        pTerm = &pWC->a[idxTerm];
126307        pTerm->wtFlags |= TERM_COPIED;
126308
126309        if( termIsEquivalence(pParse, pDup) ){
126310          pTerm->eOperator |= WO_EQUIV;
126311          eExtraOp = WO_EQUIV;
126312        }
126313      }else{
126314        pDup = pExpr;
126315        pNew = pTerm;
126316      }
126317      exprCommute(pParse, pDup);
126318      pNew->leftCursor = iCur;
126319      pNew->u.leftColumn = iColumn;
126320      testcase( (prereqLeft | extraRight) != prereqLeft );
126321      pNew->prereqRight = prereqLeft | extraRight;
126322      pNew->prereqAll = prereqAll;
126323      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
126324    }
126325  }
126326
126327#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
126328  /* If a term is the BETWEEN operator, create two new virtual terms
126329  ** that define the range that the BETWEEN implements.  For example:
126330  **
126331  **      a BETWEEN b AND c
126332  **
126333  ** is converted into:
126334  **
126335  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
126336  **
126337  ** The two new terms are added onto the end of the WhereClause object.
126338  ** The new terms are "dynamic" and are children of the original BETWEEN
126339  ** term.  That means that if the BETWEEN term is coded, the children are
126340  ** skipped.  Or, if the children are satisfied by an index, the original
126341  ** BETWEEN term is skipped.
126342  */
126343  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
126344    ExprList *pList = pExpr->x.pList;
126345    int i;
126346    static const u8 ops[] = {TK_GE, TK_LE};
126347    assert( pList!=0 );
126348    assert( pList->nExpr==2 );
126349    for(i=0; i<2; i++){
126350      Expr *pNewExpr;
126351      int idxNew;
126352      pNewExpr = sqlite3PExpr(pParse, ops[i],
126353                             sqlite3ExprDup(db, pExpr->pLeft, 0),
126354                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
126355      transferJoinMarkings(pNewExpr, pExpr);
126356      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
126357      testcase( idxNew==0 );
126358      exprAnalyze(pSrc, pWC, idxNew);
126359      pTerm = &pWC->a[idxTerm];
126360      markTermAsChild(pWC, idxNew, idxTerm);
126361    }
126362  }
126363#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
126364
126365#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
126366  /* Analyze a term that is composed of two or more subterms connected by
126367  ** an OR operator.
126368  */
126369  else if( pExpr->op==TK_OR ){
126370    assert( pWC->op==TK_AND );
126371    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
126372    pTerm = &pWC->a[idxTerm];
126373  }
126374#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
126375
126376#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
126377  /* Add constraints to reduce the search space on a LIKE or GLOB
126378  ** operator.
126379  **
126380  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
126381  **
126382  **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
126383  **
126384  ** The last character of the prefix "abc" is incremented to form the
126385  ** termination condition "abd".  If case is not significant (the default
126386  ** for LIKE) then the lower-bound is made all uppercase and the upper-
126387  ** bound is made all lowercase so that the bounds also work when comparing
126388  ** BLOBs.
126389  */
126390  if( pWC->op==TK_AND
126391   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
126392  ){
126393    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
126394    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
126395    Expr *pNewExpr1;
126396    Expr *pNewExpr2;
126397    int idxNew1;
126398    int idxNew2;
126399    const char *zCollSeqName;     /* Name of collating sequence */
126400    const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
126401
126402    pLeft = pExpr->x.pList->a[1].pExpr;
126403    pStr2 = sqlite3ExprDup(db, pStr1, 0);
126404
126405    /* Convert the lower bound to upper-case and the upper bound to
126406    ** lower-case (upper-case is less than lower-case in ASCII) so that
126407    ** the range constraints also work for BLOBs
126408    */
126409    if( noCase && !pParse->db->mallocFailed ){
126410      int i;
126411      char c;
126412      pTerm->wtFlags |= TERM_LIKE;
126413      for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
126414        pStr1->u.zToken[i] = sqlite3Toupper(c);
126415        pStr2->u.zToken[i] = sqlite3Tolower(c);
126416      }
126417    }
126418
126419    if( !db->mallocFailed ){
126420      u8 c, *pC;       /* Last character before the first wildcard */
126421      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
126422      c = *pC;
126423      if( noCase ){
126424        /* The point is to increment the last character before the first
126425        ** wildcard.  But if we increment '@', that will push it into the
126426        ** alphabetic range where case conversions will mess up the
126427        ** inequality.  To avoid this, make sure to also run the full
126428        ** LIKE on all candidate expressions by clearing the isComplete flag
126429        */
126430        if( c=='A'-1 ) isComplete = 0;
126431        c = sqlite3UpperToLower[c];
126432      }
126433      *pC = c + 1;
126434    }
126435    zCollSeqName = noCase ? "NOCASE" : "BINARY";
126436    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
126437    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
126438           sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
126439           pStr1, 0);
126440    transferJoinMarkings(pNewExpr1, pExpr);
126441    idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
126442    testcase( idxNew1==0 );
126443    exprAnalyze(pSrc, pWC, idxNew1);
126444    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
126445    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
126446           sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
126447           pStr2, 0);
126448    transferJoinMarkings(pNewExpr2, pExpr);
126449    idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
126450    testcase( idxNew2==0 );
126451    exprAnalyze(pSrc, pWC, idxNew2);
126452    pTerm = &pWC->a[idxTerm];
126453    if( isComplete ){
126454      markTermAsChild(pWC, idxNew1, idxTerm);
126455      markTermAsChild(pWC, idxNew2, idxTerm);
126456    }
126457  }
126458#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
126459
126460#ifndef SQLITE_OMIT_VIRTUALTABLE
126461  /* Add a WO_MATCH auxiliary term to the constraint set if the
126462  ** current expression is of the form:  column MATCH expr.
126463  ** This information is used by the xBestIndex methods of
126464  ** virtual tables.  The native query optimizer does not attempt
126465  ** to do anything with MATCH functions.
126466  */
126467  if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
126468    int idxNew;
126469    Expr *pRight, *pLeft;
126470    WhereTerm *pNewTerm;
126471    Bitmask prereqColumn, prereqExpr;
126472
126473    pRight = pExpr->x.pList->a[0].pExpr;
126474    pLeft = pExpr->x.pList->a[1].pExpr;
126475    prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
126476    prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
126477    if( (prereqExpr & prereqColumn)==0 ){
126478      Expr *pNewExpr;
126479      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
126480                              0, sqlite3ExprDup(db, pRight, 0), 0);
126481      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
126482      testcase( idxNew==0 );
126483      pNewTerm = &pWC->a[idxNew];
126484      pNewTerm->prereqRight = prereqExpr;
126485      pNewTerm->leftCursor = pLeft->iTable;
126486      pNewTerm->u.leftColumn = pLeft->iColumn;
126487      pNewTerm->eOperator = WO_MATCH;
126488      pNewTerm->eMatchOp = eOp2;
126489      markTermAsChild(pWC, idxNew, idxTerm);
126490      pTerm = &pWC->a[idxTerm];
126491      pTerm->wtFlags |= TERM_COPIED;
126492      pNewTerm->prereqAll = pTerm->prereqAll;
126493    }
126494  }
126495#endif /* SQLITE_OMIT_VIRTUALTABLE */
126496
126497#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
126498  /* When sqlite_stat3 histogram data is available an operator of the
126499  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
126500  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
126501  ** virtual term of that form.
126502  **
126503  ** Note that the virtual term must be tagged with TERM_VNULL.
126504  */
126505  if( pExpr->op==TK_NOTNULL
126506   && pExpr->pLeft->op==TK_COLUMN
126507   && pExpr->pLeft->iColumn>=0
126508   && OptimizationEnabled(db, SQLITE_Stat34)
126509  ){
126510    Expr *pNewExpr;
126511    Expr *pLeft = pExpr->pLeft;
126512    int idxNew;
126513    WhereTerm *pNewTerm;
126514
126515    pNewExpr = sqlite3PExpr(pParse, TK_GT,
126516                            sqlite3ExprDup(db, pLeft, 0),
126517                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
126518
126519    idxNew = whereClauseInsert(pWC, pNewExpr,
126520                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
126521    if( idxNew ){
126522      pNewTerm = &pWC->a[idxNew];
126523      pNewTerm->prereqRight = 0;
126524      pNewTerm->leftCursor = pLeft->iTable;
126525      pNewTerm->u.leftColumn = pLeft->iColumn;
126526      pNewTerm->eOperator = WO_GT;
126527      markTermAsChild(pWC, idxNew, idxTerm);
126528      pTerm = &pWC->a[idxTerm];
126529      pTerm->wtFlags |= TERM_COPIED;
126530      pNewTerm->prereqAll = pTerm->prereqAll;
126531    }
126532  }
126533#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
126534
126535  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
126536  ** an index for tables to the left of the join.
126537  */
126538  pTerm->prereqRight |= extraRight;
126539}
126540
126541/***************************************************************************
126542** Routines with file scope above.  Interface to the rest of the where.c
126543** subsystem follows.
126544***************************************************************************/
126545
126546/*
126547** This routine identifies subexpressions in the WHERE clause where
126548** each subexpression is separated by the AND operator or some other
126549** operator specified in the op parameter.  The WhereClause structure
126550** is filled with pointers to subexpressions.  For example:
126551**
126552**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
126553**           \________/     \_______________/     \________________/
126554**            slot[0]            slot[1]               slot[2]
126555**
126556** The original WHERE clause in pExpr is unaltered.  All this routine
126557** does is make slot[] entries point to substructure within pExpr.
126558**
126559** In the previous sentence and in the diagram, "slot[]" refers to
126560** the WhereClause.a[] array.  The slot[] array grows as needed to contain
126561** all terms of the WHERE clause.
126562*/
126563SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
126564  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
126565  pWC->op = op;
126566  if( pE2==0 ) return;
126567  if( pE2->op!=op ){
126568    whereClauseInsert(pWC, pExpr, 0);
126569  }else{
126570    sqlite3WhereSplit(pWC, pE2->pLeft, op);
126571    sqlite3WhereSplit(pWC, pE2->pRight, op);
126572  }
126573}
126574
126575/*
126576** Initialize a preallocated WhereClause structure.
126577*/
126578SQLITE_PRIVATE void sqlite3WhereClauseInit(
126579  WhereClause *pWC,        /* The WhereClause to be initialized */
126580  WhereInfo *pWInfo        /* The WHERE processing context */
126581){
126582  pWC->pWInfo = pWInfo;
126583  pWC->pOuter = 0;
126584  pWC->nTerm = 0;
126585  pWC->nSlot = ArraySize(pWC->aStatic);
126586  pWC->a = pWC->aStatic;
126587}
126588
126589/*
126590** Deallocate a WhereClause structure.  The WhereClause structure
126591** itself is not freed.  This routine is the inverse of
126592** sqlite3WhereClauseInit().
126593*/
126594SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
126595  int i;
126596  WhereTerm *a;
126597  sqlite3 *db = pWC->pWInfo->pParse->db;
126598  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
126599    if( a->wtFlags & TERM_DYNAMIC ){
126600      sqlite3ExprDelete(db, a->pExpr);
126601    }
126602    if( a->wtFlags & TERM_ORINFO ){
126603      whereOrInfoDelete(db, a->u.pOrInfo);
126604    }else if( a->wtFlags & TERM_ANDINFO ){
126605      whereAndInfoDelete(db, a->u.pAndInfo);
126606    }
126607  }
126608  if( pWC->a!=pWC->aStatic ){
126609    sqlite3DbFree(db, pWC->a);
126610  }
126611}
126612
126613
126614/*
126615** These routines walk (recursively) an expression tree and generate
126616** a bitmask indicating which tables are used in that expression
126617** tree.
126618*/
126619SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
126620  Bitmask mask = 0;
126621  if( p==0 ) return 0;
126622  if( p->op==TK_COLUMN ){
126623    mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
126624    return mask;
126625  }
126626  mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
126627  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
126628  if( ExprHasProperty(p, EP_xIsSelect) ){
126629    mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
126630  }else if( p->x.pList ){
126631    mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
126632  }
126633  return mask;
126634}
126635SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
126636  int i;
126637  Bitmask mask = 0;
126638  if( pList ){
126639    for(i=0; i<pList->nExpr; i++){
126640      mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
126641    }
126642  }
126643  return mask;
126644}
126645
126646
126647/*
126648** Call exprAnalyze on all terms in a WHERE clause.
126649**
126650** Note that exprAnalyze() might add new virtual terms onto the
126651** end of the WHERE clause.  We do not want to analyze these new
126652** virtual terms, so start analyzing at the end and work forward
126653** so that the added virtual terms are never processed.
126654*/
126655SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
126656  SrcList *pTabList,       /* the FROM clause */
126657  WhereClause *pWC         /* the WHERE clause to be analyzed */
126658){
126659  int i;
126660  for(i=pWC->nTerm-1; i>=0; i--){
126661    exprAnalyze(pTabList, pWC, i);
126662  }
126663}
126664
126665/*
126666** For table-valued-functions, transform the function arguments into
126667** new WHERE clause terms.
126668**
126669** Each function argument translates into an equality constraint against
126670** a HIDDEN column in the table.
126671*/
126672SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
126673  Parse *pParse,                    /* Parsing context */
126674  struct SrcList_item *pItem,       /* The FROM clause term to process */
126675  WhereClause *pWC                  /* Xfer function arguments to here */
126676){
126677  Table *pTab;
126678  int j, k;
126679  ExprList *pArgs;
126680  Expr *pColRef;
126681  Expr *pTerm;
126682  if( pItem->fg.isTabFunc==0 ) return;
126683  pTab = pItem->pTab;
126684  assert( pTab!=0 );
126685  pArgs = pItem->u1.pFuncArg;
126686  if( pArgs==0 ) return;
126687  for(j=k=0; j<pArgs->nExpr; j++){
126688    while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
126689    if( k>=pTab->nCol ){
126690      sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
126691                      pTab->zName, j);
126692      return;
126693    }
126694    pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
126695    if( pColRef==0 ) return;
126696    pColRef->iTable = pItem->iCursor;
126697    pColRef->iColumn = k++;
126698    pColRef->pTab = pTab;
126699    pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
126700                         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
126701    whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
126702  }
126703}
126704
126705/************** End of whereexpr.c *******************************************/
126706/************** Begin file where.c *******************************************/
126707/*
126708** 2001 September 15
126709**
126710** The author disclaims copyright to this source code.  In place of
126711** a legal notice, here is a blessing:
126712**
126713**    May you do good and not evil.
126714**    May you find forgiveness for yourself and forgive others.
126715**    May you share freely, never taking more than you give.
126716**
126717*************************************************************************
126718** This module contains C code that generates VDBE code used to process
126719** the WHERE clause of SQL statements.  This module is responsible for
126720** generating the code that loops through a table looking for applicable
126721** rows.  Indices are selected and used to speed the search when doing
126722** so is applicable.  Because this module is responsible for selecting
126723** indices, you might also think of this module as the "query optimizer".
126724*/
126725/* #include "sqliteInt.h" */
126726/* #include "whereInt.h" */
126727
126728/* Forward declaration of methods */
126729static int whereLoopResize(sqlite3*, WhereLoop*, int);
126730
126731/* Test variable that can be set to enable WHERE tracing */
126732#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
126733/***/ int sqlite3WhereTrace = 0;
126734#endif
126735
126736
126737/*
126738** Return the estimated number of output rows from a WHERE clause
126739*/
126740SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
126741  return pWInfo->nRowOut;
126742}
126743
126744/*
126745** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
126746** WHERE clause returns outputs for DISTINCT processing.
126747*/
126748SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
126749  return pWInfo->eDistinct;
126750}
126751
126752/*
126753** Return TRUE if the WHERE clause returns rows in ORDER BY order.
126754** Return FALSE if the output needs to be sorted.
126755*/
126756SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
126757  return pWInfo->nOBSat;
126758}
126759
126760/*
126761** Return TRUE if the innermost loop of the WHERE clause implementation
126762** returns rows in ORDER BY order for complete run of the inner loop.
126763**
126764** Across multiple iterations of outer loops, the output rows need not be
126765** sorted.  As long as rows are sorted for just the innermost loop, this
126766** routine can return TRUE.
126767*/
126768SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
126769  return pWInfo->bOrderedInnerLoop;
126770}
126771
126772/*
126773** Return the VDBE address or label to jump to in order to continue
126774** immediately with the next row of a WHERE clause.
126775*/
126776SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
126777  assert( pWInfo->iContinue!=0 );
126778  return pWInfo->iContinue;
126779}
126780
126781/*
126782** Return the VDBE address or label to jump to in order to break
126783** out of a WHERE loop.
126784*/
126785SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
126786  return pWInfo->iBreak;
126787}
126788
126789/*
126790** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
126791** operate directly on the rowis returned by a WHERE clause.  Return
126792** ONEPASS_SINGLE (1) if the statement can operation directly because only
126793** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
126794** optimization can be used on multiple
126795**
126796** If the ONEPASS optimization is used (if this routine returns true)
126797** then also write the indices of open cursors used by ONEPASS
126798** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
126799** table and iaCur[1] gets the cursor used by an auxiliary index.
126800** Either value may be -1, indicating that cursor is not used.
126801** Any cursors returned will have been opened for writing.
126802**
126803** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
126804** unable to use the ONEPASS optimization.
126805*/
126806SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
126807  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
126808#ifdef WHERETRACE_ENABLED
126809  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
126810    sqlite3DebugPrintf("%s cursors: %d %d\n",
126811         pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
126812         aiCur[0], aiCur[1]);
126813  }
126814#endif
126815  return pWInfo->eOnePass;
126816}
126817
126818/*
126819** Move the content of pSrc into pDest
126820*/
126821static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
126822  pDest->n = pSrc->n;
126823  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
126824}
126825
126826/*
126827** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
126828**
126829** The new entry might overwrite an existing entry, or it might be
126830** appended, or it might be discarded.  Do whatever is the right thing
126831** so that pSet keeps the N_OR_COST best entries seen so far.
126832*/
126833static int whereOrInsert(
126834  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
126835  Bitmask prereq,        /* Prerequisites of the new entry */
126836  LogEst rRun,           /* Run-cost of the new entry */
126837  LogEst nOut            /* Number of outputs for the new entry */
126838){
126839  u16 i;
126840  WhereOrCost *p;
126841  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
126842    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
126843      goto whereOrInsert_done;
126844    }
126845    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
126846      return 0;
126847    }
126848  }
126849  if( pSet->n<N_OR_COST ){
126850    p = &pSet->a[pSet->n++];
126851    p->nOut = nOut;
126852  }else{
126853    p = pSet->a;
126854    for(i=1; i<pSet->n; i++){
126855      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
126856    }
126857    if( p->rRun<=rRun ) return 0;
126858  }
126859whereOrInsert_done:
126860  p->prereq = prereq;
126861  p->rRun = rRun;
126862  if( p->nOut>nOut ) p->nOut = nOut;
126863  return 1;
126864}
126865
126866/*
126867** Return the bitmask for the given cursor number.  Return 0 if
126868** iCursor is not in the set.
126869*/
126870SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
126871  int i;
126872  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
126873  for(i=0; i<pMaskSet->n; i++){
126874    if( pMaskSet->ix[i]==iCursor ){
126875      return MASKBIT(i);
126876    }
126877  }
126878  return 0;
126879}
126880
126881/*
126882** Create a new mask for cursor iCursor.
126883**
126884** There is one cursor per table in the FROM clause.  The number of
126885** tables in the FROM clause is limited by a test early in the
126886** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
126887** array will never overflow.
126888*/
126889static void createMask(WhereMaskSet *pMaskSet, int iCursor){
126890  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
126891  pMaskSet->ix[pMaskSet->n++] = iCursor;
126892}
126893
126894/*
126895** Advance to the next WhereTerm that matches according to the criteria
126896** established when the pScan object was initialized by whereScanInit().
126897** Return NULL if there are no more matching WhereTerms.
126898*/
126899static WhereTerm *whereScanNext(WhereScan *pScan){
126900  int iCur;            /* The cursor on the LHS of the term */
126901  i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
126902  Expr *pX;            /* An expression being tested */
126903  WhereClause *pWC;    /* Shorthand for pScan->pWC */
126904  WhereTerm *pTerm;    /* The term being tested */
126905  int k = pScan->k;    /* Where to start scanning */
126906
126907  while( pScan->iEquiv<=pScan->nEquiv ){
126908    iCur = pScan->aiCur[pScan->iEquiv-1];
126909    iColumn = pScan->aiColumn[pScan->iEquiv-1];
126910    if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
126911    while( (pWC = pScan->pWC)!=0 ){
126912      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
126913        if( pTerm->leftCursor==iCur
126914         && pTerm->u.leftColumn==iColumn
126915         && (iColumn!=XN_EXPR
126916             || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
126917         && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
126918        ){
126919          if( (pTerm->eOperator & WO_EQUIV)!=0
126920           && pScan->nEquiv<ArraySize(pScan->aiCur)
126921           && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
126922          ){
126923            int j;
126924            for(j=0; j<pScan->nEquiv; j++){
126925              if( pScan->aiCur[j]==pX->iTable
126926               && pScan->aiColumn[j]==pX->iColumn ){
126927                  break;
126928              }
126929            }
126930            if( j==pScan->nEquiv ){
126931              pScan->aiCur[j] = pX->iTable;
126932              pScan->aiColumn[j] = pX->iColumn;
126933              pScan->nEquiv++;
126934            }
126935          }
126936          if( (pTerm->eOperator & pScan->opMask)!=0 ){
126937            /* Verify the affinity and collating sequence match */
126938            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
126939              CollSeq *pColl;
126940              Parse *pParse = pWC->pWInfo->pParse;
126941              pX = pTerm->pExpr;
126942              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
126943                continue;
126944              }
126945              assert(pX->pLeft);
126946              pColl = sqlite3BinaryCompareCollSeq(pParse,
126947                                                  pX->pLeft, pX->pRight);
126948              if( pColl==0 ) pColl = pParse->db->pDfltColl;
126949              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
126950                continue;
126951              }
126952            }
126953            if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
126954             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
126955             && pX->iTable==pScan->aiCur[0]
126956             && pX->iColumn==pScan->aiColumn[0]
126957            ){
126958              testcase( pTerm->eOperator & WO_IS );
126959              continue;
126960            }
126961            pScan->k = k+1;
126962            return pTerm;
126963          }
126964        }
126965      }
126966      pScan->pWC = pScan->pWC->pOuter;
126967      k = 0;
126968    }
126969    pScan->pWC = pScan->pOrigWC;
126970    k = 0;
126971    pScan->iEquiv++;
126972  }
126973  return 0;
126974}
126975
126976/*
126977** Initialize a WHERE clause scanner object.  Return a pointer to the
126978** first match.  Return NULL if there are no matches.
126979**
126980** The scanner will be searching the WHERE clause pWC.  It will look
126981** for terms of the form "X <op> <expr>" where X is column iColumn of table
126982** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
126983** must be one of the indexes of table iCur.
126984**
126985** The <op> must be one of the operators described by opMask.
126986**
126987** If the search is for X and the WHERE clause contains terms of the
126988** form X=Y then this routine might also return terms of the form
126989** "Y <op> <expr>".  The number of levels of transitivity is limited,
126990** but is enough to handle most commonly occurring SQL statements.
126991**
126992** If X is not the INTEGER PRIMARY KEY then X must be compatible with
126993** index pIdx.
126994*/
126995static WhereTerm *whereScanInit(
126996  WhereScan *pScan,       /* The WhereScan object being initialized */
126997  WhereClause *pWC,       /* The WHERE clause to be scanned */
126998  int iCur,               /* Cursor to scan for */
126999  int iColumn,            /* Column to scan for */
127000  u32 opMask,             /* Operator(s) to scan for */
127001  Index *pIdx             /* Must be compatible with this index */
127002){
127003  int j = 0;
127004
127005  /* memset(pScan, 0, sizeof(*pScan)); */
127006  pScan->pOrigWC = pWC;
127007  pScan->pWC = pWC;
127008  pScan->pIdxExpr = 0;
127009  if( pIdx ){
127010    j = iColumn;
127011    iColumn = pIdx->aiColumn[j];
127012    if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
127013    if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
127014  }
127015  if( pIdx && iColumn>=0 ){
127016    pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
127017    pScan->zCollName = pIdx->azColl[j];
127018  }else{
127019    pScan->idxaff = 0;
127020    pScan->zCollName = 0;
127021  }
127022  pScan->opMask = opMask;
127023  pScan->k = 0;
127024  pScan->aiCur[0] = iCur;
127025  pScan->aiColumn[0] = iColumn;
127026  pScan->nEquiv = 1;
127027  pScan->iEquiv = 1;
127028  return whereScanNext(pScan);
127029}
127030
127031/*
127032** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
127033** where X is a reference to the iColumn of table iCur or of index pIdx
127034** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
127035** the op parameter.  Return a pointer to the term.  Return 0 if not found.
127036**
127037** If pIdx!=0 then it must be one of the indexes of table iCur.
127038** Search for terms matching the iColumn-th column of pIdx
127039** rather than the iColumn-th column of table iCur.
127040**
127041** The term returned might by Y=<expr> if there is another constraint in
127042** the WHERE clause that specifies that X=Y.  Any such constraints will be
127043** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
127044** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
127045** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
127046** other equivalent values.  Hence a search for X will return <expr> if X=A1
127047** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
127048**
127049** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
127050** then try for the one with no dependencies on <expr> - in other words where
127051** <expr> is a constant expression of some kind.  Only return entries of
127052** the form "X <op> Y" where Y is a column in another table if no terms of
127053** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
127054** exist, try to return a term that does not use WO_EQUIV.
127055*/
127056SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
127057  WhereClause *pWC,     /* The WHERE clause to be searched */
127058  int iCur,             /* Cursor number of LHS */
127059  int iColumn,          /* Column number of LHS */
127060  Bitmask notReady,     /* RHS must not overlap with this mask */
127061  u32 op,               /* Mask of WO_xx values describing operator */
127062  Index *pIdx           /* Must be compatible with this index, if not NULL */
127063){
127064  WhereTerm *pResult = 0;
127065  WhereTerm *p;
127066  WhereScan scan;
127067
127068  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
127069  op &= WO_EQ|WO_IS;
127070  while( p ){
127071    if( (p->prereqRight & notReady)==0 ){
127072      if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
127073        testcase( p->eOperator & WO_IS );
127074        return p;
127075      }
127076      if( pResult==0 ) pResult = p;
127077    }
127078    p = whereScanNext(&scan);
127079  }
127080  return pResult;
127081}
127082
127083/*
127084** This function searches pList for an entry that matches the iCol-th column
127085** of index pIdx.
127086**
127087** If such an expression is found, its index in pList->a[] is returned. If
127088** no expression is found, -1 is returned.
127089*/
127090static int findIndexCol(
127091  Parse *pParse,                  /* Parse context */
127092  ExprList *pList,                /* Expression list to search */
127093  int iBase,                      /* Cursor for table associated with pIdx */
127094  Index *pIdx,                    /* Index to match column of */
127095  int iCol                        /* Column of index to match */
127096){
127097  int i;
127098  const char *zColl = pIdx->azColl[iCol];
127099
127100  for(i=0; i<pList->nExpr; i++){
127101    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
127102    if( p->op==TK_COLUMN
127103     && p->iColumn==pIdx->aiColumn[iCol]
127104     && p->iTable==iBase
127105    ){
127106      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
127107      if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
127108        return i;
127109      }
127110    }
127111  }
127112
127113  return -1;
127114}
127115
127116/*
127117** Return TRUE if the iCol-th column of index pIdx is NOT NULL
127118*/
127119static int indexColumnNotNull(Index *pIdx, int iCol){
127120  int j;
127121  assert( pIdx!=0 );
127122  assert( iCol>=0 && iCol<pIdx->nColumn );
127123  j = pIdx->aiColumn[iCol];
127124  if( j>=0 ){
127125    return pIdx->pTable->aCol[j].notNull;
127126  }else if( j==(-1) ){
127127    return 1;
127128  }else{
127129    assert( j==(-2) );
127130    return 0;  /* Assume an indexed expression can always yield a NULL */
127131
127132  }
127133}
127134
127135/*
127136** Return true if the DISTINCT expression-list passed as the third argument
127137** is redundant.
127138**
127139** A DISTINCT list is redundant if any subset of the columns in the
127140** DISTINCT list are collectively unique and individually non-null.
127141*/
127142static int isDistinctRedundant(
127143  Parse *pParse,            /* Parsing context */
127144  SrcList *pTabList,        /* The FROM clause */
127145  WhereClause *pWC,         /* The WHERE clause */
127146  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
127147){
127148  Table *pTab;
127149  Index *pIdx;
127150  int i;
127151  int iBase;
127152
127153  /* If there is more than one table or sub-select in the FROM clause of
127154  ** this query, then it will not be possible to show that the DISTINCT
127155  ** clause is redundant. */
127156  if( pTabList->nSrc!=1 ) return 0;
127157  iBase = pTabList->a[0].iCursor;
127158  pTab = pTabList->a[0].pTab;
127159
127160  /* If any of the expressions is an IPK column on table iBase, then return
127161  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
127162  ** current SELECT is a correlated sub-query.
127163  */
127164  for(i=0; i<pDistinct->nExpr; i++){
127165    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
127166    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
127167  }
127168
127169  /* Loop through all indices on the table, checking each to see if it makes
127170  ** the DISTINCT qualifier redundant. It does so if:
127171  **
127172  **   1. The index is itself UNIQUE, and
127173  **
127174  **   2. All of the columns in the index are either part of the pDistinct
127175  **      list, or else the WHERE clause contains a term of the form "col=X",
127176  **      where X is a constant value. The collation sequences of the
127177  **      comparison and select-list expressions must match those of the index.
127178  **
127179  **   3. All of those index columns for which the WHERE clause does not
127180  **      contain a "col=X" term are subject to a NOT NULL constraint.
127181  */
127182  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127183    if( !IsUniqueIndex(pIdx) ) continue;
127184    for(i=0; i<pIdx->nKeyCol; i++){
127185      if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
127186        if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
127187        if( indexColumnNotNull(pIdx, i)==0 ) break;
127188      }
127189    }
127190    if( i==pIdx->nKeyCol ){
127191      /* This index implies that the DISTINCT qualifier is redundant. */
127192      return 1;
127193    }
127194  }
127195
127196  return 0;
127197}
127198
127199
127200/*
127201** Estimate the logarithm of the input value to base 2.
127202*/
127203static LogEst estLog(LogEst N){
127204  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
127205}
127206
127207/*
127208** Convert OP_Column opcodes to OP_Copy in previously generated code.
127209**
127210** This routine runs over generated VDBE code and translates OP_Column
127211** opcodes into OP_Copy when the table is being accessed via co-routine
127212** instead of via table lookup.
127213**
127214** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
127215** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
127216** then each OP_Rowid is transformed into an instruction to increment the
127217** value stored in its output register.
127218*/
127219static void translateColumnToCopy(
127220  Vdbe *v,            /* The VDBE containing code to translate */
127221  int iStart,         /* Translate from this opcode to the end */
127222  int iTabCur,        /* OP_Column/OP_Rowid references to this table */
127223  int iRegister,      /* The first column is in this register */
127224  int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
127225){
127226  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
127227  int iEnd = sqlite3VdbeCurrentAddr(v);
127228  for(; iStart<iEnd; iStart++, pOp++){
127229    if( pOp->p1!=iTabCur ) continue;
127230    if( pOp->opcode==OP_Column ){
127231      pOp->opcode = OP_Copy;
127232      pOp->p1 = pOp->p2 + iRegister;
127233      pOp->p2 = pOp->p3;
127234      pOp->p3 = 0;
127235    }else if( pOp->opcode==OP_Rowid ){
127236      if( bIncrRowid ){
127237        /* Increment the value stored in the P2 operand of the OP_Rowid. */
127238        pOp->opcode = OP_AddImm;
127239        pOp->p1 = pOp->p2;
127240        pOp->p2 = 1;
127241      }else{
127242        pOp->opcode = OP_Null;
127243        pOp->p1 = 0;
127244        pOp->p3 = 0;
127245      }
127246    }
127247  }
127248}
127249
127250/*
127251** Two routines for printing the content of an sqlite3_index_info
127252** structure.  Used for testing and debugging only.  If neither
127253** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
127254** are no-ops.
127255*/
127256#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
127257static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
127258  int i;
127259  if( !sqlite3WhereTrace ) return;
127260  for(i=0; i<p->nConstraint; i++){
127261    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
127262       i,
127263       p->aConstraint[i].iColumn,
127264       p->aConstraint[i].iTermOffset,
127265       p->aConstraint[i].op,
127266       p->aConstraint[i].usable);
127267  }
127268  for(i=0; i<p->nOrderBy; i++){
127269    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
127270       i,
127271       p->aOrderBy[i].iColumn,
127272       p->aOrderBy[i].desc);
127273  }
127274}
127275static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
127276  int i;
127277  if( !sqlite3WhereTrace ) return;
127278  for(i=0; i<p->nConstraint; i++){
127279    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
127280       i,
127281       p->aConstraintUsage[i].argvIndex,
127282       p->aConstraintUsage[i].omit);
127283  }
127284  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
127285  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
127286  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
127287  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
127288  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
127289}
127290#else
127291#define TRACE_IDX_INPUTS(A)
127292#define TRACE_IDX_OUTPUTS(A)
127293#endif
127294
127295#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
127296/*
127297** Return TRUE if the WHERE clause term pTerm is of a form where it
127298** could be used with an index to access pSrc, assuming an appropriate
127299** index existed.
127300*/
127301static int termCanDriveIndex(
127302  WhereTerm *pTerm,              /* WHERE clause term to check */
127303  struct SrcList_item *pSrc,     /* Table we are trying to access */
127304  Bitmask notReady               /* Tables in outer loops of the join */
127305){
127306  char aff;
127307  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
127308  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
127309  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
127310  if( pTerm->u.leftColumn<0 ) return 0;
127311  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
127312  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
127313  testcase( pTerm->pExpr->op==TK_IS );
127314  return 1;
127315}
127316#endif
127317
127318
127319#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
127320/*
127321** Generate code to construct the Index object for an automatic index
127322** and to set up the WhereLevel object pLevel so that the code generator
127323** makes use of the automatic index.
127324*/
127325static void constructAutomaticIndex(
127326  Parse *pParse,              /* The parsing context */
127327  WhereClause *pWC,           /* The WHERE clause */
127328  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
127329  Bitmask notReady,           /* Mask of cursors that are not available */
127330  WhereLevel *pLevel          /* Write new index here */
127331){
127332  int nKeyCol;                /* Number of columns in the constructed index */
127333  WhereTerm *pTerm;           /* A single term of the WHERE clause */
127334  WhereTerm *pWCEnd;          /* End of pWC->a[] */
127335  Index *pIdx;                /* Object describing the transient index */
127336  Vdbe *v;                    /* Prepared statement under construction */
127337  int addrInit;               /* Address of the initialization bypass jump */
127338  Table *pTable;              /* The table being indexed */
127339  int addrTop;                /* Top of the index fill loop */
127340  int regRecord;              /* Register holding an index record */
127341  int n;                      /* Column counter */
127342  int i;                      /* Loop counter */
127343  int mxBitCol;               /* Maximum column in pSrc->colUsed */
127344  CollSeq *pColl;             /* Collating sequence to on a column */
127345  WhereLoop *pLoop;           /* The Loop object */
127346  char *zNotUsed;             /* Extra space on the end of pIdx */
127347  Bitmask idxCols;            /* Bitmap of columns used for indexing */
127348  Bitmask extraCols;          /* Bitmap of additional columns */
127349  u8 sentWarning = 0;         /* True if a warnning has been issued */
127350  Expr *pPartial = 0;         /* Partial Index Expression */
127351  int iContinue = 0;          /* Jump here to skip excluded rows */
127352  struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
127353  int addrCounter = 0;        /* Address where integer counter is initialized */
127354  int regBase;                /* Array of registers where record is assembled */
127355
127356  /* Generate code to skip over the creation and initialization of the
127357  ** transient index on 2nd and subsequent iterations of the loop. */
127358  v = pParse->pVdbe;
127359  assert( v!=0 );
127360  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
127361
127362  /* Count the number of columns that will be added to the index
127363  ** and used to match WHERE clause constraints */
127364  nKeyCol = 0;
127365  pTable = pSrc->pTab;
127366  pWCEnd = &pWC->a[pWC->nTerm];
127367  pLoop = pLevel->pWLoop;
127368  idxCols = 0;
127369  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
127370    Expr *pExpr = pTerm->pExpr;
127371    assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
127372         || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
127373         || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
127374    if( pLoop->prereq==0
127375     && (pTerm->wtFlags & TERM_VIRTUAL)==0
127376     && !ExprHasProperty(pExpr, EP_FromJoin)
127377     && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
127378      pPartial = sqlite3ExprAnd(pParse->db, pPartial,
127379                                sqlite3ExprDup(pParse->db, pExpr, 0));
127380    }
127381    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
127382      int iCol = pTerm->u.leftColumn;
127383      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
127384      testcase( iCol==BMS );
127385      testcase( iCol==BMS-1 );
127386      if( !sentWarning ){
127387        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
127388            "automatic index on %s(%s)", pTable->zName,
127389            pTable->aCol[iCol].zName);
127390        sentWarning = 1;
127391      }
127392      if( (idxCols & cMask)==0 ){
127393        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
127394          goto end_auto_index_create;
127395        }
127396        pLoop->aLTerm[nKeyCol++] = pTerm;
127397        idxCols |= cMask;
127398      }
127399    }
127400  }
127401  assert( nKeyCol>0 );
127402  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
127403  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
127404                     | WHERE_AUTO_INDEX;
127405
127406  /* Count the number of additional columns needed to create a
127407  ** covering index.  A "covering index" is an index that contains all
127408  ** columns that are needed by the query.  With a covering index, the
127409  ** original table never needs to be accessed.  Automatic indices must
127410  ** be a covering index because the index will not be updated if the
127411  ** original table changes and the index and table cannot both be used
127412  ** if they go out of sync.
127413  */
127414  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
127415  mxBitCol = MIN(BMS-1,pTable->nCol);
127416  testcase( pTable->nCol==BMS-1 );
127417  testcase( pTable->nCol==BMS-2 );
127418  for(i=0; i<mxBitCol; i++){
127419    if( extraCols & MASKBIT(i) ) nKeyCol++;
127420  }
127421  if( pSrc->colUsed & MASKBIT(BMS-1) ){
127422    nKeyCol += pTable->nCol - BMS + 1;
127423  }
127424
127425  /* Construct the Index object to describe this index */
127426  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
127427  if( pIdx==0 ) goto end_auto_index_create;
127428  pLoop->u.btree.pIndex = pIdx;
127429  pIdx->zName = "auto-index";
127430  pIdx->pTable = pTable;
127431  n = 0;
127432  idxCols = 0;
127433  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
127434    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
127435      int iCol = pTerm->u.leftColumn;
127436      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
127437      testcase( iCol==BMS-1 );
127438      testcase( iCol==BMS );
127439      if( (idxCols & cMask)==0 ){
127440        Expr *pX = pTerm->pExpr;
127441        idxCols |= cMask;
127442        pIdx->aiColumn[n] = pTerm->u.leftColumn;
127443        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
127444        pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
127445        n++;
127446      }
127447    }
127448  }
127449  assert( (u32)n==pLoop->u.btree.nEq );
127450
127451  /* Add additional columns needed to make the automatic index into
127452  ** a covering index */
127453  for(i=0; i<mxBitCol; i++){
127454    if( extraCols & MASKBIT(i) ){
127455      pIdx->aiColumn[n] = i;
127456      pIdx->azColl[n] = sqlite3StrBINARY;
127457      n++;
127458    }
127459  }
127460  if( pSrc->colUsed & MASKBIT(BMS-1) ){
127461    for(i=BMS-1; i<pTable->nCol; i++){
127462      pIdx->aiColumn[n] = i;
127463      pIdx->azColl[n] = sqlite3StrBINARY;
127464      n++;
127465    }
127466  }
127467  assert( n==nKeyCol );
127468  pIdx->aiColumn[n] = XN_ROWID;
127469  pIdx->azColl[n] = sqlite3StrBINARY;
127470
127471  /* Create the automatic index */
127472  assert( pLevel->iIdxCur>=0 );
127473  pLevel->iIdxCur = pParse->nTab++;
127474  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
127475  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
127476  VdbeComment((v, "for %s", pTable->zName));
127477
127478  /* Fill the automatic index with content */
127479  sqlite3ExprCachePush(pParse);
127480  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
127481  if( pTabItem->fg.viaCoroutine ){
127482    int regYield = pTabItem->regReturn;
127483    addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
127484    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
127485    addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
127486    VdbeCoverage(v);
127487    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
127488  }else{
127489    addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
127490  }
127491  if( pPartial ){
127492    iContinue = sqlite3VdbeMakeLabel(v);
127493    sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
127494    pLoop->wsFlags |= WHERE_PARTIALIDX;
127495  }
127496  regRecord = sqlite3GetTempReg(pParse);
127497  regBase = sqlite3GenerateIndexKey(
127498      pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
127499  );
127500  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
127501  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
127502  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
127503  if( pTabItem->fg.viaCoroutine ){
127504    sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
127505    translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
127506    sqlite3VdbeGoto(v, addrTop);
127507    pTabItem->fg.viaCoroutine = 0;
127508  }else{
127509    sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
127510  }
127511  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
127512  sqlite3VdbeJumpHere(v, addrTop);
127513  sqlite3ReleaseTempReg(pParse, regRecord);
127514  sqlite3ExprCachePop(pParse);
127515
127516  /* Jump here when skipping the initialization */
127517  sqlite3VdbeJumpHere(v, addrInit);
127518
127519end_auto_index_create:
127520  sqlite3ExprDelete(pParse->db, pPartial);
127521}
127522#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
127523
127524#ifndef SQLITE_OMIT_VIRTUALTABLE
127525/*
127526** Allocate and populate an sqlite3_index_info structure. It is the
127527** responsibility of the caller to eventually release the structure
127528** by passing the pointer returned by this function to sqlite3_free().
127529*/
127530static sqlite3_index_info *allocateIndexInfo(
127531  Parse *pParse,
127532  WhereClause *pWC,
127533  Bitmask mUnusable,              /* Ignore terms with these prereqs */
127534  struct SrcList_item *pSrc,
127535  ExprList *pOrderBy
127536){
127537  int i, j;
127538  int nTerm;
127539  struct sqlite3_index_constraint *pIdxCons;
127540  struct sqlite3_index_orderby *pIdxOrderBy;
127541  struct sqlite3_index_constraint_usage *pUsage;
127542  WhereTerm *pTerm;
127543  int nOrderBy;
127544  sqlite3_index_info *pIdxInfo;
127545
127546  /* Count the number of possible WHERE clause constraints referring
127547  ** to this virtual table */
127548  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
127549    if( pTerm->leftCursor != pSrc->iCursor ) continue;
127550    if( pTerm->prereqRight & mUnusable ) continue;
127551    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
127552    testcase( pTerm->eOperator & WO_IN );
127553    testcase( pTerm->eOperator & WO_ISNULL );
127554    testcase( pTerm->eOperator & WO_IS );
127555    testcase( pTerm->eOperator & WO_ALL );
127556    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
127557    if( pTerm->wtFlags & TERM_VNULL ) continue;
127558    assert( pTerm->u.leftColumn>=(-1) );
127559    nTerm++;
127560  }
127561
127562  /* If the ORDER BY clause contains only columns in the current
127563  ** virtual table then allocate space for the aOrderBy part of
127564  ** the sqlite3_index_info structure.
127565  */
127566  nOrderBy = 0;
127567  if( pOrderBy ){
127568    int n = pOrderBy->nExpr;
127569    for(i=0; i<n; i++){
127570      Expr *pExpr = pOrderBy->a[i].pExpr;
127571      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
127572    }
127573    if( i==n){
127574      nOrderBy = n;
127575    }
127576  }
127577
127578  /* Allocate the sqlite3_index_info structure
127579  */
127580  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
127581                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
127582                           + sizeof(*pIdxOrderBy)*nOrderBy );
127583  if( pIdxInfo==0 ){
127584    sqlite3ErrorMsg(pParse, "out of memory");
127585    return 0;
127586  }
127587
127588  /* Initialize the structure.  The sqlite3_index_info structure contains
127589  ** many fields that are declared "const" to prevent xBestIndex from
127590  ** changing them.  We have to do some funky casting in order to
127591  ** initialize those fields.
127592  */
127593  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
127594  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
127595  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
127596  *(int*)&pIdxInfo->nConstraint = nTerm;
127597  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
127598  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
127599  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
127600  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
127601                                                                   pUsage;
127602
127603  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
127604    u8 op;
127605    if( pTerm->leftCursor != pSrc->iCursor ) continue;
127606    if( pTerm->prereqRight & mUnusable ) continue;
127607    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
127608    testcase( pTerm->eOperator & WO_IN );
127609    testcase( pTerm->eOperator & WO_IS );
127610    testcase( pTerm->eOperator & WO_ISNULL );
127611    testcase( pTerm->eOperator & WO_ALL );
127612    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
127613    if( pTerm->wtFlags & TERM_VNULL ) continue;
127614    assert( pTerm->u.leftColumn>=(-1) );
127615    pIdxCons[j].iColumn = pTerm->u.leftColumn;
127616    pIdxCons[j].iTermOffset = i;
127617    op = (u8)pTerm->eOperator & WO_ALL;
127618    if( op==WO_IN ) op = WO_EQ;
127619    if( op==WO_MATCH ){
127620      op = pTerm->eMatchOp;
127621    }
127622    pIdxCons[j].op = op;
127623    /* The direct assignment in the previous line is possible only because
127624    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
127625    ** following asserts verify this fact. */
127626    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
127627    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
127628    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
127629    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
127630    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
127631    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
127632    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
127633    j++;
127634  }
127635  for(i=0; i<nOrderBy; i++){
127636    Expr *pExpr = pOrderBy->a[i].pExpr;
127637    pIdxOrderBy[i].iColumn = pExpr->iColumn;
127638    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
127639  }
127640
127641  return pIdxInfo;
127642}
127643
127644/*
127645** The table object reference passed as the second argument to this function
127646** must represent a virtual table. This function invokes the xBestIndex()
127647** method of the virtual table with the sqlite3_index_info object that
127648** comes in as the 3rd argument to this function.
127649**
127650** If an error occurs, pParse is populated with an error message and a
127651** non-zero value is returned. Otherwise, 0 is returned and the output
127652** part of the sqlite3_index_info structure is left populated.
127653**
127654** Whether or not an error is returned, it is the responsibility of the
127655** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
127656** that this is required.
127657*/
127658static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
127659  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
127660  int rc;
127661
127662  TRACE_IDX_INPUTS(p);
127663  rc = pVtab->pModule->xBestIndex(pVtab, p);
127664  TRACE_IDX_OUTPUTS(p);
127665
127666  if( rc!=SQLITE_OK ){
127667    if( rc==SQLITE_NOMEM ){
127668      sqlite3OomFault(pParse->db);
127669    }else if( !pVtab->zErrMsg ){
127670      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
127671    }else{
127672      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
127673    }
127674  }
127675  sqlite3_free(pVtab->zErrMsg);
127676  pVtab->zErrMsg = 0;
127677
127678#if 0
127679  /* This error is now caught by the caller.
127680  ** Search for "xBestIndex malfunction" below */
127681  for(i=0; i<p->nConstraint; i++){
127682    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
127683      sqlite3ErrorMsg(pParse,
127684          "table %s: xBestIndex returned an invalid plan", pTab->zName);
127685    }
127686  }
127687#endif
127688
127689  return pParse->nErr;
127690}
127691#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
127692
127693#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127694/*
127695** Estimate the location of a particular key among all keys in an
127696** index.  Store the results in aStat as follows:
127697**
127698**    aStat[0]      Est. number of rows less than pRec
127699**    aStat[1]      Est. number of rows equal to pRec
127700**
127701** Return the index of the sample that is the smallest sample that
127702** is greater than or equal to pRec. Note that this index is not an index
127703** into the aSample[] array - it is an index into a virtual set of samples
127704** based on the contents of aSample[] and the number of fields in record
127705** pRec.
127706*/
127707static int whereKeyStats(
127708  Parse *pParse,              /* Database connection */
127709  Index *pIdx,                /* Index to consider domain of */
127710  UnpackedRecord *pRec,       /* Vector of values to consider */
127711  int roundUp,                /* Round up if true.  Round down if false */
127712  tRowcnt *aStat              /* OUT: stats written here */
127713){
127714  IndexSample *aSample = pIdx->aSample;
127715  int iCol;                   /* Index of required stats in anEq[] etc. */
127716  int i;                      /* Index of first sample >= pRec */
127717  int iSample;                /* Smallest sample larger than or equal to pRec */
127718  int iMin = 0;               /* Smallest sample not yet tested */
127719  int iTest;                  /* Next sample to test */
127720  int res;                    /* Result of comparison operation */
127721  int nField;                 /* Number of fields in pRec */
127722  tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
127723
127724#ifndef SQLITE_DEBUG
127725  UNUSED_PARAMETER( pParse );
127726#endif
127727  assert( pRec!=0 );
127728  assert( pIdx->nSample>0 );
127729  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
127730
127731  /* Do a binary search to find the first sample greater than or equal
127732  ** to pRec. If pRec contains a single field, the set of samples to search
127733  ** is simply the aSample[] array. If the samples in aSample[] contain more
127734  ** than one fields, all fields following the first are ignored.
127735  **
127736  ** If pRec contains N fields, where N is more than one, then as well as the
127737  ** samples in aSample[] (truncated to N fields), the search also has to
127738  ** consider prefixes of those samples. For example, if the set of samples
127739  ** in aSample is:
127740  **
127741  **     aSample[0] = (a, 5)
127742  **     aSample[1] = (a, 10)
127743  **     aSample[2] = (b, 5)
127744  **     aSample[3] = (c, 100)
127745  **     aSample[4] = (c, 105)
127746  **
127747  ** Then the search space should ideally be the samples above and the
127748  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
127749  ** the code actually searches this set:
127750  **
127751  **     0: (a)
127752  **     1: (a, 5)
127753  **     2: (a, 10)
127754  **     3: (a, 10)
127755  **     4: (b)
127756  **     5: (b, 5)
127757  **     6: (c)
127758  **     7: (c, 100)
127759  **     8: (c, 105)
127760  **     9: (c, 105)
127761  **
127762  ** For each sample in the aSample[] array, N samples are present in the
127763  ** effective sample array. In the above, samples 0 and 1 are based on
127764  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
127765  **
127766  ** Often, sample i of each block of N effective samples has (i+1) fields.
127767  ** Except, each sample may be extended to ensure that it is greater than or
127768  ** equal to the previous sample in the array. For example, in the above,
127769  ** sample 2 is the first sample of a block of N samples, so at first it
127770  ** appears that it should be 1 field in size. However, that would make it
127771  ** smaller than sample 1, so the binary search would not work. As a result,
127772  ** it is extended to two fields. The duplicates that this creates do not
127773  ** cause any problems.
127774  */
127775  nField = pRec->nField;
127776  iCol = 0;
127777  iSample = pIdx->nSample * nField;
127778  do{
127779    int iSamp;                    /* Index in aSample[] of test sample */
127780    int n;                        /* Number of fields in test sample */
127781
127782    iTest = (iMin+iSample)/2;
127783    iSamp = iTest / nField;
127784    if( iSamp>0 ){
127785      /* The proposed effective sample is a prefix of sample aSample[iSamp].
127786      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
127787      ** fields that is greater than the previous effective sample.  */
127788      for(n=(iTest % nField) + 1; n<nField; n++){
127789        if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
127790      }
127791    }else{
127792      n = iTest + 1;
127793    }
127794
127795    pRec->nField = n;
127796    res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
127797    if( res<0 ){
127798      iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
127799      iMin = iTest+1;
127800    }else if( res==0 && n<nField ){
127801      iLower = aSample[iSamp].anLt[n-1];
127802      iMin = iTest+1;
127803      res = -1;
127804    }else{
127805      iSample = iTest;
127806      iCol = n-1;
127807    }
127808  }while( res && iMin<iSample );
127809  i = iSample / nField;
127810
127811#ifdef SQLITE_DEBUG
127812  /* The following assert statements check that the binary search code
127813  ** above found the right answer. This block serves no purpose other
127814  ** than to invoke the asserts.  */
127815  if( pParse->db->mallocFailed==0 ){
127816    if( res==0 ){
127817      /* If (res==0) is true, then pRec must be equal to sample i. */
127818      assert( i<pIdx->nSample );
127819      assert( iCol==nField-1 );
127820      pRec->nField = nField;
127821      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
127822           || pParse->db->mallocFailed
127823      );
127824    }else{
127825      /* Unless i==pIdx->nSample, indicating that pRec is larger than
127826      ** all samples in the aSample[] array, pRec must be smaller than the
127827      ** (iCol+1) field prefix of sample i.  */
127828      assert( i<=pIdx->nSample && i>=0 );
127829      pRec->nField = iCol+1;
127830      assert( i==pIdx->nSample
127831           || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
127832           || pParse->db->mallocFailed );
127833
127834      /* if i==0 and iCol==0, then record pRec is smaller than all samples
127835      ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
127836      ** be greater than or equal to the (iCol) field prefix of sample i.
127837      ** If (i>0), then pRec must also be greater than sample (i-1).  */
127838      if( iCol>0 ){
127839        pRec->nField = iCol;
127840        assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
127841             || pParse->db->mallocFailed );
127842      }
127843      if( i>0 ){
127844        pRec->nField = nField;
127845        assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
127846             || pParse->db->mallocFailed );
127847      }
127848    }
127849  }
127850#endif /* ifdef SQLITE_DEBUG */
127851
127852  if( res==0 ){
127853    /* Record pRec is equal to sample i */
127854    assert( iCol==nField-1 );
127855    aStat[0] = aSample[i].anLt[iCol];
127856    aStat[1] = aSample[i].anEq[iCol];
127857  }else{
127858    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
127859    ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
127860    ** is larger than all samples in the array. */
127861    tRowcnt iUpper, iGap;
127862    if( i>=pIdx->nSample ){
127863      iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
127864    }else{
127865      iUpper = aSample[i].anLt[iCol];
127866    }
127867
127868    if( iLower>=iUpper ){
127869      iGap = 0;
127870    }else{
127871      iGap = iUpper - iLower;
127872    }
127873    if( roundUp ){
127874      iGap = (iGap*2)/3;
127875    }else{
127876      iGap = iGap/3;
127877    }
127878    aStat[0] = iLower + iGap;
127879    aStat[1] = pIdx->aAvgEq[iCol];
127880  }
127881
127882  /* Restore the pRec->nField value before returning.  */
127883  pRec->nField = nField;
127884  return i;
127885}
127886#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127887
127888/*
127889** If it is not NULL, pTerm is a term that provides an upper or lower
127890** bound on a range scan. Without considering pTerm, it is estimated
127891** that the scan will visit nNew rows. This function returns the number
127892** estimated to be visited after taking pTerm into account.
127893**
127894** If the user explicitly specified a likelihood() value for this term,
127895** then the return value is the likelihood multiplied by the number of
127896** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
127897** has a likelihood of 0.50, and any other term a likelihood of 0.25.
127898*/
127899static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
127900  LogEst nRet = nNew;
127901  if( pTerm ){
127902    if( pTerm->truthProb<=0 ){
127903      nRet += pTerm->truthProb;
127904    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
127905      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
127906    }
127907  }
127908  return nRet;
127909}
127910
127911
127912#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127913/*
127914** Return the affinity for a single column of an index.
127915*/
127916static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
127917  assert( iCol>=0 && iCol<pIdx->nColumn );
127918  if( !pIdx->zColAff ){
127919    if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
127920  }
127921  return pIdx->zColAff[iCol];
127922}
127923#endif
127924
127925
127926#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127927/*
127928** This function is called to estimate the number of rows visited by a
127929** range-scan on a skip-scan index. For example:
127930**
127931**   CREATE INDEX i1 ON t1(a, b, c);
127932**   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
127933**
127934** Value pLoop->nOut is currently set to the estimated number of rows
127935** visited for scanning (a=? AND b=?). This function reduces that estimate
127936** by some factor to account for the (c BETWEEN ? AND ?) expression based
127937** on the stat4 data for the index. this scan will be peformed multiple
127938** times (once for each (a,b) combination that matches a=?) is dealt with
127939** by the caller.
127940**
127941** It does this by scanning through all stat4 samples, comparing values
127942** extracted from pLower and pUpper with the corresponding column in each
127943** sample. If L and U are the number of samples found to be less than or
127944** equal to the values extracted from pLower and pUpper respectively, and
127945** N is the total number of samples, the pLoop->nOut value is adjusted
127946** as follows:
127947**
127948**   nOut = nOut * ( min(U - L, 1) / N )
127949**
127950** If pLower is NULL, or a value cannot be extracted from the term, L is
127951** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
127952** U is set to N.
127953**
127954** Normally, this function sets *pbDone to 1 before returning. However,
127955** if no value can be extracted from either pLower or pUpper (and so the
127956** estimate of the number of rows delivered remains unchanged), *pbDone
127957** is left as is.
127958**
127959** If an error occurs, an SQLite error code is returned. Otherwise,
127960** SQLITE_OK.
127961*/
127962static int whereRangeSkipScanEst(
127963  Parse *pParse,       /* Parsing & code generating context */
127964  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
127965  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
127966  WhereLoop *pLoop,    /* Update the .nOut value of this loop */
127967  int *pbDone          /* Set to true if at least one expr. value extracted */
127968){
127969  Index *p = pLoop->u.btree.pIndex;
127970  int nEq = pLoop->u.btree.nEq;
127971  sqlite3 *db = pParse->db;
127972  int nLower = -1;
127973  int nUpper = p->nSample+1;
127974  int rc = SQLITE_OK;
127975  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
127976  CollSeq *pColl;
127977
127978  sqlite3_value *p1 = 0;          /* Value extracted from pLower */
127979  sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
127980  sqlite3_value *pVal = 0;        /* Value extracted from record */
127981
127982  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
127983  if( pLower ){
127984    rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
127985    nLower = 0;
127986  }
127987  if( pUpper && rc==SQLITE_OK ){
127988    rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
127989    nUpper = p2 ? 0 : p->nSample;
127990  }
127991
127992  if( p1 || p2 ){
127993    int i;
127994    int nDiff;
127995    for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
127996      rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
127997      if( rc==SQLITE_OK && p1 ){
127998        int res = sqlite3MemCompare(p1, pVal, pColl);
127999        if( res>=0 ) nLower++;
128000      }
128001      if( rc==SQLITE_OK && p2 ){
128002        int res = sqlite3MemCompare(p2, pVal, pColl);
128003        if( res>=0 ) nUpper++;
128004      }
128005    }
128006    nDiff = (nUpper - nLower);
128007    if( nDiff<=0 ) nDiff = 1;
128008
128009    /* If there is both an upper and lower bound specified, and the
128010    ** comparisons indicate that they are close together, use the fallback
128011    ** method (assume that the scan visits 1/64 of the rows) for estimating
128012    ** the number of rows visited. Otherwise, estimate the number of rows
128013    ** using the method described in the header comment for this function. */
128014    if( nDiff!=1 || pUpper==0 || pLower==0 ){
128015      int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
128016      pLoop->nOut -= nAdjust;
128017      *pbDone = 1;
128018      WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
128019                           nLower, nUpper, nAdjust*-1, pLoop->nOut));
128020    }
128021
128022  }else{
128023    assert( *pbDone==0 );
128024  }
128025
128026  sqlite3ValueFree(p1);
128027  sqlite3ValueFree(p2);
128028  sqlite3ValueFree(pVal);
128029
128030  return rc;
128031}
128032#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128033
128034/*
128035** This function is used to estimate the number of rows that will be visited
128036** by scanning an index for a range of values. The range may have an upper
128037** bound, a lower bound, or both. The WHERE clause terms that set the upper
128038** and lower bounds are represented by pLower and pUpper respectively. For
128039** example, assuming that index p is on t1(a):
128040**
128041**   ... FROM t1 WHERE a > ? AND a < ? ...
128042**                    |_____|   |_____|
128043**                       |         |
128044**                     pLower    pUpper
128045**
128046** If either of the upper or lower bound is not present, then NULL is passed in
128047** place of the corresponding WhereTerm.
128048**
128049** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
128050** column subject to the range constraint. Or, equivalently, the number of
128051** equality constraints optimized by the proposed index scan. For example,
128052** assuming index p is on t1(a, b), and the SQL query is:
128053**
128054**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
128055**
128056** then nEq is set to 1 (as the range restricted column, b, is the second
128057** left-most column of the index). Or, if the query is:
128058**
128059**   ... FROM t1 WHERE a > ? AND a < ? ...
128060**
128061** then nEq is set to 0.
128062**
128063** When this function is called, *pnOut is set to the sqlite3LogEst() of the
128064** number of rows that the index scan is expected to visit without
128065** considering the range constraints. If nEq is 0, then *pnOut is the number of
128066** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
128067** to account for the range constraints pLower and pUpper.
128068**
128069** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
128070** used, a single range inequality reduces the search space by a factor of 4.
128071** and a pair of constraints (x>? AND x<?) reduces the expected number of
128072** rows visited by a factor of 64.
128073*/
128074static int whereRangeScanEst(
128075  Parse *pParse,       /* Parsing & code generating context */
128076  WhereLoopBuilder *pBuilder,
128077  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
128078  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
128079  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
128080){
128081  int rc = SQLITE_OK;
128082  int nOut = pLoop->nOut;
128083  LogEst nNew;
128084
128085#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128086  Index *p = pLoop->u.btree.pIndex;
128087  int nEq = pLoop->u.btree.nEq;
128088
128089  if( p->nSample>0 && nEq<p->nSampleCol ){
128090    if( nEq==pBuilder->nRecValid ){
128091      UnpackedRecord *pRec = pBuilder->pRec;
128092      tRowcnt a[2];
128093      u8 aff;
128094
128095      /* Variable iLower will be set to the estimate of the number of rows in
128096      ** the index that are less than the lower bound of the range query. The
128097      ** lower bound being the concatenation of $P and $L, where $P is the
128098      ** key-prefix formed by the nEq values matched against the nEq left-most
128099      ** columns of the index, and $L is the value in pLower.
128100      **
128101      ** Or, if pLower is NULL or $L cannot be extracted from it (because it
128102      ** is not a simple variable or literal value), the lower bound of the
128103      ** range is $P. Due to a quirk in the way whereKeyStats() works, even
128104      ** if $L is available, whereKeyStats() is called for both ($P) and
128105      ** ($P:$L) and the larger of the two returned values is used.
128106      **
128107      ** Similarly, iUpper is to be set to the estimate of the number of rows
128108      ** less than the upper bound of the range query. Where the upper bound
128109      ** is either ($P) or ($P:$U). Again, even if $U is available, both values
128110      ** of iUpper are requested of whereKeyStats() and the smaller used.
128111      **
128112      ** The number of rows between the two bounds is then just iUpper-iLower.
128113      */
128114      tRowcnt iLower;     /* Rows less than the lower bound */
128115      tRowcnt iUpper;     /* Rows less than the upper bound */
128116      int iLwrIdx = -2;   /* aSample[] for the lower bound */
128117      int iUprIdx = -1;   /* aSample[] for the upper bound */
128118
128119      if( pRec ){
128120        testcase( pRec->nField!=pBuilder->nRecValid );
128121        pRec->nField = pBuilder->nRecValid;
128122      }
128123      aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
128124      assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
128125      /* Determine iLower and iUpper using ($P) only. */
128126      if( nEq==0 ){
128127        iLower = 0;
128128        iUpper = p->nRowEst0;
128129      }else{
128130        /* Note: this call could be optimized away - since the same values must
128131        ** have been requested when testing key $P in whereEqualScanEst().  */
128132        whereKeyStats(pParse, p, pRec, 0, a);
128133        iLower = a[0];
128134        iUpper = a[0] + a[1];
128135      }
128136
128137      assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
128138      assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
128139      assert( p->aSortOrder!=0 );
128140      if( p->aSortOrder[nEq] ){
128141        /* The roles of pLower and pUpper are swapped for a DESC index */
128142        SWAP(WhereTerm*, pLower, pUpper);
128143      }
128144
128145      /* If possible, improve on the iLower estimate using ($P:$L). */
128146      if( pLower ){
128147        int bOk;                    /* True if value is extracted from pExpr */
128148        Expr *pExpr = pLower->pExpr->pRight;
128149        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
128150        if( rc==SQLITE_OK && bOk ){
128151          tRowcnt iNew;
128152          iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
128153          iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
128154          if( iNew>iLower ) iLower = iNew;
128155          nOut--;
128156          pLower = 0;
128157        }
128158      }
128159
128160      /* If possible, improve on the iUpper estimate using ($P:$U). */
128161      if( pUpper ){
128162        int bOk;                    /* True if value is extracted from pExpr */
128163        Expr *pExpr = pUpper->pExpr->pRight;
128164        rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
128165        if( rc==SQLITE_OK && bOk ){
128166          tRowcnt iNew;
128167          iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
128168          iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
128169          if( iNew<iUpper ) iUpper = iNew;
128170          nOut--;
128171          pUpper = 0;
128172        }
128173      }
128174
128175      pBuilder->pRec = pRec;
128176      if( rc==SQLITE_OK ){
128177        if( iUpper>iLower ){
128178          nNew = sqlite3LogEst(iUpper - iLower);
128179          /* TUNING:  If both iUpper and iLower are derived from the same
128180          ** sample, then assume they are 4x more selective.  This brings
128181          ** the estimated selectivity more in line with what it would be
128182          ** if estimated without the use of STAT3/4 tables. */
128183          if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
128184        }else{
128185          nNew = 10;        assert( 10==sqlite3LogEst(2) );
128186        }
128187        if( nNew<nOut ){
128188          nOut = nNew;
128189        }
128190        WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
128191                           (u32)iLower, (u32)iUpper, nOut));
128192      }
128193    }else{
128194      int bDone = 0;
128195      rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
128196      if( bDone ) return rc;
128197    }
128198  }
128199#else
128200  UNUSED_PARAMETER(pParse);
128201  UNUSED_PARAMETER(pBuilder);
128202  assert( pLower || pUpper );
128203#endif
128204  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
128205  nNew = whereRangeAdjust(pLower, nOut);
128206  nNew = whereRangeAdjust(pUpper, nNew);
128207
128208  /* TUNING: If there is both an upper and lower limit and neither limit
128209  ** has an application-defined likelihood(), assume the range is
128210  ** reduced by an additional 75%. This means that, by default, an open-ended
128211  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
128212  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
128213  ** match 1/64 of the index. */
128214  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
128215    nNew -= 20;
128216  }
128217
128218  nOut -= (pLower!=0) + (pUpper!=0);
128219  if( nNew<10 ) nNew = 10;
128220  if( nNew<nOut ) nOut = nNew;
128221#if defined(WHERETRACE_ENABLED)
128222  if( pLoop->nOut>nOut ){
128223    WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
128224                    pLoop->nOut, nOut));
128225  }
128226#endif
128227  pLoop->nOut = (LogEst)nOut;
128228  return rc;
128229}
128230
128231#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128232/*
128233** Estimate the number of rows that will be returned based on
128234** an equality constraint x=VALUE and where that VALUE occurs in
128235** the histogram data.  This only works when x is the left-most
128236** column of an index and sqlite_stat3 histogram data is available
128237** for that index.  When pExpr==NULL that means the constraint is
128238** "x IS NULL" instead of "x=VALUE".
128239**
128240** Write the estimated row count into *pnRow and return SQLITE_OK.
128241** If unable to make an estimate, leave *pnRow unchanged and return
128242** non-zero.
128243**
128244** This routine can fail if it is unable to load a collating sequence
128245** required for string comparison, or if unable to allocate memory
128246** for a UTF conversion required for comparison.  The error is stored
128247** in the pParse structure.
128248*/
128249static int whereEqualScanEst(
128250  Parse *pParse,       /* Parsing & code generating context */
128251  WhereLoopBuilder *pBuilder,
128252  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
128253  tRowcnt *pnRow       /* Write the revised row estimate here */
128254){
128255  Index *p = pBuilder->pNew->u.btree.pIndex;
128256  int nEq = pBuilder->pNew->u.btree.nEq;
128257  UnpackedRecord *pRec = pBuilder->pRec;
128258  u8 aff;                   /* Column affinity */
128259  int rc;                   /* Subfunction return code */
128260  tRowcnt a[2];             /* Statistics */
128261  int bOk;
128262
128263  assert( nEq>=1 );
128264  assert( nEq<=p->nColumn );
128265  assert( p->aSample!=0 );
128266  assert( p->nSample>0 );
128267  assert( pBuilder->nRecValid<nEq );
128268
128269  /* If values are not available for all fields of the index to the left
128270  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
128271  if( pBuilder->nRecValid<(nEq-1) ){
128272    return SQLITE_NOTFOUND;
128273  }
128274
128275  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
128276  ** below would return the same value.  */
128277  if( nEq>=p->nColumn ){
128278    *pnRow = 1;
128279    return SQLITE_OK;
128280  }
128281
128282  aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
128283  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
128284  pBuilder->pRec = pRec;
128285  if( rc!=SQLITE_OK ) return rc;
128286  if( bOk==0 ) return SQLITE_NOTFOUND;
128287  pBuilder->nRecValid = nEq;
128288
128289  whereKeyStats(pParse, p, pRec, 0, a);
128290  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
128291                   p->zName, nEq-1, (int)a[1]));
128292  *pnRow = a[1];
128293
128294  return rc;
128295}
128296#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128297
128298#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128299/*
128300** Estimate the number of rows that will be returned based on
128301** an IN constraint where the right-hand side of the IN operator
128302** is a list of values.  Example:
128303**
128304**        WHERE x IN (1,2,3,4)
128305**
128306** Write the estimated row count into *pnRow and return SQLITE_OK.
128307** If unable to make an estimate, leave *pnRow unchanged and return
128308** non-zero.
128309**
128310** This routine can fail if it is unable to load a collating sequence
128311** required for string comparison, or if unable to allocate memory
128312** for a UTF conversion required for comparison.  The error is stored
128313** in the pParse structure.
128314*/
128315static int whereInScanEst(
128316  Parse *pParse,       /* Parsing & code generating context */
128317  WhereLoopBuilder *pBuilder,
128318  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
128319  tRowcnt *pnRow       /* Write the revised row estimate here */
128320){
128321  Index *p = pBuilder->pNew->u.btree.pIndex;
128322  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
128323  int nRecValid = pBuilder->nRecValid;
128324  int rc = SQLITE_OK;     /* Subfunction return code */
128325  tRowcnt nEst;           /* Number of rows for a single term */
128326  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
128327  int i;                  /* Loop counter */
128328
128329  assert( p->aSample!=0 );
128330  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
128331    nEst = nRow0;
128332    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
128333    nRowEst += nEst;
128334    pBuilder->nRecValid = nRecValid;
128335  }
128336
128337  if( rc==SQLITE_OK ){
128338    if( nRowEst > nRow0 ) nRowEst = nRow0;
128339    *pnRow = nRowEst;
128340    WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
128341  }
128342  assert( pBuilder->nRecValid==nRecValid );
128343  return rc;
128344}
128345#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128346
128347
128348#ifdef WHERETRACE_ENABLED
128349/*
128350** Print the content of a WhereTerm object
128351*/
128352static void whereTermPrint(WhereTerm *pTerm, int iTerm){
128353  if( pTerm==0 ){
128354    sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
128355  }else{
128356    char zType[4];
128357    char zLeft[50];
128358    memcpy(zType, "...", 4);
128359    if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
128360    if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
128361    if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
128362    if( pTerm->eOperator & WO_SINGLE ){
128363      sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
128364                       pTerm->leftCursor, pTerm->u.leftColumn);
128365    }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
128366      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
128367                       pTerm->u.pOrInfo->indexable);
128368    }else{
128369      sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
128370    }
128371    sqlite3DebugPrintf(
128372       "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x\n",
128373       iTerm, pTerm, zType, zLeft, pTerm->truthProb,
128374       pTerm->eOperator, pTerm->wtFlags);
128375    sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
128376  }
128377}
128378#endif
128379
128380#ifdef WHERETRACE_ENABLED
128381/*
128382** Show the complete content of a WhereClause
128383*/
128384SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
128385  int i;
128386  for(i=0; i<pWC->nTerm; i++){
128387    whereTermPrint(&pWC->a[i], i);
128388  }
128389}
128390#endif
128391
128392#ifdef WHERETRACE_ENABLED
128393/*
128394** Print a WhereLoop object for debugging purposes
128395*/
128396static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
128397  WhereInfo *pWInfo = pWC->pWInfo;
128398  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
128399  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
128400  Table *pTab = pItem->pTab;
128401  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
128402  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
128403                     p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
128404  sqlite3DebugPrintf(" %12s",
128405                     pItem->zAlias ? pItem->zAlias : pTab->zName);
128406  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
128407    const char *zName;
128408    if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
128409      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
128410        int i = sqlite3Strlen30(zName) - 1;
128411        while( zName[i]!='_' ) i--;
128412        zName += i;
128413      }
128414      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
128415    }else{
128416      sqlite3DebugPrintf("%20s","");
128417    }
128418  }else{
128419    char *z;
128420    if( p->u.vtab.idxStr ){
128421      z = sqlite3_mprintf("(%d,\"%s\",%x)",
128422                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
128423    }else{
128424      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
128425    }
128426    sqlite3DebugPrintf(" %-19s", z);
128427    sqlite3_free(z);
128428  }
128429  if( p->wsFlags & WHERE_SKIPSCAN ){
128430    sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
128431  }else{
128432    sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
128433  }
128434  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
128435  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
128436    int i;
128437    for(i=0; i<p->nLTerm; i++){
128438      whereTermPrint(p->aLTerm[i], i);
128439    }
128440  }
128441}
128442#endif
128443
128444/*
128445** Convert bulk memory into a valid WhereLoop that can be passed
128446** to whereLoopClear harmlessly.
128447*/
128448static void whereLoopInit(WhereLoop *p){
128449  p->aLTerm = p->aLTermSpace;
128450  p->nLTerm = 0;
128451  p->nLSlot = ArraySize(p->aLTermSpace);
128452  p->wsFlags = 0;
128453}
128454
128455/*
128456** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
128457*/
128458static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
128459  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
128460    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
128461      sqlite3_free(p->u.vtab.idxStr);
128462      p->u.vtab.needFree = 0;
128463      p->u.vtab.idxStr = 0;
128464    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
128465      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
128466      sqlite3DbFree(db, p->u.btree.pIndex);
128467      p->u.btree.pIndex = 0;
128468    }
128469  }
128470}
128471
128472/*
128473** Deallocate internal memory used by a WhereLoop object
128474*/
128475static void whereLoopClear(sqlite3 *db, WhereLoop *p){
128476  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
128477  whereLoopClearUnion(db, p);
128478  whereLoopInit(p);
128479}
128480
128481/*
128482** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
128483*/
128484static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
128485  WhereTerm **paNew;
128486  if( p->nLSlot>=n ) return SQLITE_OK;
128487  n = (n+7)&~7;
128488  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
128489  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
128490  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
128491  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
128492  p->aLTerm = paNew;
128493  p->nLSlot = n;
128494  return SQLITE_OK;
128495}
128496
128497/*
128498** Transfer content from the second pLoop into the first.
128499*/
128500static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
128501  whereLoopClearUnion(db, pTo);
128502  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
128503    memset(&pTo->u, 0, sizeof(pTo->u));
128504    return SQLITE_NOMEM_BKPT;
128505  }
128506  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
128507  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
128508  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
128509    pFrom->u.vtab.needFree = 0;
128510  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
128511    pFrom->u.btree.pIndex = 0;
128512  }
128513  return SQLITE_OK;
128514}
128515
128516/*
128517** Delete a WhereLoop object
128518*/
128519static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
128520  whereLoopClear(db, p);
128521  sqlite3DbFree(db, p);
128522}
128523
128524/*
128525** Free a WhereInfo structure
128526*/
128527static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
128528  if( ALWAYS(pWInfo) ){
128529    int i;
128530    for(i=0; i<pWInfo->nLevel; i++){
128531      WhereLevel *pLevel = &pWInfo->a[i];
128532      if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
128533        sqlite3DbFree(db, pLevel->u.in.aInLoop);
128534      }
128535    }
128536    sqlite3WhereClauseClear(&pWInfo->sWC);
128537    while( pWInfo->pLoops ){
128538      WhereLoop *p = pWInfo->pLoops;
128539      pWInfo->pLoops = p->pNextLoop;
128540      whereLoopDelete(db, p);
128541    }
128542    sqlite3DbFree(db, pWInfo);
128543  }
128544}
128545
128546/*
128547** Return TRUE if all of the following are true:
128548**
128549**   (1)  X has the same or lower cost that Y
128550**   (2)  X is a proper subset of Y
128551**   (3)  X skips at least as many columns as Y
128552**
128553** By "proper subset" we mean that X uses fewer WHERE clause terms
128554** than Y and that every WHERE clause term used by X is also used
128555** by Y.
128556**
128557** If X is a proper subset of Y then Y is a better choice and ought
128558** to have a lower cost.  This routine returns TRUE when that cost
128559** relationship is inverted and needs to be adjusted.  The third rule
128560** was added because if X uses skip-scan less than Y it still might
128561** deserve a lower cost even if it is a proper subset of Y.
128562*/
128563static int whereLoopCheaperProperSubset(
128564  const WhereLoop *pX,       /* First WhereLoop to compare */
128565  const WhereLoop *pY        /* Compare against this WhereLoop */
128566){
128567  int i, j;
128568  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
128569    return 0; /* X is not a subset of Y */
128570  }
128571  if( pY->nSkip > pX->nSkip ) return 0;
128572  if( pX->rRun >= pY->rRun ){
128573    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
128574    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
128575  }
128576  for(i=pX->nLTerm-1; i>=0; i--){
128577    if( pX->aLTerm[i]==0 ) continue;
128578    for(j=pY->nLTerm-1; j>=0; j--){
128579      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
128580    }
128581    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
128582  }
128583  return 1;  /* All conditions meet */
128584}
128585
128586/*
128587** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
128588** that:
128589**
128590**   (1) pTemplate costs less than any other WhereLoops that are a proper
128591**       subset of pTemplate
128592**
128593**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
128594**       is a proper subset.
128595**
128596** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
128597** WHERE clause terms than Y and that every WHERE clause term used by X is
128598** also used by Y.
128599*/
128600static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
128601  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
128602  for(; p; p=p->pNextLoop){
128603    if( p->iTab!=pTemplate->iTab ) continue;
128604    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
128605    if( whereLoopCheaperProperSubset(p, pTemplate) ){
128606      /* Adjust pTemplate cost downward so that it is cheaper than its
128607      ** subset p. */
128608      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
128609                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
128610      pTemplate->rRun = p->rRun;
128611      pTemplate->nOut = p->nOut - 1;
128612    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
128613      /* Adjust pTemplate cost upward so that it is costlier than p since
128614      ** pTemplate is a proper subset of p */
128615      WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
128616                       pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
128617      pTemplate->rRun = p->rRun;
128618      pTemplate->nOut = p->nOut + 1;
128619    }
128620  }
128621}
128622
128623/*
128624** Search the list of WhereLoops in *ppPrev looking for one that can be
128625** supplanted by pTemplate.
128626**
128627** Return NULL if the WhereLoop list contains an entry that can supplant
128628** pTemplate, in other words if pTemplate does not belong on the list.
128629**
128630** If pX is a WhereLoop that pTemplate can supplant, then return the
128631** link that points to pX.
128632**
128633** If pTemplate cannot supplant any existing element of the list but needs
128634** to be added to the list, then return a pointer to the tail of the list.
128635*/
128636static WhereLoop **whereLoopFindLesser(
128637  WhereLoop **ppPrev,
128638  const WhereLoop *pTemplate
128639){
128640  WhereLoop *p;
128641  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
128642    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
128643      /* If either the iTab or iSortIdx values for two WhereLoop are different
128644      ** then those WhereLoops need to be considered separately.  Neither is
128645      ** a candidate to replace the other. */
128646      continue;
128647    }
128648    /* In the current implementation, the rSetup value is either zero
128649    ** or the cost of building an automatic index (NlogN) and the NlogN
128650    ** is the same for compatible WhereLoops. */
128651    assert( p->rSetup==0 || pTemplate->rSetup==0
128652                 || p->rSetup==pTemplate->rSetup );
128653
128654    /* whereLoopAddBtree() always generates and inserts the automatic index
128655    ** case first.  Hence compatible candidate WhereLoops never have a larger
128656    ** rSetup. Call this SETUP-INVARIANT */
128657    assert( p->rSetup>=pTemplate->rSetup );
128658
128659    /* Any loop using an appliation-defined index (or PRIMARY KEY or
128660    ** UNIQUE constraint) with one or more == constraints is better
128661    ** than an automatic index. Unless it is a skip-scan. */
128662    if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
128663     && (pTemplate->nSkip)==0
128664     && (pTemplate->wsFlags & WHERE_INDEXED)!=0
128665     && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
128666     && (p->prereq & pTemplate->prereq)==pTemplate->prereq
128667    ){
128668      break;
128669    }
128670
128671    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
128672    ** discarded.  WhereLoop p is better if:
128673    **   (1)  p has no more dependencies than pTemplate, and
128674    **   (2)  p has an equal or lower cost than pTemplate
128675    */
128676    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
128677     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
128678     && p->rRun<=pTemplate->rRun                      /* (2b) */
128679     && p->nOut<=pTemplate->nOut                      /* (2c) */
128680    ){
128681      return 0;  /* Discard pTemplate */
128682    }
128683
128684    /* If pTemplate is always better than p, then cause p to be overwritten
128685    ** with pTemplate.  pTemplate is better than p if:
128686    **   (1)  pTemplate has no more dependences than p, and
128687    **   (2)  pTemplate has an equal or lower cost than p.
128688    */
128689    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
128690     && p->rRun>=pTemplate->rRun                             /* (2a) */
128691     && p->nOut>=pTemplate->nOut                             /* (2b) */
128692    ){
128693      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
128694      break;   /* Cause p to be overwritten by pTemplate */
128695    }
128696  }
128697  return ppPrev;
128698}
128699
128700/*
128701** Insert or replace a WhereLoop entry using the template supplied.
128702**
128703** An existing WhereLoop entry might be overwritten if the new template
128704** is better and has fewer dependencies.  Or the template will be ignored
128705** and no insert will occur if an existing WhereLoop is faster and has
128706** fewer dependencies than the template.  Otherwise a new WhereLoop is
128707** added based on the template.
128708**
128709** If pBuilder->pOrSet is not NULL then we care about only the
128710** prerequisites and rRun and nOut costs of the N best loops.  That
128711** information is gathered in the pBuilder->pOrSet object.  This special
128712** processing mode is used only for OR clause processing.
128713**
128714** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
128715** still might overwrite similar loops with the new template if the
128716** new template is better.  Loops may be overwritten if the following
128717** conditions are met:
128718**
128719**    (1)  They have the same iTab.
128720**    (2)  They have the same iSortIdx.
128721**    (3)  The template has same or fewer dependencies than the current loop
128722**    (4)  The template has the same or lower cost than the current loop
128723*/
128724static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
128725  WhereLoop **ppPrev, *p;
128726  WhereInfo *pWInfo = pBuilder->pWInfo;
128727  sqlite3 *db = pWInfo->pParse->db;
128728  int rc;
128729
128730  /* If pBuilder->pOrSet is defined, then only keep track of the costs
128731  ** and prereqs.
128732  */
128733  if( pBuilder->pOrSet!=0 ){
128734    if( pTemplate->nLTerm ){
128735#if WHERETRACE_ENABLED
128736      u16 n = pBuilder->pOrSet->n;
128737      int x =
128738#endif
128739      whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
128740                                    pTemplate->nOut);
128741#if WHERETRACE_ENABLED /* 0x8 */
128742      if( sqlite3WhereTrace & 0x8 ){
128743        sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
128744        whereLoopPrint(pTemplate, pBuilder->pWC);
128745      }
128746#endif
128747    }
128748    return SQLITE_OK;
128749  }
128750
128751  /* Look for an existing WhereLoop to replace with pTemplate
128752  */
128753  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
128754  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
128755
128756  if( ppPrev==0 ){
128757    /* There already exists a WhereLoop on the list that is better
128758    ** than pTemplate, so just ignore pTemplate */
128759#if WHERETRACE_ENABLED /* 0x8 */
128760    if( sqlite3WhereTrace & 0x8 ){
128761      sqlite3DebugPrintf("   skip: ");
128762      whereLoopPrint(pTemplate, pBuilder->pWC);
128763    }
128764#endif
128765    return SQLITE_OK;
128766  }else{
128767    p = *ppPrev;
128768  }
128769
128770  /* If we reach this point it means that either p[] should be overwritten
128771  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
128772  ** WhereLoop and insert it.
128773  */
128774#if WHERETRACE_ENABLED /* 0x8 */
128775  if( sqlite3WhereTrace & 0x8 ){
128776    if( p!=0 ){
128777      sqlite3DebugPrintf("replace: ");
128778      whereLoopPrint(p, pBuilder->pWC);
128779    }
128780    sqlite3DebugPrintf("    add: ");
128781    whereLoopPrint(pTemplate, pBuilder->pWC);
128782  }
128783#endif
128784  if( p==0 ){
128785    /* Allocate a new WhereLoop to add to the end of the list */
128786    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
128787    if( p==0 ) return SQLITE_NOMEM_BKPT;
128788    whereLoopInit(p);
128789    p->pNextLoop = 0;
128790  }else{
128791    /* We will be overwriting WhereLoop p[].  But before we do, first
128792    ** go through the rest of the list and delete any other entries besides
128793    ** p[] that are also supplated by pTemplate */
128794    WhereLoop **ppTail = &p->pNextLoop;
128795    WhereLoop *pToDel;
128796    while( *ppTail ){
128797      ppTail = whereLoopFindLesser(ppTail, pTemplate);
128798      if( ppTail==0 ) break;
128799      pToDel = *ppTail;
128800      if( pToDel==0 ) break;
128801      *ppTail = pToDel->pNextLoop;
128802#if WHERETRACE_ENABLED /* 0x8 */
128803      if( sqlite3WhereTrace & 0x8 ){
128804        sqlite3DebugPrintf(" delete: ");
128805        whereLoopPrint(pToDel, pBuilder->pWC);
128806      }
128807#endif
128808      whereLoopDelete(db, pToDel);
128809    }
128810  }
128811  rc = whereLoopXfer(db, p, pTemplate);
128812  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
128813    Index *pIndex = p->u.btree.pIndex;
128814    if( pIndex && pIndex->tnum==0 ){
128815      p->u.btree.pIndex = 0;
128816    }
128817  }
128818  return rc;
128819}
128820
128821/*
128822** Adjust the WhereLoop.nOut value downward to account for terms of the
128823** WHERE clause that reference the loop but which are not used by an
128824** index.
128825*
128826** For every WHERE clause term that is not used by the index
128827** and which has a truth probability assigned by one of the likelihood(),
128828** likely(), or unlikely() SQL functions, reduce the estimated number
128829** of output rows by the probability specified.
128830**
128831** TUNING:  For every WHERE clause term that is not used by the index
128832** and which does not have an assigned truth probability, heuristics
128833** described below are used to try to estimate the truth probability.
128834** TODO --> Perhaps this is something that could be improved by better
128835** table statistics.
128836**
128837** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
128838** value corresponds to -1 in LogEst notation, so this means decrement
128839** the WhereLoop.nOut field for every such WHERE clause term.
128840**
128841** Heuristic 2:  If there exists one or more WHERE clause terms of the
128842** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
128843** final output row estimate is no greater than 1/4 of the total number
128844** of rows in the table.  In other words, assume that x==EXPR will filter
128845** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
128846** "x" column is boolean or else -1 or 0 or 1 is a common default value
128847** on the "x" column and so in that case only cap the output row estimate
128848** at 1/2 instead of 1/4.
128849*/
128850static void whereLoopOutputAdjust(
128851  WhereClause *pWC,      /* The WHERE clause */
128852  WhereLoop *pLoop,      /* The loop to adjust downward */
128853  LogEst nRow            /* Number of rows in the entire table */
128854){
128855  WhereTerm *pTerm, *pX;
128856  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
128857  int i, j, k;
128858  LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
128859
128860  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
128861  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
128862    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
128863    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
128864    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
128865    for(j=pLoop->nLTerm-1; j>=0; j--){
128866      pX = pLoop->aLTerm[j];
128867      if( pX==0 ) continue;
128868      if( pX==pTerm ) break;
128869      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
128870    }
128871    if( j<0 ){
128872      if( pTerm->truthProb<=0 ){
128873        /* If a truth probability is specified using the likelihood() hints,
128874        ** then use the probability provided by the application. */
128875        pLoop->nOut += pTerm->truthProb;
128876      }else{
128877        /* In the absence of explicit truth probabilities, use heuristics to
128878        ** guess a reasonable truth probability. */
128879        pLoop->nOut--;
128880        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
128881          Expr *pRight = pTerm->pExpr->pRight;
128882          testcase( pTerm->pExpr->op==TK_IS );
128883          if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
128884            k = 10;
128885          }else{
128886            k = 20;
128887          }
128888          if( iReduce<k ) iReduce = k;
128889        }
128890      }
128891    }
128892  }
128893  if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
128894}
128895
128896/*
128897** Adjust the cost C by the costMult facter T.  This only occurs if
128898** compiled with -DSQLITE_ENABLE_COSTMULT
128899*/
128900#ifdef SQLITE_ENABLE_COSTMULT
128901# define ApplyCostMultiplier(C,T)  C += T
128902#else
128903# define ApplyCostMultiplier(C,T)
128904#endif
128905
128906/*
128907** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
128908** index pIndex. Try to match one more.
128909**
128910** When this function is called, pBuilder->pNew->nOut contains the
128911** number of rows expected to be visited by filtering using the nEq
128912** terms only. If it is modified, this value is restored before this
128913** function returns.
128914**
128915** If pProbe->tnum==0, that means pIndex is a fake index used for the
128916** INTEGER PRIMARY KEY.
128917*/
128918static int whereLoopAddBtreeIndex(
128919  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
128920  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
128921  Index *pProbe,                  /* An index on pSrc */
128922  LogEst nInMul                   /* log(Number of iterations due to IN) */
128923){
128924  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
128925  Parse *pParse = pWInfo->pParse;        /* Parsing context */
128926  sqlite3 *db = pParse->db;       /* Database connection malloc context */
128927  WhereLoop *pNew;                /* Template WhereLoop under construction */
128928  WhereTerm *pTerm;               /* A WhereTerm under consideration */
128929  int opMask;                     /* Valid operators for constraints */
128930  WhereScan scan;                 /* Iterator for WHERE terms */
128931  Bitmask saved_prereq;           /* Original value of pNew->prereq */
128932  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
128933  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
128934  u16 saved_nSkip;                /* Original value of pNew->nSkip */
128935  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
128936  LogEst saved_nOut;              /* Original value of pNew->nOut */
128937  int rc = SQLITE_OK;             /* Return code */
128938  LogEst rSize;                   /* Number of rows in the table */
128939  LogEst rLogSize;                /* Logarithm of table size */
128940  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
128941
128942  pNew = pBuilder->pNew;
128943  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
128944
128945  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
128946  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
128947  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
128948    opMask = WO_LT|WO_LE;
128949  }else{
128950    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
128951  }
128952  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
128953
128954  assert( pNew->u.btree.nEq<pProbe->nColumn );
128955
128956  saved_nEq = pNew->u.btree.nEq;
128957  saved_nSkip = pNew->nSkip;
128958  saved_nLTerm = pNew->nLTerm;
128959  saved_wsFlags = pNew->wsFlags;
128960  saved_prereq = pNew->prereq;
128961  saved_nOut = pNew->nOut;
128962  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
128963                        opMask, pProbe);
128964  pNew->rSetup = 0;
128965  rSize = pProbe->aiRowLogEst[0];
128966  rLogSize = estLog(rSize);
128967  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
128968    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
128969    LogEst rCostIdx;
128970    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
128971    int nIn = 0;
128972#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128973    int nRecValid = pBuilder->nRecValid;
128974#endif
128975    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
128976     && indexColumnNotNull(pProbe, saved_nEq)
128977    ){
128978      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
128979    }
128980    if( pTerm->prereqRight & pNew->maskSelf ) continue;
128981
128982    /* Do not allow the upper bound of a LIKE optimization range constraint
128983    ** to mix with a lower range bound from some other source */
128984    if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
128985
128986    /* Do not allow IS constraints from the WHERE clause to be used by the
128987    ** right table of a LEFT JOIN.  Only constraints in the ON clause are
128988    ** allowed */
128989    if( (pSrc->fg.jointype & JT_LEFT)!=0
128990     && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
128991     && (eOp & (WO_IS|WO_ISNULL))!=0
128992    ){
128993      testcase( eOp & WO_IS );
128994      testcase( eOp & WO_ISNULL );
128995      continue;
128996    }
128997
128998    pNew->wsFlags = saved_wsFlags;
128999    pNew->u.btree.nEq = saved_nEq;
129000    pNew->nLTerm = saved_nLTerm;
129001    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
129002    pNew->aLTerm[pNew->nLTerm++] = pTerm;
129003    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
129004
129005    assert( nInMul==0
129006        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
129007        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
129008        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
129009    );
129010
129011    if( eOp & WO_IN ){
129012      Expr *pExpr = pTerm->pExpr;
129013      pNew->wsFlags |= WHERE_COLUMN_IN;
129014      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
129015        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
129016        nIn = 46;  assert( 46==sqlite3LogEst(25) );
129017      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
129018        /* "x IN (value, value, ...)" */
129019        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
129020      }
129021      assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
129022                        ** changes "x IN (?)" into "x=?". */
129023
129024    }else if( eOp & (WO_EQ|WO_IS) ){
129025      int iCol = pProbe->aiColumn[saved_nEq];
129026      pNew->wsFlags |= WHERE_COLUMN_EQ;
129027      assert( saved_nEq==pNew->u.btree.nEq );
129028      if( iCol==XN_ROWID
129029       || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
129030      ){
129031        if( iCol>=0 && pProbe->uniqNotNull==0 ){
129032          pNew->wsFlags |= WHERE_UNQ_WANTED;
129033        }else{
129034          pNew->wsFlags |= WHERE_ONEROW;
129035        }
129036      }
129037    }else if( eOp & WO_ISNULL ){
129038      pNew->wsFlags |= WHERE_COLUMN_NULL;
129039    }else if( eOp & (WO_GT|WO_GE) ){
129040      testcase( eOp & WO_GT );
129041      testcase( eOp & WO_GE );
129042      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
129043      pBtm = pTerm;
129044      pTop = 0;
129045      if( pTerm->wtFlags & TERM_LIKEOPT ){
129046        /* Range contraints that come from the LIKE optimization are
129047        ** always used in pairs. */
129048        pTop = &pTerm[1];
129049        assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
129050        assert( pTop->wtFlags & TERM_LIKEOPT );
129051        assert( pTop->eOperator==WO_LT );
129052        if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
129053        pNew->aLTerm[pNew->nLTerm++] = pTop;
129054        pNew->wsFlags |= WHERE_TOP_LIMIT;
129055      }
129056    }else{
129057      assert( eOp & (WO_LT|WO_LE) );
129058      testcase( eOp & WO_LT );
129059      testcase( eOp & WO_LE );
129060      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
129061      pTop = pTerm;
129062      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
129063                     pNew->aLTerm[pNew->nLTerm-2] : 0;
129064    }
129065
129066    /* At this point pNew->nOut is set to the number of rows expected to
129067    ** be visited by the index scan before considering term pTerm, or the
129068    ** values of nIn and nInMul. In other words, assuming that all
129069    ** "x IN(...)" terms are replaced with "x = ?". This block updates
129070    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
129071    assert( pNew->nOut==saved_nOut );
129072    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
129073      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
129074      ** data, using some other estimate.  */
129075      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
129076    }else{
129077      int nEq = ++pNew->u.btree.nEq;
129078      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
129079
129080      assert( pNew->nOut==saved_nOut );
129081      if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
129082        assert( (eOp & WO_IN) || nIn==0 );
129083        testcase( eOp & WO_IN );
129084        pNew->nOut += pTerm->truthProb;
129085        pNew->nOut -= nIn;
129086      }else{
129087#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129088        tRowcnt nOut = 0;
129089        if( nInMul==0
129090         && pProbe->nSample
129091         && pNew->u.btree.nEq<=pProbe->nSampleCol
129092         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
129093        ){
129094          Expr *pExpr = pTerm->pExpr;
129095          if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
129096            testcase( eOp & WO_EQ );
129097            testcase( eOp & WO_IS );
129098            testcase( eOp & WO_ISNULL );
129099            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
129100          }else{
129101            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
129102          }
129103          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
129104          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
129105          if( nOut ){
129106            pNew->nOut = sqlite3LogEst(nOut);
129107            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
129108            pNew->nOut -= nIn;
129109          }
129110        }
129111        if( nOut==0 )
129112#endif
129113        {
129114          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
129115          if( eOp & WO_ISNULL ){
129116            /* TUNING: If there is no likelihood() value, assume that a
129117            ** "col IS NULL" expression matches twice as many rows
129118            ** as (col=?). */
129119            pNew->nOut += 10;
129120          }
129121        }
129122      }
129123    }
129124
129125    /* Set rCostIdx to the cost of visiting selected rows in index. Add
129126    ** it to pNew->rRun, which is currently set to the cost of the index
129127    ** seek only. Then, if this is a non-covering index, add the cost of
129128    ** visiting the rows in the main table.  */
129129    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
129130    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
129131    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
129132      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
129133    }
129134    ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
129135
129136    nOutUnadjusted = pNew->nOut;
129137    pNew->rRun += nInMul + nIn;
129138    pNew->nOut += nInMul + nIn;
129139    whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
129140    rc = whereLoopInsert(pBuilder, pNew);
129141
129142    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
129143      pNew->nOut = saved_nOut;
129144    }else{
129145      pNew->nOut = nOutUnadjusted;
129146    }
129147
129148    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
129149     && pNew->u.btree.nEq<pProbe->nColumn
129150    ){
129151      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
129152    }
129153    pNew->nOut = saved_nOut;
129154#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129155    pBuilder->nRecValid = nRecValid;
129156#endif
129157  }
129158  pNew->prereq = saved_prereq;
129159  pNew->u.btree.nEq = saved_nEq;
129160  pNew->nSkip = saved_nSkip;
129161  pNew->wsFlags = saved_wsFlags;
129162  pNew->nOut = saved_nOut;
129163  pNew->nLTerm = saved_nLTerm;
129164
129165  /* Consider using a skip-scan if there are no WHERE clause constraints
129166  ** available for the left-most terms of the index, and if the average
129167  ** number of repeats in the left-most terms is at least 18.
129168  **
129169  ** The magic number 18 is selected on the basis that scanning 17 rows
129170  ** is almost always quicker than an index seek (even though if the index
129171  ** contains fewer than 2^17 rows we assume otherwise in other parts of
129172  ** the code). And, even if it is not, it should not be too much slower.
129173  ** On the other hand, the extra seeks could end up being significantly
129174  ** more expensive.  */
129175  assert( 42==sqlite3LogEst(18) );
129176  if( saved_nEq==saved_nSkip
129177   && saved_nEq+1<pProbe->nKeyCol
129178   && pProbe->noSkipScan==0
129179   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
129180   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
129181  ){
129182    LogEst nIter;
129183    pNew->u.btree.nEq++;
129184    pNew->nSkip++;
129185    pNew->aLTerm[pNew->nLTerm++] = 0;
129186    pNew->wsFlags |= WHERE_SKIPSCAN;
129187    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
129188    pNew->nOut -= nIter;
129189    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
129190    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
129191    nIter += 5;
129192    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
129193    pNew->nOut = saved_nOut;
129194    pNew->u.btree.nEq = saved_nEq;
129195    pNew->nSkip = saved_nSkip;
129196    pNew->wsFlags = saved_wsFlags;
129197  }
129198
129199  return rc;
129200}
129201
129202/*
129203** Return True if it is possible that pIndex might be useful in
129204** implementing the ORDER BY clause in pBuilder.
129205**
129206** Return False if pBuilder does not contain an ORDER BY clause or
129207** if there is no way for pIndex to be useful in implementing that
129208** ORDER BY clause.
129209*/
129210static int indexMightHelpWithOrderBy(
129211  WhereLoopBuilder *pBuilder,
129212  Index *pIndex,
129213  int iCursor
129214){
129215  ExprList *pOB;
129216  ExprList *aColExpr;
129217  int ii, jj;
129218
129219  if( pIndex->bUnordered ) return 0;
129220  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
129221  for(ii=0; ii<pOB->nExpr; ii++){
129222    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
129223    if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
129224      if( pExpr->iColumn<0 ) return 1;
129225      for(jj=0; jj<pIndex->nKeyCol; jj++){
129226        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
129227      }
129228    }else if( (aColExpr = pIndex->aColExpr)!=0 ){
129229      for(jj=0; jj<pIndex->nKeyCol; jj++){
129230        if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
129231        if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
129232          return 1;
129233        }
129234      }
129235    }
129236  }
129237  return 0;
129238}
129239
129240/*
129241** Return a bitmask where 1s indicate that the corresponding column of
129242** the table is used by an index.  Only the first 63 columns are considered.
129243*/
129244static Bitmask columnsInIndex(Index *pIdx){
129245  Bitmask m = 0;
129246  int j;
129247  for(j=pIdx->nColumn-1; j>=0; j--){
129248    int x = pIdx->aiColumn[j];
129249    if( x>=0 ){
129250      testcase( x==BMS-1 );
129251      testcase( x==BMS-2 );
129252      if( x<BMS-1 ) m |= MASKBIT(x);
129253    }
129254  }
129255  return m;
129256}
129257
129258/* Check to see if a partial index with pPartIndexWhere can be used
129259** in the current query.  Return true if it can be and false if not.
129260*/
129261static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
129262  int i;
129263  WhereTerm *pTerm;
129264  while( pWhere->op==TK_AND ){
129265    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
129266    pWhere = pWhere->pRight;
129267  }
129268  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
129269    Expr *pExpr = pTerm->pExpr;
129270    if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
129271     && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
129272    ){
129273      return 1;
129274    }
129275  }
129276  return 0;
129277}
129278
129279/*
129280** Add all WhereLoop objects for a single table of the join where the table
129281** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
129282** a b-tree table, not a virtual table.
129283**
129284** The costs (WhereLoop.rRun) of the b-tree loops added by this function
129285** are calculated as follows:
129286**
129287** For a full scan, assuming the table (or index) contains nRow rows:
129288**
129289**     cost = nRow * 3.0                    // full-table scan
129290**     cost = nRow * K                      // scan of covering index
129291**     cost = nRow * (K+3.0)                // scan of non-covering index
129292**
129293** where K is a value between 1.1 and 3.0 set based on the relative
129294** estimated average size of the index and table records.
129295**
129296** For an index scan, where nVisit is the number of index rows visited
129297** by the scan, and nSeek is the number of seek operations required on
129298** the index b-tree:
129299**
129300**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
129301**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
129302**
129303** Normally, nSeek is 1. nSeek values greater than 1 come about if the
129304** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
129305** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
129306**
129307** The estimated values (nRow, nVisit, nSeek) often contain a large amount
129308** of uncertainty.  For this reason, scoring is designed to pick plans that
129309** "do the least harm" if the estimates are inaccurate.  For example, a
129310** log(nRow) factor is omitted from a non-covering index scan in order to
129311** bias the scoring in favor of using an index, since the worst-case
129312** performance of using an index is far better than the worst-case performance
129313** of a full table scan.
129314*/
129315static int whereLoopAddBtree(
129316  WhereLoopBuilder *pBuilder, /* WHERE clause information */
129317  Bitmask mPrereq             /* Extra prerequesites for using this table */
129318){
129319  WhereInfo *pWInfo;          /* WHERE analysis context */
129320  Index *pProbe;              /* An index we are evaluating */
129321  Index sPk;                  /* A fake index object for the primary key */
129322  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
129323  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
129324  SrcList *pTabList;          /* The FROM clause */
129325  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
129326  WhereLoop *pNew;            /* Template WhereLoop object */
129327  int rc = SQLITE_OK;         /* Return code */
129328  int iSortIdx = 1;           /* Index number */
129329  int b;                      /* A boolean value */
129330  LogEst rSize;               /* number of rows in the table */
129331  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
129332  WhereClause *pWC;           /* The parsed WHERE clause */
129333  Table *pTab;                /* Table being queried */
129334
129335  pNew = pBuilder->pNew;
129336  pWInfo = pBuilder->pWInfo;
129337  pTabList = pWInfo->pTabList;
129338  pSrc = pTabList->a + pNew->iTab;
129339  pTab = pSrc->pTab;
129340  pWC = pBuilder->pWC;
129341  assert( !IsVirtual(pSrc->pTab) );
129342
129343  if( pSrc->pIBIndex ){
129344    /* An INDEXED BY clause specifies a particular index to use */
129345    pProbe = pSrc->pIBIndex;
129346  }else if( !HasRowid(pTab) ){
129347    pProbe = pTab->pIndex;
129348  }else{
129349    /* There is no INDEXED BY clause.  Create a fake Index object in local
129350    ** variable sPk to represent the rowid primary key index.  Make this
129351    ** fake index the first in a chain of Index objects with all of the real
129352    ** indices to follow */
129353    Index *pFirst;                  /* First of real indices on the table */
129354    memset(&sPk, 0, sizeof(Index));
129355    sPk.nKeyCol = 1;
129356    sPk.nColumn = 1;
129357    sPk.aiColumn = &aiColumnPk;
129358    sPk.aiRowLogEst = aiRowEstPk;
129359    sPk.onError = OE_Replace;
129360    sPk.pTable = pTab;
129361    sPk.szIdxRow = pTab->szTabRow;
129362    aiRowEstPk[0] = pTab->nRowLogEst;
129363    aiRowEstPk[1] = 0;
129364    pFirst = pSrc->pTab->pIndex;
129365    if( pSrc->fg.notIndexed==0 ){
129366      /* The real indices of the table are only considered if the
129367      ** NOT INDEXED qualifier is omitted from the FROM clause */
129368      sPk.pNext = pFirst;
129369    }
129370    pProbe = &sPk;
129371  }
129372  rSize = pTab->nRowLogEst;
129373  rLogSize = estLog(rSize);
129374
129375#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
129376  /* Automatic indexes */
129377  if( !pBuilder->pOrSet      /* Not part of an OR optimization */
129378   && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
129379   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
129380   && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
129381   && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
129382   && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
129383   && !pSrc->fg.isCorrelated /* Not a correlated subquery */
129384   && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
129385  ){
129386    /* Generate auto-index WhereLoops */
129387    WhereTerm *pTerm;
129388    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
129389    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
129390      if( pTerm->prereqRight & pNew->maskSelf ) continue;
129391      if( termCanDriveIndex(pTerm, pSrc, 0) ){
129392        pNew->u.btree.nEq = 1;
129393        pNew->nSkip = 0;
129394        pNew->u.btree.pIndex = 0;
129395        pNew->nLTerm = 1;
129396        pNew->aLTerm[0] = pTerm;
129397        /* TUNING: One-time cost for computing the automatic index is
129398        ** estimated to be X*N*log2(N) where N is the number of rows in
129399        ** the table being indexed and where X is 7 (LogEst=28) for normal
129400        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
129401        ** of X is smaller for views and subqueries so that the query planner
129402        ** will be more aggressive about generating automatic indexes for
129403        ** those objects, since there is no opportunity to add schema
129404        ** indexes on subqueries and views. */
129405        pNew->rSetup = rLogSize + rSize + 4;
129406        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
129407          pNew->rSetup += 24;
129408        }
129409        ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
129410        if( pNew->rSetup<0 ) pNew->rSetup = 0;
129411        /* TUNING: Each index lookup yields 20 rows in the table.  This
129412        ** is more than the usual guess of 10 rows, since we have no way
129413        ** of knowing how selective the index will ultimately be.  It would
129414        ** not be unreasonable to make this value much larger. */
129415        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
129416        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
129417        pNew->wsFlags = WHERE_AUTO_INDEX;
129418        pNew->prereq = mPrereq | pTerm->prereqRight;
129419        rc = whereLoopInsert(pBuilder, pNew);
129420      }
129421    }
129422  }
129423#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
129424
129425  /* Loop over all indices
129426  */
129427  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
129428    if( pProbe->pPartIdxWhere!=0
129429     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
129430      testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
129431      continue;  /* Partial index inappropriate for this query */
129432    }
129433    rSize = pProbe->aiRowLogEst[0];
129434    pNew->u.btree.nEq = 0;
129435    pNew->nSkip = 0;
129436    pNew->nLTerm = 0;
129437    pNew->iSortIdx = 0;
129438    pNew->rSetup = 0;
129439    pNew->prereq = mPrereq;
129440    pNew->nOut = rSize;
129441    pNew->u.btree.pIndex = pProbe;
129442    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
129443    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
129444    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
129445    if( pProbe->tnum<=0 ){
129446      /* Integer primary key index */
129447      pNew->wsFlags = WHERE_IPK;
129448
129449      /* Full table scan */
129450      pNew->iSortIdx = b ? iSortIdx : 0;
129451      /* TUNING: Cost of full table scan is (N*3.0). */
129452      pNew->rRun = rSize + 16;
129453      ApplyCostMultiplier(pNew->rRun, pTab->costMult);
129454      whereLoopOutputAdjust(pWC, pNew, rSize);
129455      rc = whereLoopInsert(pBuilder, pNew);
129456      pNew->nOut = rSize;
129457      if( rc ) break;
129458    }else{
129459      Bitmask m;
129460      if( pProbe->isCovering ){
129461        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
129462        m = 0;
129463      }else{
129464        m = pSrc->colUsed & ~columnsInIndex(pProbe);
129465        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
129466      }
129467
129468      /* Full scan via index */
129469      if( b
129470       || !HasRowid(pTab)
129471       || pProbe->pPartIdxWhere!=0
129472       || ( m==0
129473         && pProbe->bUnordered==0
129474         && (pProbe->szIdxRow<pTab->szTabRow)
129475         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
129476         && sqlite3GlobalConfig.bUseCis
129477         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
129478          )
129479      ){
129480        pNew->iSortIdx = b ? iSortIdx : 0;
129481
129482        /* The cost of visiting the index rows is N*K, where K is
129483        ** between 1.1 and 3.0, depending on the relative sizes of the
129484        ** index and table rows. */
129485        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
129486        if( m!=0 ){
129487          /* If this is a non-covering index scan, add in the cost of
129488          ** doing table lookups.  The cost will be 3x the number of
129489          ** lookups.  Take into account WHERE clause terms that can be
129490          ** satisfied using just the index, and that do not require a
129491          ** table lookup. */
129492          LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
129493          int ii;
129494          int iCur = pSrc->iCursor;
129495          WhereClause *pWC2 = &pWInfo->sWC;
129496          for(ii=0; ii<pWC2->nTerm; ii++){
129497            WhereTerm *pTerm = &pWC2->a[ii];
129498            if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
129499              break;
129500            }
129501            /* pTerm can be evaluated using just the index.  So reduce
129502            ** the expected number of table lookups accordingly */
129503            if( pTerm->truthProb<=0 ){
129504              nLookup += pTerm->truthProb;
129505            }else{
129506              nLookup--;
129507              if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
129508            }
129509          }
129510
129511          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
129512        }
129513        ApplyCostMultiplier(pNew->rRun, pTab->costMult);
129514        whereLoopOutputAdjust(pWC, pNew, rSize);
129515        rc = whereLoopInsert(pBuilder, pNew);
129516        pNew->nOut = rSize;
129517        if( rc ) break;
129518      }
129519    }
129520
129521    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
129522#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129523    sqlite3Stat4ProbeFree(pBuilder->pRec);
129524    pBuilder->nRecValid = 0;
129525    pBuilder->pRec = 0;
129526#endif
129527
129528    /* If there was an INDEXED BY clause, then only that one index is
129529    ** considered. */
129530    if( pSrc->pIBIndex ) break;
129531  }
129532  return rc;
129533}
129534
129535#ifndef SQLITE_OMIT_VIRTUALTABLE
129536
129537/*
129538** Argument pIdxInfo is already populated with all constraints that may
129539** be used by the virtual table identified by pBuilder->pNew->iTab. This
129540** function marks a subset of those constraints usable, invokes the
129541** xBestIndex method and adds the returned plan to pBuilder.
129542**
129543** A constraint is marked usable if:
129544**
129545**   * Argument mUsable indicates that its prerequisites are available, and
129546**
129547**   * It is not one of the operators specified in the mExclude mask passed
129548**     as the fourth argument (which in practice is either WO_IN or 0).
129549**
129550** Argument mPrereq is a mask of tables that must be scanned before the
129551** virtual table in question. These are added to the plans prerequisites
129552** before it is added to pBuilder.
129553**
129554** Output parameter *pbIn is set to true if the plan added to pBuilder
129555** uses one or more WO_IN terms, or false otherwise.
129556*/
129557static int whereLoopAddVirtualOne(
129558  WhereLoopBuilder *pBuilder,
129559  Bitmask mPrereq,                /* Mask of tables that must be used. */
129560  Bitmask mUsable,                /* Mask of usable tables */
129561  u16 mExclude,                   /* Exclude terms using these operators */
129562  sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
129563  int *pbIn                       /* OUT: True if plan uses an IN(...) op */
129564){
129565  WhereClause *pWC = pBuilder->pWC;
129566  struct sqlite3_index_constraint *pIdxCons;
129567  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
129568  int i;
129569  int mxTerm;
129570  int rc = SQLITE_OK;
129571  WhereLoop *pNew = pBuilder->pNew;
129572  Parse *pParse = pBuilder->pWInfo->pParse;
129573  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
129574  int nConstraint = pIdxInfo->nConstraint;
129575
129576  assert( (mUsable & mPrereq)==mPrereq );
129577  *pbIn = 0;
129578  pNew->prereq = mPrereq;
129579
129580  /* Set the usable flag on the subset of constraints identified by
129581  ** arguments mUsable and mExclude. */
129582  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
129583  for(i=0; i<nConstraint; i++, pIdxCons++){
129584    WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
129585    pIdxCons->usable = 0;
129586    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
129587     && (pTerm->eOperator & mExclude)==0
129588    ){
129589      pIdxCons->usable = 1;
129590    }
129591  }
129592
129593  /* Initialize the output fields of the sqlite3_index_info structure */
129594  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
129595  assert( pIdxInfo->needToFreeIdxStr==0 );
129596  pIdxInfo->idxStr = 0;
129597  pIdxInfo->idxNum = 0;
129598  pIdxInfo->orderByConsumed = 0;
129599  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
129600  pIdxInfo->estimatedRows = 25;
129601  pIdxInfo->idxFlags = 0;
129602  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
129603
129604  /* Invoke the virtual table xBestIndex() method */
129605  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
129606  if( rc ) return rc;
129607
129608  mxTerm = -1;
129609  assert( pNew->nLSlot>=nConstraint );
129610  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
129611  pNew->u.vtab.omitMask = 0;
129612  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
129613  for(i=0; i<nConstraint; i++, pIdxCons++){
129614    int iTerm;
129615    if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
129616      WhereTerm *pTerm;
129617      int j = pIdxCons->iTermOffset;
129618      if( iTerm>=nConstraint
129619       || j<0
129620       || j>=pWC->nTerm
129621       || pNew->aLTerm[iTerm]!=0
129622       || pIdxCons->usable==0
129623      ){
129624        rc = SQLITE_ERROR;
129625        sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
129626        return rc;
129627      }
129628      testcase( iTerm==nConstraint-1 );
129629      testcase( j==0 );
129630      testcase( j==pWC->nTerm-1 );
129631      pTerm = &pWC->a[j];
129632      pNew->prereq |= pTerm->prereqRight;
129633      assert( iTerm<pNew->nLSlot );
129634      pNew->aLTerm[iTerm] = pTerm;
129635      if( iTerm>mxTerm ) mxTerm = iTerm;
129636      testcase( iTerm==15 );
129637      testcase( iTerm==16 );
129638      if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
129639      if( (pTerm->eOperator & WO_IN)!=0 ){
129640        /* A virtual table that is constrained by an IN clause may not
129641        ** consume the ORDER BY clause because (1) the order of IN terms
129642        ** is not necessarily related to the order of output terms and
129643        ** (2) Multiple outputs from a single IN value will not merge
129644        ** together.  */
129645        pIdxInfo->orderByConsumed = 0;
129646        pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
129647        *pbIn = 1; assert( (mExclude & WO_IN)==0 );
129648      }
129649    }
129650  }
129651
129652  pNew->nLTerm = mxTerm+1;
129653  assert( pNew->nLTerm<=pNew->nLSlot );
129654  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
129655  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
129656  pIdxInfo->needToFreeIdxStr = 0;
129657  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
129658  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
129659      pIdxInfo->nOrderBy : 0);
129660  pNew->rSetup = 0;
129661  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
129662  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
129663
129664  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
129665  ** that the scan will visit at most one row. Clear it otherwise. */
129666  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
129667    pNew->wsFlags |= WHERE_ONEROW;
129668  }else{
129669    pNew->wsFlags &= ~WHERE_ONEROW;
129670  }
129671  rc = whereLoopInsert(pBuilder, pNew);
129672  if( pNew->u.vtab.needFree ){
129673    sqlite3_free(pNew->u.vtab.idxStr);
129674    pNew->u.vtab.needFree = 0;
129675  }
129676  WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
129677                      *pbIn, (sqlite3_uint64)mPrereq,
129678                      (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
129679
129680  return rc;
129681}
129682
129683
129684/*
129685** Add all WhereLoop objects for a table of the join identified by
129686** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
129687**
129688** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
129689** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
129690** entries that occur before the virtual table in the FROM clause and are
129691** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
129692** mUnusable mask contains all FROM clause entries that occur after the
129693** virtual table and are separated from it by at least one LEFT or
129694** CROSS JOIN.
129695**
129696** For example, if the query were:
129697**
129698**   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
129699**
129700** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
129701**
129702** All the tables in mPrereq must be scanned before the current virtual
129703** table. So any terms for which all prerequisites are satisfied by
129704** mPrereq may be specified as "usable" in all calls to xBestIndex.
129705** Conversely, all tables in mUnusable must be scanned after the current
129706** virtual table, so any terms for which the prerequisites overlap with
129707** mUnusable should always be configured as "not-usable" for xBestIndex.
129708*/
129709static int whereLoopAddVirtual(
129710  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
129711  Bitmask mPrereq,             /* Tables that must be scanned before this one */
129712  Bitmask mUnusable            /* Tables that must be scanned after this one */
129713){
129714  int rc = SQLITE_OK;          /* Return code */
129715  WhereInfo *pWInfo;           /* WHERE analysis context */
129716  Parse *pParse;               /* The parsing context */
129717  WhereClause *pWC;            /* The WHERE clause */
129718  struct SrcList_item *pSrc;   /* The FROM clause term to search */
129719  sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
129720  int nConstraint;             /* Number of constraints in p */
129721  int bIn;                     /* True if plan uses IN(...) operator */
129722  WhereLoop *pNew;
129723  Bitmask mBest;               /* Tables used by best possible plan */
129724
129725  assert( (mPrereq & mUnusable)==0 );
129726  pWInfo = pBuilder->pWInfo;
129727  pParse = pWInfo->pParse;
129728  pWC = pBuilder->pWC;
129729  pNew = pBuilder->pNew;
129730  pSrc = &pWInfo->pTabList->a[pNew->iTab];
129731  assert( IsVirtual(pSrc->pTab) );
129732  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy);
129733  if( p==0 ) return SQLITE_NOMEM_BKPT;
129734  pNew->rSetup = 0;
129735  pNew->wsFlags = WHERE_VIRTUALTABLE;
129736  pNew->nLTerm = 0;
129737  pNew->u.vtab.needFree = 0;
129738  nConstraint = p->nConstraint;
129739  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
129740    sqlite3DbFree(pParse->db, p);
129741    return SQLITE_NOMEM_BKPT;
129742  }
129743
129744  /* First call xBestIndex() with all constraints usable. */
129745  WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
129746  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, &bIn);
129747
129748  /* If the call to xBestIndex() with all terms enabled produced a plan
129749  ** that does not require any source tables (IOW: a plan with mBest==0),
129750  ** then there is no point in making any further calls to xBestIndex()
129751  ** since they will all return the same result (if the xBestIndex()
129752  ** implementation is sane). */
129753  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
129754    int seenZero = 0;             /* True if a plan with no prereqs seen */
129755    int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
129756    Bitmask mPrev = 0;
129757    Bitmask mBestNoIn = 0;
129758
129759    /* If the plan produced by the earlier call uses an IN(...) term, call
129760    ** xBestIndex again, this time with IN(...) terms disabled. */
129761    if( bIn ){
129762      WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
129763      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, WO_IN, p, &bIn);
129764      assert( bIn==0 );
129765      mBestNoIn = pNew->prereq & ~mPrereq;
129766      if( mBestNoIn==0 ){
129767        seenZero = 1;
129768        seenZeroNoIN = 1;
129769      }
129770    }
129771
129772    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
129773    ** in the set of terms that apply to the current virtual table.  */
129774    while( rc==SQLITE_OK ){
129775      int i;
129776      Bitmask mNext = ALLBITS;
129777      assert( mNext>0 );
129778      for(i=0; i<nConstraint; i++){
129779        Bitmask mThis = (
129780            pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
129781        );
129782        if( mThis>mPrev && mThis<mNext ) mNext = mThis;
129783      }
129784      mPrev = mNext;
129785      if( mNext==ALLBITS ) break;
129786      if( mNext==mBest || mNext==mBestNoIn ) continue;
129787      WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
129788                       (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
129789      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mNext|mPrereq, 0, p, &bIn);
129790      if( pNew->prereq==mPrereq ){
129791        seenZero = 1;
129792        if( bIn==0 ) seenZeroNoIN = 1;
129793      }
129794    }
129795
129796    /* If the calls to xBestIndex() in the above loop did not find a plan
129797    ** that requires no source tables at all (i.e. one guaranteed to be
129798    ** usable), make a call here with all source tables disabled */
129799    if( rc==SQLITE_OK && seenZero==0 ){
129800      WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
129801      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, 0, p, &bIn);
129802      if( bIn==0 ) seenZeroNoIN = 1;
129803    }
129804
129805    /* If the calls to xBestIndex() have so far failed to find a plan
129806    ** that requires no source tables at all and does not use an IN(...)
129807    ** operator, make a final call to obtain one here.  */
129808    if( rc==SQLITE_OK && seenZeroNoIN==0 ){
129809      WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
129810      rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, WO_IN, p, &bIn);
129811    }
129812  }
129813
129814  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
129815  sqlite3DbFree(pParse->db, p);
129816  return rc;
129817}
129818#endif /* SQLITE_OMIT_VIRTUALTABLE */
129819
129820/*
129821** Add WhereLoop entries to handle OR terms.  This works for either
129822** btrees or virtual tables.
129823*/
129824static int whereLoopAddOr(
129825  WhereLoopBuilder *pBuilder,
129826  Bitmask mPrereq,
129827  Bitmask mUnusable
129828){
129829  WhereInfo *pWInfo = pBuilder->pWInfo;
129830  WhereClause *pWC;
129831  WhereLoop *pNew;
129832  WhereTerm *pTerm, *pWCEnd;
129833  int rc = SQLITE_OK;
129834  int iCur;
129835  WhereClause tempWC;
129836  WhereLoopBuilder sSubBuild;
129837  WhereOrSet sSum, sCur;
129838  struct SrcList_item *pItem;
129839
129840  pWC = pBuilder->pWC;
129841  pWCEnd = pWC->a + pWC->nTerm;
129842  pNew = pBuilder->pNew;
129843  memset(&sSum, 0, sizeof(sSum));
129844  pItem = pWInfo->pTabList->a + pNew->iTab;
129845  iCur = pItem->iCursor;
129846
129847  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
129848    if( (pTerm->eOperator & WO_OR)!=0
129849     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
129850    ){
129851      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
129852      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
129853      WhereTerm *pOrTerm;
129854      int once = 1;
129855      int i, j;
129856
129857      sSubBuild = *pBuilder;
129858      sSubBuild.pOrderBy = 0;
129859      sSubBuild.pOrSet = &sCur;
129860
129861      WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
129862      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
129863        if( (pOrTerm->eOperator & WO_AND)!=0 ){
129864          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
129865        }else if( pOrTerm->leftCursor==iCur ){
129866          tempWC.pWInfo = pWC->pWInfo;
129867          tempWC.pOuter = pWC;
129868          tempWC.op = TK_AND;
129869          tempWC.nTerm = 1;
129870          tempWC.a = pOrTerm;
129871          sSubBuild.pWC = &tempWC;
129872        }else{
129873          continue;
129874        }
129875        sCur.n = 0;
129876#ifdef WHERETRACE_ENABLED
129877        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
129878                   (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
129879        if( sqlite3WhereTrace & 0x400 ){
129880          sqlite3WhereClausePrint(sSubBuild.pWC);
129881        }
129882#endif
129883#ifndef SQLITE_OMIT_VIRTUALTABLE
129884        if( IsVirtual(pItem->pTab) ){
129885          rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
129886        }else
129887#endif
129888        {
129889          rc = whereLoopAddBtree(&sSubBuild, mPrereq);
129890        }
129891        if( rc==SQLITE_OK ){
129892          rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
129893        }
129894        assert( rc==SQLITE_OK || sCur.n==0 );
129895        if( sCur.n==0 ){
129896          sSum.n = 0;
129897          break;
129898        }else if( once ){
129899          whereOrMove(&sSum, &sCur);
129900          once = 0;
129901        }else{
129902          WhereOrSet sPrev;
129903          whereOrMove(&sPrev, &sSum);
129904          sSum.n = 0;
129905          for(i=0; i<sPrev.n; i++){
129906            for(j=0; j<sCur.n; j++){
129907              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
129908                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
129909                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
129910            }
129911          }
129912        }
129913      }
129914      pNew->nLTerm = 1;
129915      pNew->aLTerm[0] = pTerm;
129916      pNew->wsFlags = WHERE_MULTI_OR;
129917      pNew->rSetup = 0;
129918      pNew->iSortIdx = 0;
129919      memset(&pNew->u, 0, sizeof(pNew->u));
129920      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
129921        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
129922        ** of all sub-scans required by the OR-scan. However, due to rounding
129923        ** errors, it may be that the cost of the OR-scan is equal to its
129924        ** most expensive sub-scan. Add the smallest possible penalty
129925        ** (equivalent to multiplying the cost by 1.07) to ensure that
129926        ** this does not happen. Otherwise, for WHERE clauses such as the
129927        ** following where there is an index on "y":
129928        **
129929        **     WHERE likelihood(x=?, 0.99) OR y=?
129930        **
129931        ** the planner may elect to "OR" together a full-table scan and an
129932        ** index lookup. And other similarly odd results.  */
129933        pNew->rRun = sSum.a[i].rRun + 1;
129934        pNew->nOut = sSum.a[i].nOut;
129935        pNew->prereq = sSum.a[i].prereq;
129936        rc = whereLoopInsert(pBuilder, pNew);
129937      }
129938      WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
129939    }
129940  }
129941  return rc;
129942}
129943
129944/*
129945** Add all WhereLoop objects for all tables
129946*/
129947static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
129948  WhereInfo *pWInfo = pBuilder->pWInfo;
129949  Bitmask mPrereq = 0;
129950  Bitmask mPrior = 0;
129951  int iTab;
129952  SrcList *pTabList = pWInfo->pTabList;
129953  struct SrcList_item *pItem;
129954  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
129955  sqlite3 *db = pWInfo->pParse->db;
129956  int rc = SQLITE_OK;
129957  WhereLoop *pNew;
129958  u8 priorJointype = 0;
129959
129960  /* Loop over the tables in the join, from left to right */
129961  pNew = pBuilder->pNew;
129962  whereLoopInit(pNew);
129963  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
129964    Bitmask mUnusable = 0;
129965    pNew->iTab = iTab;
129966    pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
129967    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
129968      /* This condition is true when pItem is the FROM clause term on the
129969      ** right-hand-side of a LEFT or CROSS JOIN.  */
129970      mPrereq = mPrior;
129971    }
129972    priorJointype = pItem->fg.jointype;
129973#ifndef SQLITE_OMIT_VIRTUALTABLE
129974    if( IsVirtual(pItem->pTab) ){
129975      struct SrcList_item *p;
129976      for(p=&pItem[1]; p<pEnd; p++){
129977        if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
129978          mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
129979        }
129980      }
129981      rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
129982    }else
129983#endif /* SQLITE_OMIT_VIRTUALTABLE */
129984    {
129985      rc = whereLoopAddBtree(pBuilder, mPrereq);
129986    }
129987    if( rc==SQLITE_OK ){
129988      rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
129989    }
129990    mPrior |= pNew->maskSelf;
129991    if( rc || db->mallocFailed ) break;
129992  }
129993
129994  whereLoopClear(db, pNew);
129995  return rc;
129996}
129997
129998/*
129999** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
130000** parameters) to see if it outputs rows in the requested ORDER BY
130001** (or GROUP BY) without requiring a separate sort operation.  Return N:
130002**
130003**   N>0:   N terms of the ORDER BY clause are satisfied
130004**   N==0:  No terms of the ORDER BY clause are satisfied
130005**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
130006**
130007** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
130008** strict.  With GROUP BY and DISTINCT the only requirement is that
130009** equivalent rows appear immediately adjacent to one another.  GROUP BY
130010** and DISTINCT do not require rows to appear in any particular order as long
130011** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
130012** the pOrderBy terms can be matched in any order.  With ORDER BY, the
130013** pOrderBy terms must be matched in strict left-to-right order.
130014*/
130015static i8 wherePathSatisfiesOrderBy(
130016  WhereInfo *pWInfo,    /* The WHERE clause */
130017  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
130018  WherePath *pPath,     /* The WherePath to check */
130019  u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
130020  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
130021  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
130022  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
130023){
130024  u8 revSet;            /* True if rev is known */
130025  u8 rev;               /* Composite sort order */
130026  u8 revIdx;            /* Index sort order */
130027  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
130028  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
130029  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
130030  u16 eqOpMask;         /* Allowed equality operators */
130031  u16 nKeyCol;          /* Number of key columns in pIndex */
130032  u16 nColumn;          /* Total number of ordered columns in the index */
130033  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
130034  int iLoop;            /* Index of WhereLoop in pPath being processed */
130035  int i, j;             /* Loop counters */
130036  int iCur;             /* Cursor number for current WhereLoop */
130037  int iColumn;          /* A column number within table iCur */
130038  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
130039  WhereTerm *pTerm;     /* A single term of the WHERE clause */
130040  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
130041  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
130042  Index *pIndex;        /* The index associated with pLoop */
130043  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
130044  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
130045  Bitmask obDone;       /* Mask of all ORDER BY terms */
130046  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
130047  Bitmask ready;              /* Mask of inner loops */
130048
130049  /*
130050  ** We say the WhereLoop is "one-row" if it generates no more than one
130051  ** row of output.  A WhereLoop is one-row if all of the following are true:
130052  **  (a) All index columns match with WHERE_COLUMN_EQ.
130053  **  (b) The index is unique
130054  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
130055  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
130056  **
130057  ** We say the WhereLoop is "order-distinct" if the set of columns from
130058  ** that WhereLoop that are in the ORDER BY clause are different for every
130059  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
130060  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
130061  ** is not order-distinct. To be order-distinct is not quite the same as being
130062  ** UNIQUE since a UNIQUE column or index can have multiple rows that
130063  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
130064  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
130065  **
130066  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
130067  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
130068  ** automatically order-distinct.
130069  */
130070
130071  assert( pOrderBy!=0 );
130072  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
130073
130074  nOrderBy = pOrderBy->nExpr;
130075  testcase( nOrderBy==BMS-1 );
130076  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
130077  isOrderDistinct = 1;
130078  obDone = MASKBIT(nOrderBy)-1;
130079  orderDistinctMask = 0;
130080  ready = 0;
130081  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
130082  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
130083  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
130084    if( iLoop>0 ) ready |= pLoop->maskSelf;
130085    if( iLoop<nLoop ){
130086      pLoop = pPath->aLoop[iLoop];
130087      if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
130088    }else{
130089      pLoop = pLast;
130090    }
130091    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
130092      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
130093      break;
130094    }
130095    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
130096
130097    /* Mark off any ORDER BY term X that is a column in the table of
130098    ** the current loop for which there is term in the WHERE
130099    ** clause of the form X IS NULL or X=? that reference only outer
130100    ** loops.
130101    */
130102    for(i=0; i<nOrderBy; i++){
130103      if( MASKBIT(i) & obSat ) continue;
130104      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
130105      if( pOBExpr->op!=TK_COLUMN ) continue;
130106      if( pOBExpr->iTable!=iCur ) continue;
130107      pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
130108                       ~ready, eqOpMask, 0);
130109      if( pTerm==0 ) continue;
130110      if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
130111        const char *z1, *z2;
130112        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
130113        if( !pColl ) pColl = db->pDfltColl;
130114        z1 = pColl->zName;
130115        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
130116        if( !pColl ) pColl = db->pDfltColl;
130117        z2 = pColl->zName;
130118        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
130119        testcase( pTerm->pExpr->op==TK_IS );
130120      }
130121      obSat |= MASKBIT(i);
130122    }
130123
130124    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
130125      if( pLoop->wsFlags & WHERE_IPK ){
130126        pIndex = 0;
130127        nKeyCol = 0;
130128        nColumn = 1;
130129      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
130130        return 0;
130131      }else{
130132        nKeyCol = pIndex->nKeyCol;
130133        nColumn = pIndex->nColumn;
130134        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
130135        assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
130136                          || !HasRowid(pIndex->pTable));
130137        isOrderDistinct = IsUniqueIndex(pIndex);
130138      }
130139
130140      /* Loop through all columns of the index and deal with the ones
130141      ** that are not constrained by == or IN.
130142      */
130143      rev = revSet = 0;
130144      distinctColumns = 0;
130145      for(j=0; j<nColumn; j++){
130146        u8 bOnce;   /* True to run the ORDER BY search loop */
130147
130148        /* Skip over == and IS and ISNULL terms.
130149        ** (Also skip IN terms when doing WHERE_ORDERBY_LIMIT processing)
130150        */
130151        if( j<pLoop->u.btree.nEq
130152         && pLoop->nSkip==0
130153         && ((i = pLoop->aLTerm[j]->eOperator) & eqOpMask)!=0
130154        ){
130155          if( i & WO_ISNULL ){
130156            testcase( isOrderDistinct );
130157            isOrderDistinct = 0;
130158          }
130159          continue;
130160        }
130161
130162        /* Get the column number in the table (iColumn) and sort order
130163        ** (revIdx) for the j-th column of the index.
130164        */
130165        if( pIndex ){
130166          iColumn = pIndex->aiColumn[j];
130167          revIdx = pIndex->aSortOrder[j];
130168          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
130169        }else{
130170          iColumn = XN_ROWID;
130171          revIdx = 0;
130172        }
130173
130174        /* An unconstrained column that might be NULL means that this
130175        ** WhereLoop is not well-ordered
130176        */
130177        if( isOrderDistinct
130178         && iColumn>=0
130179         && j>=pLoop->u.btree.nEq
130180         && pIndex->pTable->aCol[iColumn].notNull==0
130181        ){
130182          isOrderDistinct = 0;
130183        }
130184
130185        /* Find the ORDER BY term that corresponds to the j-th column
130186        ** of the index and mark that ORDER BY term off
130187        */
130188        bOnce = 1;
130189        isMatch = 0;
130190        for(i=0; bOnce && i<nOrderBy; i++){
130191          if( MASKBIT(i) & obSat ) continue;
130192          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
130193          testcase( wctrlFlags & WHERE_GROUPBY );
130194          testcase( wctrlFlags & WHERE_DISTINCTBY );
130195          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
130196          if( iColumn>=(-1) ){
130197            if( pOBExpr->op!=TK_COLUMN ) continue;
130198            if( pOBExpr->iTable!=iCur ) continue;
130199            if( pOBExpr->iColumn!=iColumn ) continue;
130200          }else{
130201            if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
130202              continue;
130203            }
130204          }
130205          if( iColumn>=0 ){
130206            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
130207            if( !pColl ) pColl = db->pDfltColl;
130208            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
130209          }
130210          isMatch = 1;
130211          break;
130212        }
130213        if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
130214          /* Make sure the sort order is compatible in an ORDER BY clause.
130215          ** Sort order is irrelevant for a GROUP BY clause. */
130216          if( revSet ){
130217            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
130218          }else{
130219            rev = revIdx ^ pOrderBy->a[i].sortOrder;
130220            if( rev ) *pRevMask |= MASKBIT(iLoop);
130221            revSet = 1;
130222          }
130223        }
130224        if( isMatch ){
130225          if( iColumn<0 ){
130226            testcase( distinctColumns==0 );
130227            distinctColumns = 1;
130228          }
130229          obSat |= MASKBIT(i);
130230        }else{
130231          /* No match found */
130232          if( j==0 || j<nKeyCol ){
130233            testcase( isOrderDistinct!=0 );
130234            isOrderDistinct = 0;
130235          }
130236          break;
130237        }
130238      } /* end Loop over all index columns */
130239      if( distinctColumns ){
130240        testcase( isOrderDistinct==0 );
130241        isOrderDistinct = 1;
130242      }
130243    } /* end-if not one-row */
130244
130245    /* Mark off any other ORDER BY terms that reference pLoop */
130246    if( isOrderDistinct ){
130247      orderDistinctMask |= pLoop->maskSelf;
130248      for(i=0; i<nOrderBy; i++){
130249        Expr *p;
130250        Bitmask mTerm;
130251        if( MASKBIT(i) & obSat ) continue;
130252        p = pOrderBy->a[i].pExpr;
130253        mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
130254        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
130255        if( (mTerm&~orderDistinctMask)==0 ){
130256          obSat |= MASKBIT(i);
130257        }
130258      }
130259    }
130260  } /* End the loop over all WhereLoops from outer-most down to inner-most */
130261  if( obSat==obDone ) return (i8)nOrderBy;
130262  if( !isOrderDistinct ){
130263    for(i=nOrderBy-1; i>0; i--){
130264      Bitmask m = MASKBIT(i) - 1;
130265      if( (obSat&m)==m ) return i;
130266    }
130267    return 0;
130268  }
130269  return -1;
130270}
130271
130272
130273/*
130274** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
130275** the planner assumes that the specified pOrderBy list is actually a GROUP
130276** BY clause - and so any order that groups rows as required satisfies the
130277** request.
130278**
130279** Normally, in this case it is not possible for the caller to determine
130280** whether or not the rows are really being delivered in sorted order, or
130281** just in some other order that provides the required grouping. However,
130282** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
130283** this function may be called on the returned WhereInfo object. It returns
130284** true if the rows really will be sorted in the specified order, or false
130285** otherwise.
130286**
130287** For example, assuming:
130288**
130289**   CREATE INDEX i1 ON t1(x, Y);
130290**
130291** then
130292**
130293**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
130294**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
130295*/
130296SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
130297  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
130298  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
130299  return pWInfo->sorted;
130300}
130301
130302#ifdef WHERETRACE_ENABLED
130303/* For debugging use only: */
130304static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
130305  static char zName[65];
130306  int i;
130307  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
130308  if( pLast ) zName[i++] = pLast->cId;
130309  zName[i] = 0;
130310  return zName;
130311}
130312#endif
130313
130314/*
130315** Return the cost of sorting nRow rows, assuming that the keys have
130316** nOrderby columns and that the first nSorted columns are already in
130317** order.
130318*/
130319static LogEst whereSortingCost(
130320  WhereInfo *pWInfo,
130321  LogEst nRow,
130322  int nOrderBy,
130323  int nSorted
130324){
130325  /* TUNING: Estimated cost of a full external sort, where N is
130326  ** the number of rows to sort is:
130327  **
130328  **   cost = (3.0 * N * log(N)).
130329  **
130330  ** Or, if the order-by clause has X terms but only the last Y
130331  ** terms are out of order, then block-sorting will reduce the
130332  ** sorting cost to:
130333  **
130334  **   cost = (3.0 * N * log(N)) * (Y/X)
130335  **
130336  ** The (Y/X) term is implemented using stack variable rScale
130337  ** below.  */
130338  LogEst rScale, rSortCost;
130339  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
130340  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
130341  rSortCost = nRow + rScale + 16;
130342
130343  /* Multiple by log(M) where M is the number of output rows.
130344  ** Use the LIMIT for M if it is smaller */
130345  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
130346    nRow = pWInfo->iLimit;
130347  }
130348  rSortCost += estLog(nRow);
130349  return rSortCost;
130350}
130351
130352/*
130353** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
130354** attempts to find the lowest cost path that visits each WhereLoop
130355** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
130356**
130357** Assume that the total number of output rows that will need to be sorted
130358** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
130359** costs if nRowEst==0.
130360**
130361** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
130362** error occurs.
130363*/
130364static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
130365  int mxChoice;             /* Maximum number of simultaneous paths tracked */
130366  int nLoop;                /* Number of terms in the join */
130367  Parse *pParse;            /* Parsing context */
130368  sqlite3 *db;              /* The database connection */
130369  int iLoop;                /* Loop counter over the terms of the join */
130370  int ii, jj;               /* Loop counters */
130371  int mxI = 0;              /* Index of next entry to replace */
130372  int nOrderBy;             /* Number of ORDER BY clause terms */
130373  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
130374  LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
130375  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
130376  WherePath *aFrom;         /* All nFrom paths at the previous level */
130377  WherePath *aTo;           /* The nTo best paths at the current level */
130378  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
130379  WherePath *pTo;           /* An element of aTo[] that we are working on */
130380  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
130381  WhereLoop **pX;           /* Used to divy up the pSpace memory */
130382  LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
130383  char *pSpace;             /* Temporary memory used by this routine */
130384  int nSpace;               /* Bytes of space allocated at pSpace */
130385
130386  pParse = pWInfo->pParse;
130387  db = pParse->db;
130388  nLoop = pWInfo->nLevel;
130389  /* TUNING: For simple queries, only the best path is tracked.
130390  ** For 2-way joins, the 5 best paths are followed.
130391  ** For joins of 3 or more tables, track the 10 best paths */
130392  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
130393  assert( nLoop<=pWInfo->pTabList->nSrc );
130394  WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
130395
130396  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
130397  ** case the purpose of this call is to estimate the number of rows returned
130398  ** by the overall query. Once this estimate has been obtained, the caller
130399  ** will invoke this function a second time, passing the estimate as the
130400  ** nRowEst parameter.  */
130401  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
130402    nOrderBy = 0;
130403  }else{
130404    nOrderBy = pWInfo->pOrderBy->nExpr;
130405  }
130406
130407  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
130408  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
130409  nSpace += sizeof(LogEst) * nOrderBy;
130410  pSpace = sqlite3DbMallocRawNN(db, nSpace);
130411  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
130412  aTo = (WherePath*)pSpace;
130413  aFrom = aTo+mxChoice;
130414  memset(aFrom, 0, sizeof(aFrom[0]));
130415  pX = (WhereLoop**)(aFrom+mxChoice);
130416  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
130417    pFrom->aLoop = pX;
130418  }
130419  if( nOrderBy ){
130420    /* If there is an ORDER BY clause and it is not being ignored, set up
130421    ** space for the aSortCost[] array. Each element of the aSortCost array
130422    ** is either zero - meaning it has not yet been initialized - or the
130423    ** cost of sorting nRowEst rows of data where the first X terms of
130424    ** the ORDER BY clause are already in order, where X is the array
130425    ** index.  */
130426    aSortCost = (LogEst*)pX;
130427    memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
130428  }
130429  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
130430  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
130431
130432  /* Seed the search with a single WherePath containing zero WhereLoops.
130433  **
130434  ** TUNING: Do not let the number of iterations go above 28.  If the cost
130435  ** of computing an automatic index is not paid back within the first 28
130436  ** rows, then do not use the automatic index. */
130437  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
130438  nFrom = 1;
130439  assert( aFrom[0].isOrdered==0 );
130440  if( nOrderBy ){
130441    /* If nLoop is zero, then there are no FROM terms in the query. Since
130442    ** in this case the query may return a maximum of one row, the results
130443    ** are already in the requested order. Set isOrdered to nOrderBy to
130444    ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
130445    ** -1, indicating that the result set may or may not be ordered,
130446    ** depending on the loops added to the current plan.  */
130447    aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
130448  }
130449
130450  /* Compute successively longer WherePaths using the previous generation
130451  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
130452  ** best paths at each generation */
130453  for(iLoop=0; iLoop<nLoop; iLoop++){
130454    nTo = 0;
130455    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
130456      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
130457        LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
130458        LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
130459        LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
130460        i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
130461        Bitmask maskNew;                  /* Mask of src visited by (..) */
130462        Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
130463
130464        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
130465        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
130466        if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
130467          /* Do not use an automatic index if the this loop is expected
130468          ** to run less than 2 times. */
130469          assert( 10==sqlite3LogEst(2) );
130470          continue;
130471        }
130472        /* At this point, pWLoop is a candidate to be the next loop.
130473        ** Compute its cost */
130474        rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
130475        rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
130476        nOut = pFrom->nRow + pWLoop->nOut;
130477        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
130478        if( isOrdered<0 ){
130479          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
130480                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
130481                       iLoop, pWLoop, &revMask);
130482        }else{
130483          revMask = pFrom->revLoop;
130484        }
130485        if( isOrdered>=0 && isOrdered<nOrderBy ){
130486          if( aSortCost[isOrdered]==0 ){
130487            aSortCost[isOrdered] = whereSortingCost(
130488                pWInfo, nRowEst, nOrderBy, isOrdered
130489            );
130490          }
130491          rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
130492
130493          WHERETRACE(0x002,
130494              ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
130495               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
130496               rUnsorted, rCost));
130497        }else{
130498          rCost = rUnsorted;
130499        }
130500
130501        /* Check to see if pWLoop should be added to the set of
130502        ** mxChoice best-so-far paths.
130503        **
130504        ** First look for an existing path among best-so-far paths
130505        ** that covers the same set of loops and has the same isOrdered
130506        ** setting as the current path candidate.
130507        **
130508        ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
130509        ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
130510        ** of legal values for isOrdered, -1..64.
130511        */
130512        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
130513          if( pTo->maskLoop==maskNew
130514           && ((pTo->isOrdered^isOrdered)&0x80)==0
130515          ){
130516            testcase( jj==nTo-1 );
130517            break;
130518          }
130519        }
130520        if( jj>=nTo ){
130521          /* None of the existing best-so-far paths match the candidate. */
130522          if( nTo>=mxChoice
130523           && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
130524          ){
130525            /* The current candidate is no better than any of the mxChoice
130526            ** paths currently in the best-so-far buffer.  So discard
130527            ** this candidate as not viable. */
130528#ifdef WHERETRACE_ENABLED /* 0x4 */
130529            if( sqlite3WhereTrace&0x4 ){
130530              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
130531                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130532                  isOrdered>=0 ? isOrdered+'0' : '?');
130533            }
130534#endif
130535            continue;
130536          }
130537          /* If we reach this points it means that the new candidate path
130538          ** needs to be added to the set of best-so-far paths. */
130539          if( nTo<mxChoice ){
130540            /* Increase the size of the aTo set by one */
130541            jj = nTo++;
130542          }else{
130543            /* New path replaces the prior worst to keep count below mxChoice */
130544            jj = mxI;
130545          }
130546          pTo = &aTo[jj];
130547#ifdef WHERETRACE_ENABLED /* 0x4 */
130548          if( sqlite3WhereTrace&0x4 ){
130549            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
130550                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130551                isOrdered>=0 ? isOrdered+'0' : '?');
130552          }
130553#endif
130554        }else{
130555          /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
130556          ** same set of loops and has the sam isOrdered setting as the
130557          ** candidate path.  Check to see if the candidate should replace
130558          ** pTo or if the candidate should be skipped */
130559          if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
130560#ifdef WHERETRACE_ENABLED /* 0x4 */
130561            if( sqlite3WhereTrace&0x4 ){
130562              sqlite3DebugPrintf(
130563                  "Skip   %s cost=%-3d,%3d order=%c",
130564                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130565                  isOrdered>=0 ? isOrdered+'0' : '?');
130566              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
130567                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130568                  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
130569            }
130570#endif
130571            /* Discard the candidate path from further consideration */
130572            testcase( pTo->rCost==rCost );
130573            continue;
130574          }
130575          testcase( pTo->rCost==rCost+1 );
130576          /* Control reaches here if the candidate path is better than the
130577          ** pTo path.  Replace pTo with the candidate. */
130578#ifdef WHERETRACE_ENABLED /* 0x4 */
130579          if( sqlite3WhereTrace&0x4 ){
130580            sqlite3DebugPrintf(
130581                "Update %s cost=%-3d,%3d order=%c",
130582                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130583                isOrdered>=0 ? isOrdered+'0' : '?');
130584            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
130585                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130586                pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
130587          }
130588#endif
130589        }
130590        /* pWLoop is a winner.  Add it to the set of best so far */
130591        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
130592        pTo->revLoop = revMask;
130593        pTo->nRow = nOut;
130594        pTo->rCost = rCost;
130595        pTo->rUnsorted = rUnsorted;
130596        pTo->isOrdered = isOrdered;
130597        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
130598        pTo->aLoop[iLoop] = pWLoop;
130599        if( nTo>=mxChoice ){
130600          mxI = 0;
130601          mxCost = aTo[0].rCost;
130602          mxUnsorted = aTo[0].nRow;
130603          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
130604            if( pTo->rCost>mxCost
130605             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
130606            ){
130607              mxCost = pTo->rCost;
130608              mxUnsorted = pTo->rUnsorted;
130609              mxI = jj;
130610            }
130611          }
130612        }
130613      }
130614    }
130615
130616#ifdef WHERETRACE_ENABLED  /* >=2 */
130617    if( sqlite3WhereTrace & 0x02 ){
130618      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
130619      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
130620        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
130621           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130622           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
130623        if( pTo->isOrdered>0 ){
130624          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
130625        }else{
130626          sqlite3DebugPrintf("\n");
130627        }
130628      }
130629    }
130630#endif
130631
130632    /* Swap the roles of aFrom and aTo for the next generation */
130633    pFrom = aTo;
130634    aTo = aFrom;
130635    aFrom = pFrom;
130636    nFrom = nTo;
130637  }
130638
130639  if( nFrom==0 ){
130640    sqlite3ErrorMsg(pParse, "no query solution");
130641    sqlite3DbFree(db, pSpace);
130642    return SQLITE_ERROR;
130643  }
130644
130645  /* Find the lowest cost path.  pFrom will be left pointing to that path */
130646  pFrom = aFrom;
130647  for(ii=1; ii<nFrom; ii++){
130648    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
130649  }
130650  assert( pWInfo->nLevel==nLoop );
130651  /* Load the lowest cost path into pWInfo */
130652  for(iLoop=0; iLoop<nLoop; iLoop++){
130653    WhereLevel *pLevel = pWInfo->a + iLoop;
130654    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
130655    pLevel->iFrom = pWLoop->iTab;
130656    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
130657  }
130658  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
130659   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
130660   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
130661   && nRowEst
130662  ){
130663    Bitmask notUsed;
130664    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
130665                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
130666    if( rc==pWInfo->pDistinctSet->nExpr ){
130667      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
130668    }
130669  }
130670  if( pWInfo->pOrderBy ){
130671    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
130672      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
130673        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
130674      }
130675    }else{
130676      pWInfo->nOBSat = pFrom->isOrdered;
130677      pWInfo->revMask = pFrom->revLoop;
130678      if( pWInfo->nOBSat<=0 ){
130679        pWInfo->nOBSat = 0;
130680        if( nLoop>0 && (pFrom->aLoop[nLoop-1]->wsFlags & WHERE_ONEROW)==0 ){
130681          Bitmask m = 0;
130682          int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
130683                      WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
130684          if( rc==pWInfo->pOrderBy->nExpr ){
130685            pWInfo->bOrderedInnerLoop = 1;
130686            pWInfo->revMask = m;
130687          }
130688        }
130689      }
130690    }
130691    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
130692        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
130693    ){
130694      Bitmask revMask = 0;
130695      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
130696          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
130697      );
130698      assert( pWInfo->sorted==0 );
130699      if( nOrder==pWInfo->pOrderBy->nExpr ){
130700        pWInfo->sorted = 1;
130701        pWInfo->revMask = revMask;
130702      }
130703    }
130704  }
130705
130706
130707  pWInfo->nRowOut = pFrom->nRow;
130708
130709  /* Free temporary memory and return success */
130710  sqlite3DbFree(db, pSpace);
130711  return SQLITE_OK;
130712}
130713
130714/*
130715** Most queries use only a single table (they are not joins) and have
130716** simple == constraints against indexed fields.  This routine attempts
130717** to plan those simple cases using much less ceremony than the
130718** general-purpose query planner, and thereby yield faster sqlite3_prepare()
130719** times for the common case.
130720**
130721** Return non-zero on success, if this query can be handled by this
130722** no-frills query planner.  Return zero if this query needs the
130723** general-purpose query planner.
130724*/
130725static int whereShortCut(WhereLoopBuilder *pBuilder){
130726  WhereInfo *pWInfo;
130727  struct SrcList_item *pItem;
130728  WhereClause *pWC;
130729  WhereTerm *pTerm;
130730  WhereLoop *pLoop;
130731  int iCur;
130732  int j;
130733  Table *pTab;
130734  Index *pIdx;
130735
130736  pWInfo = pBuilder->pWInfo;
130737  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
130738  assert( pWInfo->pTabList->nSrc>=1 );
130739  pItem = pWInfo->pTabList->a;
130740  pTab = pItem->pTab;
130741  if( IsVirtual(pTab) ) return 0;
130742  if( pItem->fg.isIndexedBy ) return 0;
130743  iCur = pItem->iCursor;
130744  pWC = &pWInfo->sWC;
130745  pLoop = pBuilder->pNew;
130746  pLoop->wsFlags = 0;
130747  pLoop->nSkip = 0;
130748  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
130749  if( pTerm ){
130750    testcase( pTerm->eOperator & WO_IS );
130751    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
130752    pLoop->aLTerm[0] = pTerm;
130753    pLoop->nLTerm = 1;
130754    pLoop->u.btree.nEq = 1;
130755    /* TUNING: Cost of a rowid lookup is 10 */
130756    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
130757  }else{
130758    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
130759      int opMask;
130760      assert( pLoop->aLTermSpace==pLoop->aLTerm );
130761      if( !IsUniqueIndex(pIdx)
130762       || pIdx->pPartIdxWhere!=0
130763       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
130764      ) continue;
130765      opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
130766      for(j=0; j<pIdx->nKeyCol; j++){
130767        pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
130768        if( pTerm==0 ) break;
130769        testcase( pTerm->eOperator & WO_IS );
130770        pLoop->aLTerm[j] = pTerm;
130771      }
130772      if( j!=pIdx->nKeyCol ) continue;
130773      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
130774      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
130775        pLoop->wsFlags |= WHERE_IDX_ONLY;
130776      }
130777      pLoop->nLTerm = j;
130778      pLoop->u.btree.nEq = j;
130779      pLoop->u.btree.pIndex = pIdx;
130780      /* TUNING: Cost of a unique index lookup is 15 */
130781      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
130782      break;
130783    }
130784  }
130785  if( pLoop->wsFlags ){
130786    pLoop->nOut = (LogEst)1;
130787    pWInfo->a[0].pWLoop = pLoop;
130788    pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
130789    pWInfo->a[0].iTabCur = iCur;
130790    pWInfo->nRowOut = 1;
130791    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
130792    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
130793      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130794    }
130795#ifdef SQLITE_DEBUG
130796    pLoop->cId = '0';
130797#endif
130798    return 1;
130799  }
130800  return 0;
130801}
130802
130803/*
130804** Generate the beginning of the loop used for WHERE clause processing.
130805** The return value is a pointer to an opaque structure that contains
130806** information needed to terminate the loop.  Later, the calling routine
130807** should invoke sqlite3WhereEnd() with the return value of this function
130808** in order to complete the WHERE clause processing.
130809**
130810** If an error occurs, this routine returns NULL.
130811**
130812** The basic idea is to do a nested loop, one loop for each table in
130813** the FROM clause of a select.  (INSERT and UPDATE statements are the
130814** same as a SELECT with only a single table in the FROM clause.)  For
130815** example, if the SQL is this:
130816**
130817**       SELECT * FROM t1, t2, t3 WHERE ...;
130818**
130819** Then the code generated is conceptually like the following:
130820**
130821**      foreach row1 in t1 do       \    Code generated
130822**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
130823**          foreach row3 in t3 do   /
130824**            ...
130825**          end                     \    Code generated
130826**        end                        |-- by sqlite3WhereEnd()
130827**      end                         /
130828**
130829** Note that the loops might not be nested in the order in which they
130830** appear in the FROM clause if a different order is better able to make
130831** use of indices.  Note also that when the IN operator appears in
130832** the WHERE clause, it might result in additional nested loops for
130833** scanning through all values on the right-hand side of the IN.
130834**
130835** There are Btree cursors associated with each table.  t1 uses cursor
130836** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
130837** And so forth.  This routine generates code to open those VDBE cursors
130838** and sqlite3WhereEnd() generates the code to close them.
130839**
130840** The code that sqlite3WhereBegin() generates leaves the cursors named
130841** in pTabList pointing at their appropriate entries.  The [...] code
130842** can use OP_Column and OP_Rowid opcodes on these cursors to extract
130843** data from the various tables of the loop.
130844**
130845** If the WHERE clause is empty, the foreach loops must each scan their
130846** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
130847** the tables have indices and there are terms in the WHERE clause that
130848** refer to those indices, a complete table scan can be avoided and the
130849** code will run much faster.  Most of the work of this routine is checking
130850** to see if there are indices that can be used to speed up the loop.
130851**
130852** Terms of the WHERE clause are also used to limit which rows actually
130853** make it to the "..." in the middle of the loop.  After each "foreach",
130854** terms of the WHERE clause that use only terms in that loop and outer
130855** loops are evaluated and if false a jump is made around all subsequent
130856** inner loops (or around the "..." if the test occurs within the inner-
130857** most loop)
130858**
130859** OUTER JOINS
130860**
130861** An outer join of tables t1 and t2 is conceptally coded as follows:
130862**
130863**    foreach row1 in t1 do
130864**      flag = 0
130865**      foreach row2 in t2 do
130866**        start:
130867**          ...
130868**          flag = 1
130869**      end
130870**      if flag==0 then
130871**        move the row2 cursor to a null row
130872**        goto start
130873**      fi
130874**    end
130875**
130876** ORDER BY CLAUSE PROCESSING
130877**
130878** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
130879** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
130880** if there is one.  If there is no ORDER BY clause or if this routine
130881** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
130882**
130883** The iIdxCur parameter is the cursor number of an index.  If
130884** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
130885** to use for OR clause processing.  The WHERE clause should use this
130886** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
130887** the first cursor in an array of cursors for all indices.  iIdxCur should
130888** be used to compute the appropriate cursor depending on which index is
130889** used.
130890*/
130891SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
130892  Parse *pParse,          /* The parser context */
130893  SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
130894  Expr *pWhere,           /* The WHERE clause */
130895  ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
130896  ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
130897  u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
130898  int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
130899                          ** If WHERE_USE_LIMIT, then the limit amount */
130900){
130901  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
130902  int nTabList;              /* Number of elements in pTabList */
130903  WhereInfo *pWInfo;         /* Will become the return value of this function */
130904  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
130905  Bitmask notReady;          /* Cursors that are not yet positioned */
130906  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
130907  WhereMaskSet *pMaskSet;    /* The expression mask set */
130908  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
130909  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
130910  int ii;                    /* Loop counter */
130911  sqlite3 *db;               /* Database connection */
130912  int rc;                    /* Return code */
130913  u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
130914
130915  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
130916        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
130917     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130918  ));
130919
130920  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
130921  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130922            || (wctrlFlags & WHERE_USE_LIMIT)==0 );
130923
130924  /* Variable initialization */
130925  db = pParse->db;
130926  memset(&sWLB, 0, sizeof(sWLB));
130927
130928  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
130929  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
130930  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
130931  sWLB.pOrderBy = pOrderBy;
130932
130933  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
130934  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
130935  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
130936    wctrlFlags &= ~WHERE_WANT_DISTINCT;
130937  }
130938
130939  /* The number of tables in the FROM clause is limited by the number of
130940  ** bits in a Bitmask
130941  */
130942  testcase( pTabList->nSrc==BMS );
130943  if( pTabList->nSrc>BMS ){
130944    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
130945    return 0;
130946  }
130947
130948  /* This function normally generates a nested loop for all tables in
130949  ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
130950  ** only generate code for the first table in pTabList and assume that
130951  ** any cursors associated with subsequent tables are uninitialized.
130952  */
130953  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
130954
130955  /* Allocate and initialize the WhereInfo structure that will become the
130956  ** return value. A single allocation is used to store the WhereInfo
130957  ** struct, the contents of WhereInfo.a[], the WhereClause structure
130958  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
130959  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
130960  ** some architectures. Hence the ROUND8() below.
130961  */
130962  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
130963  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
130964  if( db->mallocFailed ){
130965    sqlite3DbFree(db, pWInfo);
130966    pWInfo = 0;
130967    goto whereBeginError;
130968  }
130969  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
130970  pWInfo->nLevel = nTabList;
130971  pWInfo->pParse = pParse;
130972  pWInfo->pTabList = pTabList;
130973  pWInfo->pOrderBy = pOrderBy;
130974  pWInfo->pDistinctSet = pDistinctSet;
130975  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
130976  pWInfo->wctrlFlags = wctrlFlags;
130977  pWInfo->iLimit = iAuxArg;
130978  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
130979  assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
130980  pMaskSet = &pWInfo->sMaskSet;
130981  sWLB.pWInfo = pWInfo;
130982  sWLB.pWC = &pWInfo->sWC;
130983  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
130984  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
130985  whereLoopInit(sWLB.pNew);
130986#ifdef SQLITE_DEBUG
130987  sWLB.pNew->cId = '*';
130988#endif
130989
130990  /* Split the WHERE clause into separate subexpressions where each
130991  ** subexpression is separated by an AND operator.
130992  */
130993  initMaskSet(pMaskSet);
130994  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
130995  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
130996
130997  /* Special case: a WHERE clause that is constant.  Evaluate the
130998  ** expression and either jump over all of the code or fall thru.
130999  */
131000  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
131001    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
131002      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
131003                         SQLITE_JUMPIFNULL);
131004      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
131005    }
131006  }
131007
131008  /* Special case: No FROM clause
131009  */
131010  if( nTabList==0 ){
131011    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
131012    if( wctrlFlags & WHERE_WANT_DISTINCT ){
131013      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
131014    }
131015  }
131016
131017  /* Assign a bit from the bitmask to every term in the FROM clause.
131018  **
131019  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
131020  **
131021  ** The rule of the previous sentence ensures thta if X is the bitmask for
131022  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
131023  ** Knowing the bitmask for all tables to the left of a left join is
131024  ** important.  Ticket #3015.
131025  **
131026  ** Note that bitmasks are created for all pTabList->nSrc tables in
131027  ** pTabList, not just the first nTabList tables.  nTabList is normally
131028  ** equal to pTabList->nSrc but might be shortened to 1 if the
131029  ** WHERE_OR_SUBCLAUSE flag is set.
131030  */
131031  for(ii=0; ii<pTabList->nSrc; ii++){
131032    createMask(pMaskSet, pTabList->a[ii].iCursor);
131033    sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
131034  }
131035#ifdef SQLITE_DEBUG
131036  for(ii=0; ii<pTabList->nSrc; ii++){
131037    Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
131038    assert( m==MASKBIT(ii) );
131039  }
131040#endif
131041
131042  /* Analyze all of the subexpressions. */
131043  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
131044  if( db->mallocFailed ) goto whereBeginError;
131045
131046  if( wctrlFlags & WHERE_WANT_DISTINCT ){
131047    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
131048      /* The DISTINCT marking is pointless.  Ignore it. */
131049      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
131050    }else if( pOrderBy==0 ){
131051      /* Try to ORDER BY the result set to make distinct processing easier */
131052      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
131053      pWInfo->pOrderBy = pDistinctSet;
131054    }
131055  }
131056
131057  /* Construct the WhereLoop objects */
131058#if defined(WHERETRACE_ENABLED)
131059  if( sqlite3WhereTrace & 0xffff ){
131060    sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
131061    if( wctrlFlags & WHERE_USE_LIMIT ){
131062      sqlite3DebugPrintf(", limit: %d", iAuxArg);
131063    }
131064    sqlite3DebugPrintf(")\n");
131065  }
131066  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
131067    sqlite3WhereClausePrint(sWLB.pWC);
131068  }
131069#endif
131070
131071  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
131072    rc = whereLoopAddAll(&sWLB);
131073    if( rc ) goto whereBeginError;
131074
131075#ifdef WHERETRACE_ENABLED
131076    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
131077      WhereLoop *p;
131078      int i;
131079      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
131080                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
131081      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
131082        p->cId = zLabel[i%sizeof(zLabel)];
131083        whereLoopPrint(p, sWLB.pWC);
131084      }
131085    }
131086#endif
131087
131088    wherePathSolver(pWInfo, 0);
131089    if( db->mallocFailed ) goto whereBeginError;
131090    if( pWInfo->pOrderBy ){
131091       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
131092       if( db->mallocFailed ) goto whereBeginError;
131093    }
131094  }
131095  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
131096     pWInfo->revMask = ALLBITS;
131097  }
131098  if( pParse->nErr || NEVER(db->mallocFailed) ){
131099    goto whereBeginError;
131100  }
131101#ifdef WHERETRACE_ENABLED
131102  if( sqlite3WhereTrace ){
131103    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
131104    if( pWInfo->nOBSat>0 ){
131105      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
131106    }
131107    switch( pWInfo->eDistinct ){
131108      case WHERE_DISTINCT_UNIQUE: {
131109        sqlite3DebugPrintf("  DISTINCT=unique");
131110        break;
131111      }
131112      case WHERE_DISTINCT_ORDERED: {
131113        sqlite3DebugPrintf("  DISTINCT=ordered");
131114        break;
131115      }
131116      case WHERE_DISTINCT_UNORDERED: {
131117        sqlite3DebugPrintf("  DISTINCT=unordered");
131118        break;
131119      }
131120    }
131121    sqlite3DebugPrintf("\n");
131122    for(ii=0; ii<pWInfo->nLevel; ii++){
131123      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
131124    }
131125  }
131126#endif
131127  /* Attempt to omit tables from the join that do not effect the result */
131128  if( pWInfo->nLevel>=2
131129   && pDistinctSet!=0
131130   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
131131  ){
131132    Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
131133    if( sWLB.pOrderBy ){
131134      tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
131135    }
131136    while( pWInfo->nLevel>=2 ){
131137      WhereTerm *pTerm, *pEnd;
131138      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
131139      if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
131140      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
131141       && (pLoop->wsFlags & WHERE_ONEROW)==0
131142      ){
131143        break;
131144      }
131145      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
131146      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
131147      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
131148        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
131149         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
131150        ){
131151          break;
131152        }
131153      }
131154      if( pTerm<pEnd ) break;
131155      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
131156      pWInfo->nLevel--;
131157      nTabList--;
131158    }
131159  }
131160  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
131161  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
131162
131163  /* If the caller is an UPDATE or DELETE statement that is requesting
131164  ** to use a one-pass algorithm, determine if this is appropriate.
131165  */
131166  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
131167  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
131168    int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
131169    int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
131170    if( bOnerow
131171     || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
131172           && 0==(wsFlags & WHERE_VIRTUALTABLE))
131173    ){
131174      pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
131175      if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
131176        if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
131177          bFordelete = OPFLAG_FORDELETE;
131178        }
131179        pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
131180      }
131181    }
131182  }
131183
131184  /* Open all tables in the pTabList and any indices selected for
131185  ** searching those tables.
131186  */
131187  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
131188    Table *pTab;     /* Table to open */
131189    int iDb;         /* Index of database containing table/index */
131190    struct SrcList_item *pTabItem;
131191
131192    pTabItem = &pTabList->a[pLevel->iFrom];
131193    pTab = pTabItem->pTab;
131194    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
131195    pLoop = pLevel->pWLoop;
131196    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
131197      /* Do nothing */
131198    }else
131199#ifndef SQLITE_OMIT_VIRTUALTABLE
131200    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
131201      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
131202      int iCur = pTabItem->iCursor;
131203      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
131204    }else if( IsVirtual(pTab) ){
131205      /* noop */
131206    }else
131207#endif
131208    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
131209         && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
131210      int op = OP_OpenRead;
131211      if( pWInfo->eOnePass!=ONEPASS_OFF ){
131212        op = OP_OpenWrite;
131213        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
131214      };
131215      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
131216      assert( pTabItem->iCursor==pLevel->iTabCur );
131217      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
131218      testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
131219      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
131220        Bitmask b = pTabItem->colUsed;
131221        int n = 0;
131222        for(; b; b=b>>1, n++){}
131223        sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
131224        assert( n<=pTab->nCol );
131225      }
131226#ifdef SQLITE_ENABLE_CURSOR_HINTS
131227      if( pLoop->u.btree.pIndex!=0 ){
131228        sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
131229      }else
131230#endif
131231      {
131232        sqlite3VdbeChangeP5(v, bFordelete);
131233      }
131234#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
131235      sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
131236                            (const u8*)&pTabItem->colUsed, P4_INT64);
131237#endif
131238    }else{
131239      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
131240    }
131241    if( pLoop->wsFlags & WHERE_INDEXED ){
131242      Index *pIx = pLoop->u.btree.pIndex;
131243      int iIndexCur;
131244      int op = OP_OpenRead;
131245      /* iAuxArg is always set if to a positive value if ONEPASS is possible */
131246      assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
131247      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
131248       && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
131249      ){
131250        /* This is one term of an OR-optimization using the PRIMARY KEY of a
131251        ** WITHOUT ROWID table.  No need for a separate index */
131252        iIndexCur = pLevel->iTabCur;
131253        op = 0;
131254      }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
131255        Index *pJ = pTabItem->pTab->pIndex;
131256        iIndexCur = iAuxArg;
131257        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
131258        while( ALWAYS(pJ) && pJ!=pIx ){
131259          iIndexCur++;
131260          pJ = pJ->pNext;
131261        }
131262        op = OP_OpenWrite;
131263        pWInfo->aiCurOnePass[1] = iIndexCur;
131264      }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
131265        iIndexCur = iAuxArg;
131266        op = OP_ReopenIdx;
131267      }else{
131268        iIndexCur = pParse->nTab++;
131269      }
131270      pLevel->iIdxCur = iIndexCur;
131271      assert( pIx->pSchema==pTab->pSchema );
131272      assert( iIndexCur>=0 );
131273      if( op ){
131274        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
131275        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
131276        if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
131277         && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
131278         && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
131279        ){
131280          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
131281        }
131282        VdbeComment((v, "%s", pIx->zName));
131283#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
131284        {
131285          u64 colUsed = 0;
131286          int ii, jj;
131287          for(ii=0; ii<pIx->nColumn; ii++){
131288            jj = pIx->aiColumn[ii];
131289            if( jj<0 ) continue;
131290            if( jj>63 ) jj = 63;
131291            if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
131292            colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
131293          }
131294          sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
131295                                (u8*)&colUsed, P4_INT64);
131296        }
131297#endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
131298      }
131299    }
131300    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
131301  }
131302  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
131303  if( db->mallocFailed ) goto whereBeginError;
131304
131305  /* Generate the code to do the search.  Each iteration of the for
131306  ** loop below generates code for a single nested loop of the VM
131307  ** program.
131308  */
131309  notReady = ~(Bitmask)0;
131310  for(ii=0; ii<nTabList; ii++){
131311    int addrExplain;
131312    int wsFlags;
131313    pLevel = &pWInfo->a[ii];
131314    wsFlags = pLevel->pWLoop->wsFlags;
131315#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
131316    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
131317      constructAutomaticIndex(pParse, &pWInfo->sWC,
131318                &pTabList->a[pLevel->iFrom], notReady, pLevel);
131319      if( db->mallocFailed ) goto whereBeginError;
131320    }
131321#endif
131322    addrExplain = sqlite3WhereExplainOneScan(
131323        pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
131324    );
131325    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
131326    notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
131327    pWInfo->iContinue = pLevel->addrCont;
131328    if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
131329      sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
131330    }
131331  }
131332
131333  /* Done. */
131334  VdbeModuleComment((v, "Begin WHERE-core"));
131335  return pWInfo;
131336
131337  /* Jump here if malloc fails */
131338whereBeginError:
131339  if( pWInfo ){
131340    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
131341    whereInfoFree(db, pWInfo);
131342  }
131343  return 0;
131344}
131345
131346/*
131347** Generate the end of the WHERE loop.  See comments on
131348** sqlite3WhereBegin() for additional information.
131349*/
131350SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
131351  Parse *pParse = pWInfo->pParse;
131352  Vdbe *v = pParse->pVdbe;
131353  int i;
131354  WhereLevel *pLevel;
131355  WhereLoop *pLoop;
131356  SrcList *pTabList = pWInfo->pTabList;
131357  sqlite3 *db = pParse->db;
131358
131359  /* Generate loop termination code.
131360  */
131361  VdbeModuleComment((v, "End WHERE-core"));
131362  sqlite3ExprCacheClear(pParse);
131363  for(i=pWInfo->nLevel-1; i>=0; i--){
131364    int addr;
131365    pLevel = &pWInfo->a[i];
131366    pLoop = pLevel->pWLoop;
131367    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
131368    if( pLevel->op!=OP_Noop ){
131369      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
131370      sqlite3VdbeChangeP5(v, pLevel->p5);
131371      VdbeCoverage(v);
131372      VdbeCoverageIf(v, pLevel->op==OP_Next);
131373      VdbeCoverageIf(v, pLevel->op==OP_Prev);
131374      VdbeCoverageIf(v, pLevel->op==OP_VNext);
131375    }
131376    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
131377      struct InLoop *pIn;
131378      int j;
131379      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
131380      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
131381        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
131382        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
131383        VdbeCoverage(v);
131384        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
131385        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
131386        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
131387      }
131388    }
131389    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
131390    if( pLevel->addrSkip ){
131391      sqlite3VdbeGoto(v, pLevel->addrSkip);
131392      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
131393      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
131394      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
131395    }
131396#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
131397    if( pLevel->addrLikeRep ){
131398      sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
131399                        pLevel->addrLikeRep);
131400      VdbeCoverage(v);
131401    }
131402#endif
131403    if( pLevel->iLeftJoin ){
131404      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
131405      assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
131406           || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
131407      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
131408        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
131409      }
131410      if( pLoop->wsFlags & WHERE_INDEXED ){
131411        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
131412      }
131413      if( pLevel->op==OP_Return ){
131414        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
131415      }else{
131416        sqlite3VdbeGoto(v, pLevel->addrFirst);
131417      }
131418      sqlite3VdbeJumpHere(v, addr);
131419    }
131420    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
131421                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
131422  }
131423
131424  /* The "break" point is here, just past the end of the outer loop.
131425  ** Set it.
131426  */
131427  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
131428
131429  assert( pWInfo->nLevel<=pTabList->nSrc );
131430  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
131431    int k, last;
131432    VdbeOp *pOp;
131433    Index *pIdx = 0;
131434    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
131435    Table *pTab = pTabItem->pTab;
131436    assert( pTab!=0 );
131437    pLoop = pLevel->pWLoop;
131438
131439    /* For a co-routine, change all OP_Column references to the table of
131440    ** the co-routine into OP_Copy of result contained in a register.
131441    ** OP_Rowid becomes OP_Null.
131442    */
131443    if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
131444      translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
131445                            pTabItem->regResult, 0);
131446      continue;
131447    }
131448
131449    /* Close all of the cursors that were opened by sqlite3WhereBegin.
131450    ** Except, do not close cursors that will be reused by the OR optimization
131451    ** (WHERE_OR_SUBCLAUSE).  And do not close the OP_OpenWrite cursors
131452    ** created for the ONEPASS optimization.
131453    */
131454    if( (pTab->tabFlags & TF_Ephemeral)==0
131455     && pTab->pSelect==0
131456     && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
131457    ){
131458      int ws = pLoop->wsFlags;
131459      if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
131460        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
131461      }
131462      if( (ws & WHERE_INDEXED)!=0
131463       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
131464       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
131465      ){
131466        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
131467      }
131468    }
131469
131470    /* If this scan uses an index, make VDBE code substitutions to read data
131471    ** from the index instead of from the table where possible.  In some cases
131472    ** this optimization prevents the table from ever being read, which can
131473    ** yield a significant performance boost.
131474    **
131475    ** Calls to the code generator in between sqlite3WhereBegin and
131476    ** sqlite3WhereEnd will have created code that references the table
131477    ** directly.  This loop scans all that code looking for opcodes
131478    ** that reference the table and converts them into opcodes that
131479    ** reference the index.
131480    */
131481    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
131482      pIdx = pLoop->u.btree.pIndex;
131483    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
131484      pIdx = pLevel->u.pCovidx;
131485    }
131486    if( pIdx
131487     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
131488     && !db->mallocFailed
131489    ){
131490      last = sqlite3VdbeCurrentAddr(v);
131491      k = pLevel->addrBody;
131492      pOp = sqlite3VdbeGetOp(v, k);
131493      for(; k<last; k++, pOp++){
131494        if( pOp->p1!=pLevel->iTabCur ) continue;
131495        if( pOp->opcode==OP_Column ){
131496          int x = pOp->p2;
131497          assert( pIdx->pTable==pTab );
131498          if( !HasRowid(pTab) ){
131499            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
131500            x = pPk->aiColumn[x];
131501            assert( x>=0 );
131502          }
131503          x = sqlite3ColumnOfIndex(pIdx, x);
131504          if( x>=0 ){
131505            pOp->p2 = x;
131506            pOp->p1 = pLevel->iIdxCur;
131507          }
131508          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
131509        }else if( pOp->opcode==OP_Rowid ){
131510          pOp->p1 = pLevel->iIdxCur;
131511          pOp->opcode = OP_IdxRowid;
131512        }
131513      }
131514    }
131515  }
131516
131517  /* Final cleanup
131518  */
131519  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
131520  whereInfoFree(db, pWInfo);
131521  return;
131522}
131523
131524/************** End of where.c ***********************************************/
131525/************** Begin file parse.c *******************************************/
131526/*
131527** 2000-05-29
131528**
131529** The author disclaims copyright to this source code.  In place of
131530** a legal notice, here is a blessing:
131531**
131532**    May you do good and not evil.
131533**    May you find forgiveness for yourself and forgive others.
131534**    May you share freely, never taking more than you give.
131535**
131536*************************************************************************
131537** Driver template for the LEMON parser generator.
131538**
131539** The "lemon" program processes an LALR(1) input grammar file, then uses
131540** this template to construct a parser.  The "lemon" program inserts text
131541** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
131542** interstitial "-" characters) contained in this template is changed into
131543** the value of the %name directive from the grammar.  Otherwise, the content
131544** of this template is copied straight through into the generate parser
131545** source file.
131546**
131547** The following is the concatenation of all %include directives from the
131548** input grammar file:
131549*/
131550/* #include <stdio.h> */
131551/************ Begin %include sections from the grammar ************************/
131552
131553/* #include "sqliteInt.h" */
131554
131555/*
131556** Disable all error recovery processing in the parser push-down
131557** automaton.
131558*/
131559#define YYNOERRORRECOVERY 1
131560
131561/*
131562** Make yytestcase() the same as testcase()
131563*/
131564#define yytestcase(X) testcase(X)
131565
131566/*
131567** Indicate that sqlite3ParserFree() will never be called with a null
131568** pointer.
131569*/
131570#define YYPARSEFREENEVERNULL 1
131571
131572/*
131573** Alternative datatype for the argument to the malloc() routine passed
131574** into sqlite3ParserAlloc().  The default is size_t.
131575*/
131576#define YYMALLOCARGTYPE  u64
131577
131578/*
131579** An instance of this structure holds information about the
131580** LIMIT clause of a SELECT statement.
131581*/
131582struct LimitVal {
131583  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
131584  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
131585};
131586
131587/*
131588** An instance of this structure is used to store the LIKE,
131589** GLOB, NOT LIKE, and NOT GLOB operators.
131590*/
131591struct LikeOp {
131592  Token eOperator;  /* "like" or "glob" or "regexp" */
131593  int bNot;         /* True if the NOT keyword is present */
131594};
131595
131596/*
131597** An instance of the following structure describes the event of a
131598** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
131599** TK_DELETE, or TK_INSTEAD.  If the event is of the form
131600**
131601**      UPDATE ON (a,b,c)
131602**
131603** Then the "b" IdList records the list "a,b,c".
131604*/
131605struct TrigEvent { int a; IdList * b; };
131606
131607/*
131608** An instance of this structure holds the ATTACH key and the key type.
131609*/
131610struct AttachKey { int type;  Token key; };
131611
131612/*
131613** Disable lookaside memory allocation for objects that might be
131614** shared across database connections.
131615*/
131616static void disableLookaside(Parse *pParse){
131617  pParse->disableLookaside++;
131618  pParse->db->lookaside.bDisable++;
131619}
131620
131621
131622  /*
131623  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
131624  ** all elements in the list.  And make sure list length does not exceed
131625  ** SQLITE_LIMIT_COMPOUND_SELECT.
131626  */
131627  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
131628    if( p->pPrior ){
131629      Select *pNext = 0, *pLoop;
131630      int mxSelect, cnt = 0;
131631      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
131632        pLoop->pNext = pNext;
131633        pLoop->selFlags |= SF_Compound;
131634      }
131635      if( (p->selFlags & SF_MultiValue)==0 &&
131636        (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
131637        cnt>mxSelect
131638      ){
131639        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
131640      }
131641    }
131642  }
131643
131644  /* This is a utility routine used to set the ExprSpan.zStart and
131645  ** ExprSpan.zEnd values of pOut so that the span covers the complete
131646  ** range of text beginning with pStart and going to the end of pEnd.
131647  */
131648  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
131649    pOut->zStart = pStart->z;
131650    pOut->zEnd = &pEnd->z[pEnd->n];
131651  }
131652
131653  /* Construct a new Expr object from a single identifier.  Use the
131654  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
131655  ** that created the expression.
131656  */
131657  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
131658    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, &t);
131659    pOut->zStart = t.z;
131660    pOut->zEnd = &t.z[t.n];
131661  }
131662
131663  /* This routine constructs a binary expression node out of two ExprSpan
131664  ** objects and uses the result to populate a new ExprSpan object.
131665  */
131666  static void spanBinaryExpr(
131667    Parse *pParse,      /* The parsing context.  Errors accumulate here */
131668    int op,             /* The binary operation */
131669    ExprSpan *pLeft,    /* The left operand, and output */
131670    ExprSpan *pRight    /* The right operand */
131671  ){
131672    pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
131673    pLeft->zEnd = pRight->zEnd;
131674  }
131675
131676  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
131677  ** outside of *ppExpr.
131678  */
131679  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
131680    if( doNot ){
131681      pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
131682    }
131683  }
131684
131685  /* Construct an expression node for a unary postfix operator
131686  */
131687  static void spanUnaryPostfix(
131688    Parse *pParse,         /* Parsing context to record errors */
131689    int op,                /* The operator */
131690    ExprSpan *pOperand,    /* The operand, and output */
131691    Token *pPostOp         /* The operand token for setting the span */
131692  ){
131693    pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
131694    pOperand->zEnd = &pPostOp->z[pPostOp->n];
131695  }
131696
131697  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
131698  ** unary TK_ISNULL or TK_NOTNULL expression. */
131699  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
131700    sqlite3 *db = pParse->db;
131701    if( pA && pY && pY->op==TK_NULL ){
131702      pA->op = (u8)op;
131703      sqlite3ExprDelete(db, pA->pRight);
131704      pA->pRight = 0;
131705    }
131706  }
131707
131708  /* Construct an expression node for a unary prefix operator
131709  */
131710  static void spanUnaryPrefix(
131711    ExprSpan *pOut,        /* Write the new expression node here */
131712    Parse *pParse,         /* Parsing context to record errors */
131713    int op,                /* The operator */
131714    ExprSpan *pOperand,    /* The operand */
131715    Token *pPreOp         /* The operand token for setting the span */
131716  ){
131717    pOut->zStart = pPreOp->z;
131718    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
131719    pOut->zEnd = pOperand->zEnd;
131720  }
131721
131722  /* Add a single new term to an ExprList that is used to store a
131723  ** list of identifiers.  Report an error if the ID list contains
131724  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
131725  ** error while parsing a legacy schema.
131726  */
131727  static ExprList *parserAddExprIdListTerm(
131728    Parse *pParse,
131729    ExprList *pPrior,
131730    Token *pIdToken,
131731    int hasCollate,
131732    int sortOrder
131733  ){
131734    ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
131735    if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
131736        && pParse->db->init.busy==0
131737    ){
131738      sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
131739                         pIdToken->n, pIdToken->z);
131740    }
131741    sqlite3ExprListSetName(pParse, p, pIdToken, 1);
131742    return p;
131743  }
131744/**************** End of %include directives **********************************/
131745/* These constants specify the various numeric values for terminal symbols
131746** in a format understandable to "makeheaders".  This section is blank unless
131747** "lemon" is run with the "-m" command-line option.
131748***************** Begin makeheaders token definitions *************************/
131749/**************** End makeheaders token definitions ***************************/
131750
131751/* The next sections is a series of control #defines.
131752** various aspects of the generated parser.
131753**    YYCODETYPE         is the data type used to store the integer codes
131754**                       that represent terminal and non-terminal symbols.
131755**                       "unsigned char" is used if there are fewer than
131756**                       256 symbols.  Larger types otherwise.
131757**    YYNOCODE           is a number of type YYCODETYPE that is not used for
131758**                       any terminal or nonterminal symbol.
131759**    YYFALLBACK         If defined, this indicates that one or more tokens
131760**                       (also known as: "terminal symbols") have fall-back
131761**                       values which should be used if the original symbol
131762**                       would not parse.  This permits keywords to sometimes
131763**                       be used as identifiers, for example.
131764**    YYACTIONTYPE       is the data type used for "action codes" - numbers
131765**                       that indicate what to do in response to the next
131766**                       token.
131767**    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
131768**                       symbols.  Background: A "minor type" is a semantic
131769**                       value associated with a terminal or non-terminal
131770**                       symbols.  For example, for an "ID" terminal symbol,
131771**                       the minor type might be the name of the identifier.
131772**                       Each non-terminal can have a different minor type.
131773**                       Terminal symbols all have the same minor type, though.
131774**                       This macros defines the minor type for terminal
131775**                       symbols.
131776**    YYMINORTYPE        is the data type used for all minor types.
131777**                       This is typically a union of many types, one of
131778**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
131779**                       for terminal symbols is called "yy0".
131780**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
131781**                       zero the stack is dynamically sized using realloc()
131782**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
131783**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
131784**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
131785**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
131786**    YYERRORSYMBOL      is the code number of the error symbol.  If not
131787**                       defined, then do no error processing.
131788**    YYNSTATE           the combined number of states.
131789**    YYNRULE            the number of rules in the grammar
131790**    YY_MAX_SHIFT       Maximum value for shift actions
131791**    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
131792**    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
131793**    YY_MIN_REDUCE      Maximum value for reduce actions
131794**    YY_ERROR_ACTION    The yy_action[] code for syntax error
131795**    YY_ACCEPT_ACTION   The yy_action[] code for accept
131796**    YY_NO_ACTION       The yy_action[] code for no-op
131797*/
131798#ifndef INTERFACE
131799# define INTERFACE 1
131800#endif
131801/************* Begin control #defines *****************************************/
131802#define YYCODETYPE unsigned char
131803#define YYNOCODE 252
131804#define YYACTIONTYPE unsigned short int
131805#define YYWILDCARD 96
131806#define sqlite3ParserTOKENTYPE Token
131807typedef union {
131808  int yyinit;
131809  sqlite3ParserTOKENTYPE yy0;
131810  Expr* yy72;
131811  TriggerStep* yy145;
131812  ExprList* yy148;
131813  SrcList* yy185;
131814  ExprSpan yy190;
131815  int yy194;
131816  Select* yy243;
131817  IdList* yy254;
131818  With* yy285;
131819  struct TrigEvent yy332;
131820  struct LimitVal yy354;
131821  struct LikeOp yy392;
131822  struct {int value; int mask;} yy497;
131823} YYMINORTYPE;
131824#ifndef YYSTACKDEPTH
131825#define YYSTACKDEPTH 100
131826#endif
131827#define sqlite3ParserARG_SDECL Parse *pParse;
131828#define sqlite3ParserARG_PDECL ,Parse *pParse
131829#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
131830#define sqlite3ParserARG_STORE yypParser->pParse = pParse
131831#define YYFALLBACK 1
131832#define YYNSTATE             443
131833#define YYNRULE              328
131834#define YY_MAX_SHIFT         442
131835#define YY_MIN_SHIFTREDUCE   653
131836#define YY_MAX_SHIFTREDUCE   980
131837#define YY_MIN_REDUCE        981
131838#define YY_MAX_REDUCE        1308
131839#define YY_ERROR_ACTION      1309
131840#define YY_ACCEPT_ACTION     1310
131841#define YY_NO_ACTION         1311
131842/************* End control #defines *******************************************/
131843
131844/* Define the yytestcase() macro to be a no-op if is not already defined
131845** otherwise.
131846**
131847** Applications can choose to define yytestcase() in the %include section
131848** to a macro that can assist in verifying code coverage.  For production
131849** code the yytestcase() macro should be turned off.  But it is useful
131850** for testing.
131851*/
131852#ifndef yytestcase
131853# define yytestcase(X)
131854#endif
131855
131856
131857/* Next are the tables used to determine what action to take based on the
131858** current state and lookahead token.  These tables are used to implement
131859** functions that take a state number and lookahead value and return an
131860** action integer.
131861**
131862** Suppose the action integer is N.  Then the action is determined as
131863** follows
131864**
131865**   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
131866**                                      token onto the stack and goto state N.
131867**
131868**   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
131869**     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
131870**
131871**   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
131872**     and YY_MAX_REDUCE
131873
131874**   N == YY_ERROR_ACTION               A syntax error has occurred.
131875**
131876**   N == YY_ACCEPT_ACTION              The parser accepts its input.
131877**
131878**   N == YY_NO_ACTION                  No such action.  Denotes unused
131879**                                      slots in the yy_action[] table.
131880**
131881** The action table is constructed as a single large table named yy_action[].
131882** Given state S and lookahead X, the action is computed as
131883**
131884**      yy_action[ yy_shift_ofst[S] + X ]
131885**
131886** If the index value yy_shift_ofst[S]+X is out of range or if the value
131887** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
131888** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
131889** and that yy_default[S] should be used instead.
131890**
131891** The formula above is for computing the action when the lookahead is
131892** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
131893** a reduce action) then the yy_reduce_ofst[] array is used in place of
131894** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
131895** YY_SHIFT_USE_DFLT.
131896**
131897** The following are the tables generated in this section:
131898**
131899**  yy_action[]        A single table containing all actions.
131900**  yy_lookahead[]     A table containing the lookahead for each entry in
131901**                     yy_action.  Used to detect hash collisions.
131902**  yy_shift_ofst[]    For each state, the offset into yy_action for
131903**                     shifting terminals.
131904**  yy_reduce_ofst[]   For each state, the offset into yy_action for
131905**                     shifting non-terminals after a reduce.
131906**  yy_default[]       Default action for each state.
131907**
131908*********** Begin parsing tables **********************************************/
131909#define YY_ACTTAB_COUNT (1507)
131910static const YYACTIONTYPE yy_action[] = {
131911 /*     0 */   317,  814,  341,  808,    5,  195,  195,  802,   93,   94,
131912 /*    10 */    84,  823,  823,  835,  838,  827,  827,   91,   91,   92,
131913 /*    20 */    92,   92,   92,  293,   90,   90,   90,   90,   89,   89,
131914 /*    30 */    88,   88,   88,   87,  341,  317,  958,  958,  807,  807,
131915 /*    40 */   807,  928,  344,   93,   94,   84,  823,  823,  835,  838,
131916 /*    50 */   827,  827,   91,   91,   92,   92,   92,   92,  328,   90,
131917 /*    60 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  341,
131918 /*    70 */    89,   89,   88,   88,   88,   87,  341,  776,  958,  958,
131919 /*    80 */   317,   88,   88,   88,   87,  341,  777,   69,   93,   94,
131920 /*    90 */    84,  823,  823,  835,  838,  827,  827,   91,   91,   92,
131921 /*   100 */    92,   92,   92,  437,   90,   90,   90,   90,   89,   89,
131922 /*   110 */    88,   88,   88,   87,  341, 1310,  147,  147,    2,  317,
131923 /*   120 */    76,   25,   74,   49,   49,   87,  341,   93,   94,   84,
131924 /*   130 */   823,  823,  835,  838,  827,  827,   91,   91,   92,   92,
131925 /*   140 */    92,   92,   95,   90,   90,   90,   90,   89,   89,   88,
131926 /*   150 */    88,   88,   87,  341,  939,  939,  317,  260,  415,  400,
131927 /*   160 */   398,   58,  737,  737,   93,   94,   84,  823,  823,  835,
131928 /*   170 */   838,  827,  827,   91,   91,   92,   92,   92,   92,   57,
131929 /*   180 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131930 /*   190 */   341,  317, 1253,  928,  344,  269,  940,  941,  242,   93,
131931 /*   200 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131932 /*   210 */    92,   92,   92,   92,  293,   90,   90,   90,   90,   89,
131933 /*   220 */    89,   88,   88,   88,   87,  341,  317,  919, 1303,  793,
131934 /*   230 */   691, 1303,  724,  724,   93,   94,   84,  823,  823,  835,
131935 /*   240 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  337,
131936 /*   250 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131937 /*   260 */   341,  317,  114,  919, 1304,  684,  395, 1304,  124,   93,
131938 /*   270 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131939 /*   280 */    92,   92,   92,   92,  683,   90,   90,   90,   90,   89,
131940 /*   290 */    89,   88,   88,   88,   87,  341,  317,   86,   83,  169,
131941 /*   300 */   801,  917,  234,  399,   93,   94,   84,  823,  823,  835,
131942 /*   310 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  686,
131943 /*   320 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131944 /*   330 */   341,  317,  436,  742,   86,   83,  169,  917,  741,   93,
131945 /*   340 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131946 /*   350 */    92,   92,   92,   92,  902,   90,   90,   90,   90,   89,
131947 /*   360 */    89,   88,   88,   88,   87,  341,  317,  321,  434,  434,
131948 /*   370 */   434,    1,  722,  722,   93,   94,   84,  823,  823,  835,
131949 /*   380 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  190,
131950 /*   390 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131951 /*   400 */   341,  317,  685,  292,  939,  939,  150,  977,  310,   93,
131952 /*   410 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131953 /*   420 */    92,   92,   92,   92,  437,   90,   90,   90,   90,   89,
131954 /*   430 */    89,   88,   88,   88,   87,  341,  926,    2,  372,  719,
131955 /*   440 */   698,  369,  950,  317,   49,   49,  940,  941,  719,  177,
131956 /*   450 */    72,   93,   94,   84,  823,  823,  835,  838,  827,  827,
131957 /*   460 */    91,   91,   92,   92,   92,   92,  322,   90,   90,   90,
131958 /*   470 */    90,   89,   89,   88,   88,   88,   87,  341,  317,  415,
131959 /*   480 */   405,  824,  824,  836,  839,   75,   93,   82,   84,  823,
131960 /*   490 */   823,  835,  838,  827,  827,   91,   91,   92,   92,   92,
131961 /*   500 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
131962 /*   510 */    88,   87,  341,  317,  340,  340,  340,  658,  659,  660,
131963 /*   520 */   333,  288,   94,   84,  823,  823,  835,  838,  827,  827,
131964 /*   530 */    91,   91,   92,   92,   92,   92,  437,   90,   90,   90,
131965 /*   540 */    90,   89,   89,   88,   88,   88,   87,  341,  317,  882,
131966 /*   550 */   882,  375,  828,   66,  330,  409,   49,   49,   84,  823,
131967 /*   560 */   823,  835,  838,  827,  827,   91,   91,   92,   92,   92,
131968 /*   570 */    92,  351,   90,   90,   90,   90,   89,   89,   88,   88,
131969 /*   580 */    88,   87,  341,   80,  432,  742,    3, 1180,  351,  350,
131970 /*   590 */   741,  334,  796,  939,  939,  761,   80,  432,  278,    3,
131971 /*   600 */   204,  161,  279,  393,  274,  392,  191,  362,  437,  277,
131972 /*   610 */   745,   77,   78,  272,  800,  254,  355,  243,   79,  342,
131973 /*   620 */   342,   86,   83,  169,   77,   78,  234,  399,   49,   49,
131974 /*   630 */   435,   79,  342,  342,  437,  940,  941,  186,  442,  655,
131975 /*   640 */   390,  387,  386,  435,  235,  213,  108,  421,  761,  351,
131976 /*   650 */   437,  385,  167,  732,   10,   10,  124,  124,  671,  814,
131977 /*   660 */   421,  439,  438,  415,  414,  802,  362,  168,  327,  124,
131978 /*   670 */    49,   49,  814,  219,  439,  438,  800,  186,  802,  326,
131979 /*   680 */   390,  387,  386,  437, 1248, 1248,   23,  939,  939,   80,
131980 /*   690 */   432,  385,    3,  761,  416,  876,  807,  807,  807,  809,
131981 /*   700 */    19,  290,  149,   49,   49,  415,  396,  260,  910,  807,
131982 /*   710 */   807,  807,  809,   19,  312,  237,  145,   77,   78,  746,
131983 /*   720 */   168,  702,  437,  149,   79,  342,  342,  114,  358,  940,
131984 /*   730 */   941,  302,  223,  397,  345,  313,  435,  260,  415,  417,
131985 /*   740 */   858,  374,   31,   31,   80,  432,  761,    3,  348,   92,
131986 /*   750 */    92,   92,   92,  421,   90,   90,   90,   90,   89,   89,
131987 /*   760 */    88,   88,   88,   87,  341,  814,  114,  439,  438,  796,
131988 /*   770 */   367,  802,   77,   78,  701,  796,  124, 1187,  220,   79,
131989 /*   780 */   342,  342,  124,  747,  734,  939,  939,  775,  404,  939,
131990 /*   790 */   939,  435,  254,  360,  253,  402,  895,  346,  254,  360,
131991 /*   800 */   253,  774,  807,  807,  807,  809,   19,  800,  421,   90,
131992 /*   810 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  341,
131993 /*   820 */   814,  114,  439,  438,  939,  939,  802,  940,  941,  114,
131994 /*   830 */   437,  940,  941,   86,   83,  169,  192,  166,  309,  979,
131995 /*   840 */    70,  432,  700,    3,  382,  870,  238,   86,   83,  169,
131996 /*   850 */    10,   10,  361,  406,  763,  190,  222,  807,  807,  807,
131997 /*   860 */   809,   19,  870,  872,  329,   24,  940,  941,   77,   78,
131998 /*   870 */   359,  437,  335,  260,  218,   79,  342,  342,  437,  307,
131999 /*   880 */   306,  305,  207,  303,  339,  338,  668,  435,  339,  338,
132000 /*   890 */   407,   10,   10,  762,  216,  216,  939,  939,   49,   49,
132001 /*   900 */   437,  260,   97,  241,  421,  225,  402,  189,  188,  187,
132002 /*   910 */   309,  918,  980,  149,  221,  898,  814,  868,  439,  438,
132003 /*   920 */    10,   10,  802,  870,  915,  316,  898,  163,  162,  171,
132004 /*   930 */   249,  240,  322,  410,  412,  687,  687,  272,  940,  941,
132005 /*   940 */   239,  965,  901,  437,  226,  403,  226,  437,  963,  367,
132006 /*   950 */   964,  173,  248,  807,  807,  807,  809,   19,  174,  367,
132007 /*   960 */   899,  124,  172,   48,   48,    9,    9,   35,   35,  966,
132008 /*   970 */   966,  899,  363,  966,  966,  814,  900,  808,  725,  939,
132009 /*   980 */   939,  802,  895,  318,  980,  324,  125,  900,  726,  420,
132010 /*   990 */    92,   92,   92,   92,   85,   90,   90,   90,   90,   89,
132011 /*  1000 */    89,   88,   88,   88,   87,  341,  216,  216,  437,  946,
132012 /*  1010 */   349,  292,  807,  807,  807,  114,  291,  693,  402,  705,
132013 /*  1020 */   890,  940,  941,  437,  245,  889,  247,  437,   36,   36,
132014 /*  1030 */   437,  353,  391,  437,  260,  252,  260,  437,  361,  437,
132015 /*  1040 */   706,  437,  370,   12,   12,  224,  437,   27,   27,  437,
132016 /*  1050 */    37,   37,  437,   38,   38,  752,  368,   39,   39,   28,
132017 /*  1060 */    28,   29,   29,  215,  166,  331,   40,   40,  437,   41,
132018 /*  1070 */    41,  437,   42,   42,  437,  866,  246,  731,  437,  879,
132019 /*  1080 */   437,  256,  437,  878,  437,  267,  437,  261,   11,   11,
132020 /*  1090 */   437,   43,   43,  437,   99,   99,  437,  373,   44,   44,
132021 /*  1100 */    45,   45,   32,   32,   46,   46,   47,   47,  437,  426,
132022 /*  1110 */    33,   33,  776,  116,  116,  437,  117,  117,  437,  124,
132023 /*  1120 */   437,  777,  437,  260,  437,  957,  437,  352,  118,  118,
132024 /*  1130 */   437,  195,  437,  111,  437,   53,   53,  264,   34,   34,
132025 /*  1140 */   100,  100,   50,   50,  101,  101,  102,  102,  437,  260,
132026 /*  1150 */    98,   98,  115,  115,  113,  113,  437,  262,  437,  265,
132027 /*  1160 */   437,  943,  958,  437,  727,  437,  681,  437,  106,  106,
132028 /*  1170 */    68,  437,  893,  730,  437,  365,  105,  105,  103,  103,
132029 /*  1180 */   104,  104,  217,   52,   52,   54,   54,   51,   51,  694,
132030 /*  1190 */   259,   26,   26,  266,   30,   30,  677,  323,  433,  323,
132031 /*  1200 */   674,  423,  427,  943,  958,  114,  114,  431,  681,  865,
132032 /*  1210 */  1277,  233,  366,  714,  112,   20,  154,  704,  703,  810,
132033 /*  1220 */   914,   55,  159,  311,  798,  255,  383,  194,   68,  200,
132034 /*  1230 */    21,  694,  268,  114,  114,  114,  270,  711,  712,   68,
132035 /*  1240 */   114,  739,  770,  715,   71,  194,  861,  875,  875,  200,
132036 /*  1250 */   696,  865,  874,  874,  679,  699,  273,  110,  229,  419,
132037 /*  1260 */   768,  810,  799,  378,  748,  759,  418,  210,  294,  281,
132038 /*  1270 */   295,  806,  283,  682,  676,  665,  664,  666,  933,  151,
132039 /*  1280 */   285,    7, 1267,  308,  251,  790,  354,  244,  892,  364,
132040 /*  1290 */   287,  422,  300,  164,  160,  936,  974,  127,  197,  137,
132041 /*  1300 */   909,  907,  971,  388,  276,  863,  862,   56,  698,  325,
132042 /*  1310 */   148,   59,  122,   66,  356,  381,  357,  176,  152,   62,
132043 /*  1320 */   371,  130,  877,  181,  377,  760,  211,  182,  132,  133,
132044 /*  1330 */   134,  135,  258,  146,  140,  795,  787,  263,  183,  379,
132045 /*  1340 */   667,  394,  184,  332,  894,  314,  718,  717,  857,  716,
132046 /*  1350 */   696,  315,  709,  690,   65,  196,    6,  408,  289,  708,
132047 /*  1360 */   275,  689,  688,  948,  756,  757,  280,  282,  425,  755,
132048 /*  1370 */   284,  336,   73,   67,  754,  429,  411,   96,  286,  413,
132049 /*  1380 */   205,  934,  673,   22,  209,  440,  119,  120,  109,  206,
132050 /*  1390 */   208,  441,  662,  661,  656,  843,  654,  343,  158,  236,
132051 /*  1400 */   170,  347,  107,  227,  121,  738,  873,  298,  296,  297,
132052 /*  1410 */   299,  871,  794,  128,  129,  728,  230,  131,  175,  250,
132053 /*  1420 */   888,  136,  138,  231,  232,  139,   60,   61,  891,  178,
132054 /*  1430 */   179,  887,    8,   13,  180,  257,  880,  968,  194,  141,
132055 /*  1440 */   142,  376,  153,  670,  380,  185,  143,  277,   63,  384,
132056 /*  1450 */    14,  707,  271,   15,  389,   64,  319,  320,  126,  228,
132057 /*  1460 */   813,  812,  841,  736,  123,   16,  401,  740,    4,  769,
132058 /*  1470 */   165,  212,  214,  193,  144,  764,   71,   68,   17,   18,
132059 /*  1480 */   856,  842,  840,  897,  845,  896,  199,  198,  923,  155,
132060 /*  1490 */   424,  929,  924,  156,  201,  202,  428,  844,  157,  203,
132061 /*  1500 */   811,  680,   81, 1269, 1268,  301,  304,
132062};
132063static const YYCODETYPE yy_lookahead[] = {
132064 /*     0 */    19,   95,   53,   97,   22,   24,   24,  101,   27,   28,
132065 /*    10 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
132066 /*    20 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
132067 /*    30 */    49,   50,   51,   52,   53,   19,   55,   55,  132,  133,
132068 /*    40 */   134,    1,    2,   27,   28,   29,   30,   31,   32,   33,
132069 /*    50 */    34,   35,   36,   37,   38,   39,   40,   41,  187,   43,
132070 /*    60 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
132071 /*    70 */    47,   48,   49,   50,   51,   52,   53,   61,   97,   97,
132072 /*    80 */    19,   49,   50,   51,   52,   53,   70,   26,   27,   28,
132073 /*    90 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
132074 /*   100 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
132075 /*   110 */    49,   50,   51,   52,   53,  144,  145,  146,  147,   19,
132076 /*   120 */   137,   22,  139,  172,  173,   52,   53,   27,   28,   29,
132077 /*   130 */    30,   31,   32,   33,   34,   35,   36,   37,   38,   39,
132078 /*   140 */    40,   41,   81,   43,   44,   45,   46,   47,   48,   49,
132079 /*   150 */    50,   51,   52,   53,   55,   56,   19,  152,  207,  208,
132080 /*   160 */   115,   24,  117,  118,   27,   28,   29,   30,   31,   32,
132081 /*   170 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   79,
132082 /*   180 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132083 /*   190 */    53,   19,    0,    1,    2,   23,   97,   98,  193,   27,
132084 /*   200 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132085 /*   210 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
132086 /*   220 */    48,   49,   50,   51,   52,   53,   19,   22,   23,  163,
132087 /*   230 */    23,   26,  190,  191,   27,   28,   29,   30,   31,   32,
132088 /*   240 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  187,
132089 /*   250 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132090 /*   260 */    53,   19,  196,   22,   23,   23,   49,   26,   92,   27,
132091 /*   270 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132092 /*   280 */    38,   39,   40,   41,  172,   43,   44,   45,   46,   47,
132093 /*   290 */    48,   49,   50,   51,   52,   53,   19,  221,  222,  223,
132094 /*   300 */    23,   96,  119,  120,   27,   28,   29,   30,   31,   32,
132095 /*   310 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  172,
132096 /*   320 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132097 /*   330 */    53,   19,  152,  116,  221,  222,  223,   96,  121,   27,
132098 /*   340 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132099 /*   350 */    38,   39,   40,   41,  241,   43,   44,   45,   46,   47,
132100 /*   360 */    48,   49,   50,   51,   52,   53,   19,  157,  168,  169,
132101 /*   370 */   170,   22,  190,  191,   27,   28,   29,   30,   31,   32,
132102 /*   380 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   30,
132103 /*   390 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132104 /*   400 */    53,   19,  172,  152,   55,   56,   24,  247,  248,   27,
132105 /*   410 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132106 /*   420 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
132107 /*   430 */    48,   49,   50,   51,   52,   53,  146,  147,  228,  179,
132108 /*   440 */   180,  231,  185,   19,  172,  173,   97,   98,  188,   26,
132109 /*   450 */   138,   27,   28,   29,   30,   31,   32,   33,   34,   35,
132110 /*   460 */    36,   37,   38,   39,   40,   41,  107,   43,   44,   45,
132111 /*   470 */    46,   47,   48,   49,   50,   51,   52,   53,   19,  207,
132112 /*   480 */   208,   30,   31,   32,   33,  138,   27,   28,   29,   30,
132113 /*   490 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
132114 /*   500 */    41,  250,   43,   44,   45,   46,   47,   48,   49,   50,
132115 /*   510 */    51,   52,   53,   19,  168,  169,  170,    7,    8,    9,
132116 /*   520 */    19,  152,   28,   29,   30,   31,   32,   33,   34,   35,
132117 /*   530 */    36,   37,   38,   39,   40,   41,  152,   43,   44,   45,
132118 /*   540 */    46,   47,   48,   49,   50,   51,   52,   53,   19,  108,
132119 /*   550 */   109,  110,  101,  130,   53,  152,  172,  173,   29,   30,
132120 /*   560 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
132121 /*   570 */    41,  152,   43,   44,   45,   46,   47,   48,   49,   50,
132122 /*   580 */    51,   52,   53,   19,   20,  116,   22,   23,  169,  170,
132123 /*   590 */   121,  207,   85,   55,   56,   26,   19,   20,  101,   22,
132124 /*   600 */    99,  100,  101,  102,  103,  104,  105,  152,  152,  112,
132125 /*   610 */   210,   47,   48,  112,  152,  108,  109,  110,   54,   55,
132126 /*   620 */    56,  221,  222,  223,   47,   48,  119,  120,  172,  173,
132127 /*   630 */    66,   54,   55,   56,  152,   97,   98,   99,  148,  149,
132128 /*   640 */   102,  103,  104,   66,  154,   23,  156,   83,   26,  230,
132129 /*   650 */   152,  113,  152,  163,  172,  173,   92,   92,   21,   95,
132130 /*   660 */    83,   97,   98,  207,  208,  101,  152,   98,  186,   92,
132131 /*   670 */   172,  173,   95,  218,   97,   98,  152,   99,  101,  217,
132132 /*   680 */   102,  103,  104,  152,  119,  120,  196,   55,   56,   19,
132133 /*   690 */    20,  113,   22,  124,  163,   11,  132,  133,  134,  135,
132134 /*   700 */   136,  152,  152,  172,  173,  207,  208,  152,  152,  132,
132135 /*   710 */   133,  134,  135,  136,  164,  152,   84,   47,   48,   49,
132136 /*   720 */    98,  181,  152,  152,   54,   55,   56,  196,   91,   97,
132137 /*   730 */    98,  160,  218,  163,  244,  164,   66,  152,  207,  208,
132138 /*   740 */   103,  217,  172,  173,   19,   20,  124,   22,  193,   38,
132139 /*   750 */    39,   40,   41,   83,   43,   44,   45,   46,   47,   48,
132140 /*   760 */    49,   50,   51,   52,   53,   95,  196,   97,   98,   85,
132141 /*   770 */   152,  101,   47,   48,  181,   85,   92,  140,  193,   54,
132142 /*   780 */    55,   56,   92,   49,  195,   55,   56,  175,  163,   55,
132143 /*   790 */    56,   66,  108,  109,  110,  206,  163,  242,  108,  109,
132144 /*   800 */   110,  175,  132,  133,  134,  135,  136,  152,   83,   43,
132145 /*   810 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
132146 /*   820 */    95,  196,   97,   98,   55,   56,  101,   97,   98,  196,
132147 /*   830 */   152,   97,   98,  221,  222,  223,  211,  212,   22,   23,
132148 /*   840 */    19,   20,  181,   22,   19,  152,  152,  221,  222,  223,
132149 /*   850 */   172,  173,  219,   19,  124,   30,  238,  132,  133,  134,
132150 /*   860 */   135,  136,  169,  170,  186,  232,   97,   98,   47,   48,
132151 /*   870 */   237,  152,  217,  152,    5,   54,   55,   56,  152,   10,
132152 /*   880 */    11,   12,   13,   14,   47,   48,   17,   66,   47,   48,
132153 /*   890 */    56,  172,  173,  124,  194,  195,   55,   56,  172,  173,
132154 /*   900 */   152,  152,   22,  152,   83,  186,  206,  108,  109,  110,
132155 /*   910 */    22,   23,   96,  152,  193,   12,   95,  152,   97,   98,
132156 /*   920 */   172,  173,  101,  230,  152,  164,   12,   47,   48,   60,
132157 /*   930 */   152,   62,  107,  207,  186,   55,   56,  112,   97,   98,
132158 /*   940 */    71,  100,  193,  152,  183,  152,  185,  152,  107,  152,
132159 /*   950 */   109,   82,   16,  132,  133,  134,  135,  136,   89,  152,
132160 /*   960 */    57,   92,   93,  172,  173,  172,  173,  172,  173,  132,
132161 /*   970 */   133,   57,  152,  132,  133,   95,   73,   97,   75,   55,
132162 /*   980 */    56,  101,  163,  114,   96,  245,  246,   73,   85,   75,
132163 /*   990 */    38,   39,   40,   41,   42,   43,   44,   45,   46,   47,
132164 /*  1000 */    48,   49,   50,   51,   52,   53,  194,  195,  152,  171,
132165 /*  1010 */   141,  152,  132,  133,  134,  196,  225,  179,  206,   65,
132166 /*  1020 */   152,   97,   98,  152,   88,  152,   90,  152,  172,  173,
132167 /*  1030 */   152,  219,   78,  152,  152,  238,  152,  152,  219,  152,
132168 /*  1040 */    86,  152,  152,  172,  173,  238,  152,  172,  173,  152,
132169 /*  1050 */   172,  173,  152,  172,  173,  213,  237,  172,  173,  172,
132170 /*  1060 */   173,  172,  173,  211,  212,  111,  172,  173,  152,  172,
132171 /*  1070 */   173,  152,  172,  173,  152,  193,  140,  193,  152,   59,
132172 /*  1080 */   152,  152,  152,   63,  152,   16,  152,  152,  172,  173,
132173 /*  1090 */   152,  172,  173,  152,  172,  173,  152,   77,  172,  173,
132174 /*  1100 */   172,  173,  172,  173,  172,  173,  172,  173,  152,  250,
132175 /*  1110 */   172,  173,   61,  172,  173,  152,  172,  173,  152,   92,
132176 /*  1120 */   152,   70,  152,  152,  152,   26,  152,  100,  172,  173,
132177 /*  1130 */   152,   24,  152,   22,  152,  172,  173,  152,  172,  173,
132178 /*  1140 */   172,  173,  172,  173,  172,  173,  172,  173,  152,  152,
132179 /*  1150 */   172,  173,  172,  173,  172,  173,  152,   88,  152,   90,
132180 /*  1160 */   152,   55,   55,  152,  193,  152,   55,  152,  172,  173,
132181 /*  1170 */    26,  152,  163,  163,  152,   19,  172,  173,  172,  173,
132182 /*  1180 */   172,  173,   22,  172,  173,  172,  173,  172,  173,   55,
132183 /*  1190 */   193,  172,  173,  152,  172,  173,  166,  167,  166,  167,
132184 /*  1200 */   163,  163,  163,   97,   97,  196,  196,  163,   97,   55,
132185 /*  1210 */    23,  199,   56,   26,   22,   22,   24,  100,  101,   55,
132186 /*  1220 */    23,  209,  123,   26,   23,   23,   23,   26,   26,   26,
132187 /*  1230 */    37,   97,  152,  196,  196,  196,   23,    7,    8,   26,
132188 /*  1240 */   196,   23,   23,  152,   26,   26,   23,  132,  133,   26,
132189 /*  1250 */   106,   97,  132,  133,   23,  152,  152,   26,  210,  191,
132190 /*  1260 */   152,   97,  152,  234,  152,  152,  152,  233,  152,  210,
132191 /*  1270 */   152,  152,  210,  152,  152,  152,  152,  152,  152,  197,
132192 /*  1280 */   210,  198,  122,  150,  239,  201,  214,  214,  201,  239,
132193 /*  1290 */   214,  227,  200,  184,  198,  155,   67,  243,  122,   22,
132194 /*  1300 */   159,  159,   69,  176,  175,  175,  175,  240,  180,  159,
132195 /*  1310 */   220,  240,   27,  130,   18,   18,  159,  158,  220,  137,
132196 /*  1320 */   159,  189,  236,  158,   74,  159,  159,  158,  192,  192,
132197 /*  1330 */   192,  192,  235,   22,  189,  189,  201,  159,  158,  177,
132198 /*  1340 */   159,  107,  158,   76,  201,  177,  174,  174,  201,  174,
132199 /*  1350 */   106,  177,  182,  174,  107,  159,   22,  125,  159,  182,
132200 /*  1360 */   174,  176,  174,  174,  216,  216,  215,  215,  177,  216,
132201 /*  1370 */   215,   53,  137,  128,  216,  177,  127,  129,  215,  126,
132202 /*  1380 */    25,   13,  162,   26,    6,  161,  165,  165,  178,  153,
132203 /*  1390 */   153,  151,  151,  151,  151,  224,    4,    3,   22,  142,
132204 /*  1400 */    15,   94,   16,  178,  165,  205,   23,  202,  204,  203,
132205 /*  1410 */   201,   23,  120,  131,  111,   20,  226,  123,  125,   16,
132206 /*  1420 */     1,  123,  131,  229,  229,  111,   37,   37,   56,   64,
132207 /*  1430 */   122,    1,    5,   22,  107,  140,   80,   87,   26,   80,
132208 /*  1440 */   107,   72,   24,   20,   19,  105,   22,  112,   22,   79,
132209 /*  1450 */    22,   58,   23,   22,   79,   22,  249,  249,  246,   79,
132210 /*  1460 */    23,   23,   23,  116,   68,   22,   26,   23,   22,   56,
132211 /*  1470 */   122,   23,   23,   64,   22,  124,   26,   26,   64,   64,
132212 /*  1480 */    23,   23,   23,   23,   11,   23,   22,   26,   23,   22,
132213 /*  1490 */    24,    1,   23,   22,   26,  122,   24,   23,   22,  122,
132214 /*  1500 */    23,   23,   22,  122,  122,   23,   15,
132215};
132216#define YY_SHIFT_USE_DFLT (-95)
132217#define YY_SHIFT_COUNT (442)
132218#define YY_SHIFT_MIN   (-94)
132219#define YY_SHIFT_MAX   (1491)
132220static const short yy_shift_ofst[] = {
132221 /*     0 */    40,  564,  869,  577,  725,  725,  725,  725,  690,  -19,
132222 /*    10 */    16,   16,  100,  725,  725,  725,  725,  725,  725,  725,
132223 /*    20 */   841,  841,  538,  507,  684,  565,   61,  137,  172,  207,
132224 /*    30 */   242,  277,  312,  347,  382,  424,  424,  424,  424,  424,
132225 /*    40 */   424,  424,  424,  424,  424,  424,  424,  424,  424,  424,
132226 /*    50 */   459,  424,  494,  529,  529,  670,  725,  725,  725,  725,
132227 /*    60 */   725,  725,  725,  725,  725,  725,  725,  725,  725,  725,
132228 /*    70 */   725,  725,  725,  725,  725,  725,  725,  725,  725,  725,
132229 /*    80 */   725,  725,  725,  725,  821,  725,  725,  725,  725,  725,
132230 /*    90 */   725,  725,  725,  725,  725,  725,  725,  725,  952,  711,
132231 /*   100 */   711,  711,  711,  711,  766,   23,   32,  924,  637,  825,
132232 /*   110 */   837,  837,  924,   73,  183,  -51,  -95,  -95,  -95,  501,
132233 /*   120 */   501,  501,  903,  903,  632,  205,  241,  924,  924,  924,
132234 /*   130 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132235 /*   140 */   924,  924,  924,  924,  924,  924,  924,  192, 1027, 1106,
132236 /*   150 */  1106,  183,  176,  176,  176,  176,  176,  176,  -95,  -95,
132237 /*   160 */   -95,  880,  -94,  -94,  578,  734,   99,  730,  769,  349,
132238 /*   170 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132239 /*   180 */   924,  924,  924,  924,  924,  924,  924,  954,  954,  954,
132240 /*   190 */   924,  924,  622,  924,  924,  924,  -18,  924,  924,  914,
132241 /*   200 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132242 /*   210 */   441, 1020, 1107, 1107, 1107,  569,   45,  217,  510,  423,
132243 /*   220 */   834,  834, 1156,  423, 1156, 1144, 1187,  359, 1051,  834,
132244 /*   230 */   -17, 1051, 1051, 1099,  469, 1192, 1229, 1176, 1176, 1233,
132245 /*   240 */  1233, 1176, 1277, 1285, 1183, 1296, 1296, 1296, 1296, 1176,
132246 /*   250 */  1297, 1183, 1277, 1285, 1285, 1183, 1176, 1297, 1182, 1250,
132247 /*   260 */  1176, 1176, 1297, 1311, 1176, 1297, 1176, 1297, 1311, 1234,
132248 /*   270 */  1234, 1234, 1267, 1311, 1234, 1244, 1234, 1267, 1234, 1234,
132249 /*   280 */  1232, 1247, 1232, 1247, 1232, 1247, 1232, 1247, 1176, 1334,
132250 /*   290 */  1176, 1235, 1311, 1318, 1318, 1311, 1248, 1253, 1245, 1249,
132251 /*   300 */  1183, 1355, 1357, 1368, 1368, 1378, 1378, 1378, 1378,  -95,
132252 /*   310 */   -95,  -95,  -95,  -95,  -95,  -95,  -95,  451,  936,  816,
132253 /*   320 */   888, 1069,  799, 1111, 1197, 1193, 1201, 1202, 1203, 1213,
132254 /*   330 */  1134, 1117, 1230,  497, 1218, 1219, 1154, 1223, 1115, 1120,
132255 /*   340 */  1231, 1164, 1160, 1392, 1394, 1376, 1257, 1385, 1307, 1386,
132256 /*   350 */  1383, 1388, 1292, 1282, 1303, 1294, 1395, 1293, 1403, 1419,
132257 /*   360 */  1298, 1291, 1389, 1390, 1314, 1372, 1365, 1308, 1430, 1427,
132258 /*   370 */  1411, 1327, 1295, 1356, 1412, 1359, 1350, 1369, 1333, 1418,
132259 /*   380 */  1423, 1425, 1335, 1340, 1424, 1370, 1426, 1428, 1429, 1431,
132260 /*   390 */  1375, 1393, 1433, 1380, 1396, 1437, 1438, 1439, 1347, 1443,
132261 /*   400 */  1444, 1446, 1440, 1348, 1448, 1449, 1413, 1409, 1452, 1351,
132262 /*   410 */  1450, 1414, 1451, 1415, 1457, 1450, 1458, 1459, 1460, 1461,
132263 /*   420 */  1462, 1464, 1473, 1465, 1467, 1466, 1468, 1469, 1471, 1472,
132264 /*   430 */  1468, 1474, 1476, 1477, 1478, 1480, 1373, 1377, 1381, 1382,
132265 /*   440 */  1482, 1491, 1490,
132266};
132267#define YY_REDUCE_USE_DFLT (-130)
132268#define YY_REDUCE_COUNT (316)
132269#define YY_REDUCE_MIN   (-129)
132270#define YY_REDUCE_MAX   (1243)
132271static const short yy_reduce_ofst[] = {
132272 /*     0 */   -29,  531,  490,  570,  -49,  272,  456,  498,  633,  400,
132273 /*    10 */   612,  626,  113,  482,  678,  719,  384,  726,  748,  791,
132274 /*    20 */   419,  693,  761,  812,  819,  625,   76,   76,   76,   76,
132275 /*    30 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
132276 /*    40 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
132277 /*    50 */    76,   76,   76,   76,   76,  793,  795,  856,  871,  875,
132278 /*    60 */   878,  881,  885,  887,  889,  894,  897,  900,  916,  919,
132279 /*    70 */   922,  926,  928,  930,  932,  934,  938,  941,  944,  956,
132280 /*    80 */   963,  966,  968,  970,  972,  974,  978,  980,  982,  996,
132281 /*    90 */  1004, 1006, 1008, 1011, 1013, 1015, 1019, 1022,   76,   76,
132282 /*   100 */    76,   76,   76,   76,   76,   76,   76,  555,  210,  260,
132283 /*   110 */   200,  346,  571,   76,  700,   76,   76,   76,   76,  838,
132284 /*   120 */   838,  838,   42,  182,  251,  160,  160,  550,    5,  455,
132285 /*   130 */   585,  721,  749,  882,  884,  971,  618,  462,  797,  514,
132286 /*   140 */   807,  524,  997, -129,  655,  859,   62,  290,   66, 1030,
132287 /*   150 */  1032,  589, 1009, 1010, 1037, 1038, 1039, 1044,  740,  852,
132288 /*   160 */  1012,  112,  147,  230,  257,  180,  369,  403,  500,  549,
132289 /*   170 */   556,  563,  694,  751,  765,  772,  778,  820,  868,  873,
132290 /*   180 */   890,  929,  935,  985, 1041, 1080, 1091,  540,  593,  661,
132291 /*   190 */  1103, 1104,  842, 1108, 1110, 1112, 1048, 1113, 1114, 1068,
132292 /*   200 */  1116, 1118, 1119,  180, 1121, 1122, 1123, 1124, 1125, 1126,
132293 /*   210 */  1029, 1034, 1059, 1062, 1070,  842, 1082, 1083, 1133, 1084,
132294 /*   220 */  1072, 1073, 1045, 1087, 1050, 1127, 1109, 1128, 1129, 1076,
132295 /*   230 */  1064, 1130, 1131, 1092, 1096, 1140, 1054, 1141, 1142, 1067,
132296 /*   240 */  1071, 1150, 1090, 1132, 1135, 1136, 1137, 1138, 1139, 1157,
132297 /*   250 */  1159, 1143, 1098, 1145, 1146, 1147, 1161, 1165, 1086, 1097,
132298 /*   260 */  1166, 1167, 1169, 1162, 1178, 1180, 1181, 1184, 1168, 1172,
132299 /*   270 */  1173, 1175, 1170, 1174, 1179, 1185, 1186, 1177, 1188, 1189,
132300 /*   280 */  1148, 1151, 1149, 1152, 1153, 1155, 1158, 1163, 1196, 1171,
132301 /*   290 */  1199, 1190, 1191, 1194, 1195, 1198, 1200, 1204, 1206, 1205,
132302 /*   300 */  1209, 1220, 1224, 1236, 1237, 1240, 1241, 1242, 1243, 1207,
132303 /*   310 */  1208, 1212, 1221, 1222, 1210, 1225, 1239,
132304};
132305static const YYACTIONTYPE yy_default[] = {
132306 /*     0 */  1258, 1248, 1248, 1248, 1180, 1180, 1180, 1180, 1248, 1077,
132307 /*    10 */  1106, 1106, 1232, 1309, 1309, 1309, 1309, 1309, 1309, 1179,
132308 /*    20 */  1309, 1309, 1309, 1309, 1248, 1081, 1112, 1309, 1309, 1309,
132309 /*    30 */  1309, 1309, 1309, 1309, 1309, 1231, 1233, 1120, 1119, 1214,
132310 /*    40 */  1093, 1117, 1110, 1114, 1181, 1175, 1176, 1174, 1178, 1182,
132311 /*    50 */  1309, 1113, 1144, 1159, 1143, 1309, 1309, 1309, 1309, 1309,
132312 /*    60 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132313 /*    70 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132314 /*    80 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132315 /*    90 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1153, 1158,
132316 /*   100 */  1165, 1157, 1154, 1146, 1145, 1147, 1148, 1309, 1000, 1048,
132317 /*   110 */  1309, 1309, 1309, 1149, 1309, 1150, 1162, 1161, 1160, 1239,
132318 /*   120 */  1266, 1265, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132319 /*   130 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132320 /*   140 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1258, 1248, 1006,
132321 /*   150 */  1006, 1309, 1248, 1248, 1248, 1248, 1248, 1248, 1244, 1081,
132322 /*   160 */  1072, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132323 /*   170 */  1309, 1236, 1234, 1309, 1195, 1309, 1309, 1309, 1309, 1309,
132324 /*   180 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132325 /*   190 */  1309, 1309, 1309, 1309, 1309, 1309, 1077, 1309, 1309, 1309,
132326 /*   200 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1260,
132327 /*   210 */  1309, 1209, 1077, 1077, 1077, 1079, 1061, 1071,  985, 1116,
132328 /*   220 */  1095, 1095, 1298, 1116, 1298, 1023, 1280, 1020, 1106, 1095,
132329 /*   230 */  1177, 1106, 1106, 1078, 1071, 1309, 1301, 1086, 1086, 1300,
132330 /*   240 */  1300, 1086, 1125, 1051, 1116, 1057, 1057, 1057, 1057, 1086,
132331 /*   250 */   997, 1116, 1125, 1051, 1051, 1116, 1086,  997, 1213, 1295,
132332 /*   260 */  1086, 1086,  997, 1188, 1086,  997, 1086,  997, 1188, 1049,
132333 /*   270 */  1049, 1049, 1038, 1188, 1049, 1023, 1049, 1038, 1049, 1049,
132334 /*   280 */  1099, 1094, 1099, 1094, 1099, 1094, 1099, 1094, 1086, 1183,
132335 /*   290 */  1086, 1309, 1188, 1192, 1192, 1188, 1111, 1100, 1109, 1107,
132336 /*   300 */  1116, 1003, 1041, 1263, 1263, 1259, 1259, 1259, 1259, 1306,
132337 /*   310 */  1306, 1244, 1275, 1275, 1025, 1025, 1275, 1309, 1309, 1309,
132338 /*   320 */  1309, 1309, 1309, 1270, 1309, 1197, 1309, 1309, 1309, 1309,
132339 /*   330 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132340 /*   340 */  1309, 1309, 1131, 1309,  981, 1241, 1309, 1309, 1240, 1309,
132341 /*   350 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132342 /*   360 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1297, 1309, 1309,
132343 /*   370 */  1309, 1309, 1309, 1309, 1212, 1211, 1309, 1309, 1309, 1309,
132344 /*   380 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132345 /*   390 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1063, 1309,
132346 /*   400 */  1309, 1309, 1284, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132347 /*   410 */  1108, 1309, 1101, 1309, 1309, 1288, 1309, 1309, 1309, 1309,
132348 /*   420 */  1309, 1309, 1309, 1309, 1309, 1309, 1250, 1309, 1309, 1309,
132349 /*   430 */  1249, 1309, 1309, 1309, 1309, 1309, 1133, 1309, 1132, 1136,
132350 /*   440 */  1309,  991, 1309,
132351};
132352/********** End of lemon-generated parsing tables *****************************/
132353
132354/* The next table maps tokens (terminal symbols) into fallback tokens.
132355** If a construct like the following:
132356**
132357**      %fallback ID X Y Z.
132358**
132359** appears in the grammar, then ID becomes a fallback token for X, Y,
132360** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
132361** but it does not parse, the type of the token is changed to ID and
132362** the parse is retried before an error is thrown.
132363**
132364** This feature can be used, for example, to cause some keywords in a language
132365** to revert to identifiers if they keyword does not apply in the context where
132366** it appears.
132367*/
132368#ifdef YYFALLBACK
132369static const YYCODETYPE yyFallback[] = {
132370    0,  /*          $ => nothing */
132371    0,  /*       SEMI => nothing */
132372   55,  /*    EXPLAIN => ID */
132373   55,  /*      QUERY => ID */
132374   55,  /*       PLAN => ID */
132375   55,  /*      BEGIN => ID */
132376    0,  /* TRANSACTION => nothing */
132377   55,  /*   DEFERRED => ID */
132378   55,  /*  IMMEDIATE => ID */
132379   55,  /*  EXCLUSIVE => ID */
132380    0,  /*     COMMIT => nothing */
132381   55,  /*        END => ID */
132382   55,  /*   ROLLBACK => ID */
132383   55,  /*  SAVEPOINT => ID */
132384   55,  /*    RELEASE => ID */
132385    0,  /*         TO => nothing */
132386    0,  /*      TABLE => nothing */
132387    0,  /*     CREATE => nothing */
132388   55,  /*         IF => ID */
132389    0,  /*        NOT => nothing */
132390    0,  /*     EXISTS => nothing */
132391   55,  /*       TEMP => ID */
132392    0,  /*         LP => nothing */
132393    0,  /*         RP => nothing */
132394    0,  /*         AS => nothing */
132395   55,  /*    WITHOUT => ID */
132396    0,  /*      COMMA => nothing */
132397    0,  /*         OR => nothing */
132398    0,  /*        AND => nothing */
132399    0,  /*         IS => nothing */
132400   55,  /*      MATCH => ID */
132401   55,  /*    LIKE_KW => ID */
132402    0,  /*    BETWEEN => nothing */
132403    0,  /*         IN => nothing */
132404    0,  /*     ISNULL => nothing */
132405    0,  /*    NOTNULL => nothing */
132406    0,  /*         NE => nothing */
132407    0,  /*         EQ => nothing */
132408    0,  /*         GT => nothing */
132409    0,  /*         LE => nothing */
132410    0,  /*         LT => nothing */
132411    0,  /*         GE => nothing */
132412    0,  /*     ESCAPE => nothing */
132413    0,  /*     BITAND => nothing */
132414    0,  /*      BITOR => nothing */
132415    0,  /*     LSHIFT => nothing */
132416    0,  /*     RSHIFT => nothing */
132417    0,  /*       PLUS => nothing */
132418    0,  /*      MINUS => nothing */
132419    0,  /*       STAR => nothing */
132420    0,  /*      SLASH => nothing */
132421    0,  /*        REM => nothing */
132422    0,  /*     CONCAT => nothing */
132423    0,  /*    COLLATE => nothing */
132424    0,  /*     BITNOT => nothing */
132425    0,  /*         ID => nothing */
132426    0,  /*    INDEXED => nothing */
132427   55,  /*      ABORT => ID */
132428   55,  /*     ACTION => ID */
132429   55,  /*      AFTER => ID */
132430   55,  /*    ANALYZE => ID */
132431   55,  /*        ASC => ID */
132432   55,  /*     ATTACH => ID */
132433   55,  /*     BEFORE => ID */
132434   55,  /*         BY => ID */
132435   55,  /*    CASCADE => ID */
132436   55,  /*       CAST => ID */
132437   55,  /*   COLUMNKW => ID */
132438   55,  /*   CONFLICT => ID */
132439   55,  /*   DATABASE => ID */
132440   55,  /*       DESC => ID */
132441   55,  /*     DETACH => ID */
132442   55,  /*       EACH => ID */
132443   55,  /*       FAIL => ID */
132444   55,  /*        FOR => ID */
132445   55,  /*     IGNORE => ID */
132446   55,  /*  INITIALLY => ID */
132447   55,  /*    INSTEAD => ID */
132448   55,  /*         NO => ID */
132449   55,  /*        KEY => ID */
132450   55,  /*         OF => ID */
132451   55,  /*     OFFSET => ID */
132452   55,  /*     PRAGMA => ID */
132453   55,  /*      RAISE => ID */
132454   55,  /*  RECURSIVE => ID */
132455   55,  /*    REPLACE => ID */
132456   55,  /*   RESTRICT => ID */
132457   55,  /*        ROW => ID */
132458   55,  /*    TRIGGER => ID */
132459   55,  /*     VACUUM => ID */
132460   55,  /*       VIEW => ID */
132461   55,  /*    VIRTUAL => ID */
132462   55,  /*       WITH => ID */
132463   55,  /*    REINDEX => ID */
132464   55,  /*     RENAME => ID */
132465   55,  /*   CTIME_KW => ID */
132466};
132467#endif /* YYFALLBACK */
132468
132469/* The following structure represents a single element of the
132470** parser's stack.  Information stored includes:
132471**
132472**   +  The state number for the parser at this level of the stack.
132473**
132474**   +  The value of the token stored at this level of the stack.
132475**      (In other words, the "major" token.)
132476**
132477**   +  The semantic value stored at this level of the stack.  This is
132478**      the information used by the action routines in the grammar.
132479**      It is sometimes called the "minor" token.
132480**
132481** After the "shift" half of a SHIFTREDUCE action, the stateno field
132482** actually contains the reduce action for the second half of the
132483** SHIFTREDUCE.
132484*/
132485struct yyStackEntry {
132486  YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
132487  YYCODETYPE major;      /* The major token value.  This is the code
132488                         ** number for the token at this stack level */
132489  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
132490                         ** is the value of the token  */
132491};
132492typedef struct yyStackEntry yyStackEntry;
132493
132494/* The state of the parser is completely contained in an instance of
132495** the following structure */
132496struct yyParser {
132497  yyStackEntry *yytos;          /* Pointer to top element of the stack */
132498#ifdef YYTRACKMAXSTACKDEPTH
132499  int yyhwm;                    /* High-water mark of the stack */
132500#endif
132501#ifndef YYNOERRORRECOVERY
132502  int yyerrcnt;                 /* Shifts left before out of the error */
132503#endif
132504  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
132505#if YYSTACKDEPTH<=0
132506  int yystksz;                  /* Current side of the stack */
132507  yyStackEntry *yystack;        /* The parser's stack */
132508  yyStackEntry yystk0;          /* First stack entry */
132509#else
132510  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
132511#endif
132512};
132513typedef struct yyParser yyParser;
132514
132515#ifndef NDEBUG
132516/* #include <stdio.h> */
132517static FILE *yyTraceFILE = 0;
132518static char *yyTracePrompt = 0;
132519#endif /* NDEBUG */
132520
132521#ifndef NDEBUG
132522/*
132523** Turn parser tracing on by giving a stream to which to write the trace
132524** and a prompt to preface each trace message.  Tracing is turned off
132525** by making either argument NULL
132526**
132527** Inputs:
132528** <ul>
132529** <li> A FILE* to which trace output should be written.
132530**      If NULL, then tracing is turned off.
132531** <li> A prefix string written at the beginning of every
132532**      line of trace output.  If NULL, then tracing is
132533**      turned off.
132534** </ul>
132535**
132536** Outputs:
132537** None.
132538*/
132539SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
132540  yyTraceFILE = TraceFILE;
132541  yyTracePrompt = zTracePrompt;
132542  if( yyTraceFILE==0 ) yyTracePrompt = 0;
132543  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
132544}
132545#endif /* NDEBUG */
132546
132547#ifndef NDEBUG
132548/* For tracing shifts, the names of all terminals and nonterminals
132549** are required.  The following table supplies these names */
132550static const char *const yyTokenName[] = {
132551  "$",             "SEMI",          "EXPLAIN",       "QUERY",
132552  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
132553  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
132554  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
132555  "TABLE",         "CREATE",        "IF",            "NOT",
132556  "EXISTS",        "TEMP",          "LP",            "RP",
132557  "AS",            "WITHOUT",       "COMMA",         "OR",
132558  "AND",           "IS",            "MATCH",         "LIKE_KW",
132559  "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",
132560  "NE",            "EQ",            "GT",            "LE",
132561  "LT",            "GE",            "ESCAPE",        "BITAND",
132562  "BITOR",         "LSHIFT",        "RSHIFT",        "PLUS",
132563  "MINUS",         "STAR",          "SLASH",         "REM",
132564  "CONCAT",        "COLLATE",       "BITNOT",        "ID",
132565  "INDEXED",       "ABORT",         "ACTION",        "AFTER",
132566  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
132567  "BY",            "CASCADE",       "CAST",          "COLUMNKW",
132568  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
132569  "EACH",          "FAIL",          "FOR",           "IGNORE",
132570  "INITIALLY",     "INSTEAD",       "NO",            "KEY",
132571  "OF",            "OFFSET",        "PRAGMA",        "RAISE",
132572  "RECURSIVE",     "REPLACE",       "RESTRICT",      "ROW",
132573  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
132574  "WITH",          "REINDEX",       "RENAME",        "CTIME_KW",
132575  "ANY",           "STRING",        "JOIN_KW",       "CONSTRAINT",
132576  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
132577  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
132578  "INSERT",        "DELETE",        "UPDATE",        "SET",
132579  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
132580  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
132581  "VALUES",        "DISTINCT",      "DOT",           "FROM",
132582  "JOIN",          "USING",         "ORDER",         "GROUP",
132583  "HAVING",        "LIMIT",         "WHERE",         "INTO",
132584  "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
132585  "CASE",          "WHEN",          "THEN",          "ELSE",
132586  "INDEX",         "ALTER",         "ADD",           "error",
132587  "input",         "cmdlist",       "ecmd",          "explain",
132588  "cmdx",          "cmd",           "transtype",     "trans_opt",
132589  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
132590  "createkw",      "temp",          "ifnotexists",   "dbnm",
132591  "columnlist",    "conslist_opt",  "table_options",  "select",
132592  "columnname",    "carglist",      "typetoken",     "typename",
132593  "signed",        "plus_num",      "minus_num",     "ccons",
132594  "term",          "expr",          "onconf",        "sortorder",
132595  "autoinc",       "eidlist_opt",   "refargs",       "defer_subclause",
132596  "refarg",        "refact",        "init_deferred_pred_opt",  "conslist",
132597  "tconscomma",    "tcons",         "sortlist",      "eidlist",
132598  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
132599  "ifexists",      "fullname",      "selectnowith",  "oneselect",
132600  "with",          "multiselect_op",  "distinct",      "selcollist",
132601  "from",          "where_opt",     "groupby_opt",   "having_opt",
132602  "orderby_opt",   "limit_opt",     "values",        "nexprlist",
132603  "exprlist",      "sclp",          "as",            "seltablist",
132604  "stl_prefix",    "joinop",        "indexed_opt",   "on_opt",
132605  "using_opt",     "idlist",        "setlist",       "insert_cmd",
132606  "idlist_opt",    "likeop",        "between_op",    "in_op",
132607  "paren_exprlist",  "case_operand",  "case_exprlist",  "case_else",
132608  "uniqueflag",    "collate",       "nmnum",         "trigger_decl",
132609  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
132610  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
132611  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
132612  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
132613  "lp",            "anylist",       "wqlist",
132614};
132615#endif /* NDEBUG */
132616
132617#ifndef NDEBUG
132618/* For tracing reduce actions, the names of all rules are required.
132619*/
132620static const char *const yyRuleName[] = {
132621 /*   0 */ "explain ::= EXPLAIN",
132622 /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
132623 /*   2 */ "cmdx ::= cmd",
132624 /*   3 */ "cmd ::= BEGIN transtype trans_opt",
132625 /*   4 */ "transtype ::=",
132626 /*   5 */ "transtype ::= DEFERRED",
132627 /*   6 */ "transtype ::= IMMEDIATE",
132628 /*   7 */ "transtype ::= EXCLUSIVE",
132629 /*   8 */ "cmd ::= COMMIT trans_opt",
132630 /*   9 */ "cmd ::= END trans_opt",
132631 /*  10 */ "cmd ::= ROLLBACK trans_opt",
132632 /*  11 */ "cmd ::= SAVEPOINT nm",
132633 /*  12 */ "cmd ::= RELEASE savepoint_opt nm",
132634 /*  13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
132635 /*  14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
132636 /*  15 */ "createkw ::= CREATE",
132637 /*  16 */ "ifnotexists ::=",
132638 /*  17 */ "ifnotexists ::= IF NOT EXISTS",
132639 /*  18 */ "temp ::= TEMP",
132640 /*  19 */ "temp ::=",
132641 /*  20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
132642 /*  21 */ "create_table_args ::= AS select",
132643 /*  22 */ "table_options ::=",
132644 /*  23 */ "table_options ::= WITHOUT nm",
132645 /*  24 */ "columnname ::= nm typetoken",
132646 /*  25 */ "typetoken ::=",
132647 /*  26 */ "typetoken ::= typename LP signed RP",
132648 /*  27 */ "typetoken ::= typename LP signed COMMA signed RP",
132649 /*  28 */ "typename ::= typename ID|STRING",
132650 /*  29 */ "ccons ::= CONSTRAINT nm",
132651 /*  30 */ "ccons ::= DEFAULT term",
132652 /*  31 */ "ccons ::= DEFAULT LP expr RP",
132653 /*  32 */ "ccons ::= DEFAULT PLUS term",
132654 /*  33 */ "ccons ::= DEFAULT MINUS term",
132655 /*  34 */ "ccons ::= DEFAULT ID|INDEXED",
132656 /*  35 */ "ccons ::= NOT NULL onconf",
132657 /*  36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
132658 /*  37 */ "ccons ::= UNIQUE onconf",
132659 /*  38 */ "ccons ::= CHECK LP expr RP",
132660 /*  39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
132661 /*  40 */ "ccons ::= defer_subclause",
132662 /*  41 */ "ccons ::= COLLATE ID|STRING",
132663 /*  42 */ "autoinc ::=",
132664 /*  43 */ "autoinc ::= AUTOINCR",
132665 /*  44 */ "refargs ::=",
132666 /*  45 */ "refargs ::= refargs refarg",
132667 /*  46 */ "refarg ::= MATCH nm",
132668 /*  47 */ "refarg ::= ON INSERT refact",
132669 /*  48 */ "refarg ::= ON DELETE refact",
132670 /*  49 */ "refarg ::= ON UPDATE refact",
132671 /*  50 */ "refact ::= SET NULL",
132672 /*  51 */ "refact ::= SET DEFAULT",
132673 /*  52 */ "refact ::= CASCADE",
132674 /*  53 */ "refact ::= RESTRICT",
132675 /*  54 */ "refact ::= NO ACTION",
132676 /*  55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
132677 /*  56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
132678 /*  57 */ "init_deferred_pred_opt ::=",
132679 /*  58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
132680 /*  59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
132681 /*  60 */ "conslist_opt ::=",
132682 /*  61 */ "tconscomma ::= COMMA",
132683 /*  62 */ "tcons ::= CONSTRAINT nm",
132684 /*  63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
132685 /*  64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
132686 /*  65 */ "tcons ::= CHECK LP expr RP onconf",
132687 /*  66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
132688 /*  67 */ "defer_subclause_opt ::=",
132689 /*  68 */ "onconf ::=",
132690 /*  69 */ "onconf ::= ON CONFLICT resolvetype",
132691 /*  70 */ "orconf ::=",
132692 /*  71 */ "orconf ::= OR resolvetype",
132693 /*  72 */ "resolvetype ::= IGNORE",
132694 /*  73 */ "resolvetype ::= REPLACE",
132695 /*  74 */ "cmd ::= DROP TABLE ifexists fullname",
132696 /*  75 */ "ifexists ::= IF EXISTS",
132697 /*  76 */ "ifexists ::=",
132698 /*  77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
132699 /*  78 */ "cmd ::= DROP VIEW ifexists fullname",
132700 /*  79 */ "cmd ::= select",
132701 /*  80 */ "select ::= with selectnowith",
132702 /*  81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
132703 /*  82 */ "multiselect_op ::= UNION",
132704 /*  83 */ "multiselect_op ::= UNION ALL",
132705 /*  84 */ "multiselect_op ::= EXCEPT|INTERSECT",
132706 /*  85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
132707 /*  86 */ "values ::= VALUES LP nexprlist RP",
132708 /*  87 */ "values ::= values COMMA LP exprlist RP",
132709 /*  88 */ "distinct ::= DISTINCT",
132710 /*  89 */ "distinct ::= ALL",
132711 /*  90 */ "distinct ::=",
132712 /*  91 */ "sclp ::=",
132713 /*  92 */ "selcollist ::= sclp expr as",
132714 /*  93 */ "selcollist ::= sclp STAR",
132715 /*  94 */ "selcollist ::= sclp nm DOT STAR",
132716 /*  95 */ "as ::= AS nm",
132717 /*  96 */ "as ::=",
132718 /*  97 */ "from ::=",
132719 /*  98 */ "from ::= FROM seltablist",
132720 /*  99 */ "stl_prefix ::= seltablist joinop",
132721 /* 100 */ "stl_prefix ::=",
132722 /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
132723 /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
132724 /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
132725 /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
132726 /* 105 */ "dbnm ::=",
132727 /* 106 */ "dbnm ::= DOT nm",
132728 /* 107 */ "fullname ::= nm dbnm",
132729 /* 108 */ "joinop ::= COMMA|JOIN",
132730 /* 109 */ "joinop ::= JOIN_KW JOIN",
132731 /* 110 */ "joinop ::= JOIN_KW nm JOIN",
132732 /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
132733 /* 112 */ "on_opt ::= ON expr",
132734 /* 113 */ "on_opt ::=",
132735 /* 114 */ "indexed_opt ::=",
132736 /* 115 */ "indexed_opt ::= INDEXED BY nm",
132737 /* 116 */ "indexed_opt ::= NOT INDEXED",
132738 /* 117 */ "using_opt ::= USING LP idlist RP",
132739 /* 118 */ "using_opt ::=",
132740 /* 119 */ "orderby_opt ::=",
132741 /* 120 */ "orderby_opt ::= ORDER BY sortlist",
132742 /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
132743 /* 122 */ "sortlist ::= expr sortorder",
132744 /* 123 */ "sortorder ::= ASC",
132745 /* 124 */ "sortorder ::= DESC",
132746 /* 125 */ "sortorder ::=",
132747 /* 126 */ "groupby_opt ::=",
132748 /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
132749 /* 128 */ "having_opt ::=",
132750 /* 129 */ "having_opt ::= HAVING expr",
132751 /* 130 */ "limit_opt ::=",
132752 /* 131 */ "limit_opt ::= LIMIT expr",
132753 /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
132754 /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
132755 /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
132756 /* 135 */ "where_opt ::=",
132757 /* 136 */ "where_opt ::= WHERE expr",
132758 /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
132759 /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
132760 /* 139 */ "setlist ::= nm EQ expr",
132761 /* 140 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
132762 /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
132763 /* 142 */ "insert_cmd ::= INSERT orconf",
132764 /* 143 */ "insert_cmd ::= REPLACE",
132765 /* 144 */ "idlist_opt ::=",
132766 /* 145 */ "idlist_opt ::= LP idlist RP",
132767 /* 146 */ "idlist ::= idlist COMMA nm",
132768 /* 147 */ "idlist ::= nm",
132769 /* 148 */ "expr ::= LP expr RP",
132770 /* 149 */ "term ::= NULL",
132771 /* 150 */ "expr ::= ID|INDEXED",
132772 /* 151 */ "expr ::= JOIN_KW",
132773 /* 152 */ "expr ::= nm DOT nm",
132774 /* 153 */ "expr ::= nm DOT nm DOT nm",
132775 /* 154 */ "term ::= INTEGER|FLOAT|BLOB",
132776 /* 155 */ "term ::= STRING",
132777 /* 156 */ "expr ::= VARIABLE",
132778 /* 157 */ "expr ::= expr COLLATE ID|STRING",
132779 /* 158 */ "expr ::= CAST LP expr AS typetoken RP",
132780 /* 159 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
132781 /* 160 */ "expr ::= ID|INDEXED LP STAR RP",
132782 /* 161 */ "term ::= CTIME_KW",
132783 /* 162 */ "expr ::= expr AND expr",
132784 /* 163 */ "expr ::= expr OR expr",
132785 /* 164 */ "expr ::= expr LT|GT|GE|LE expr",
132786 /* 165 */ "expr ::= expr EQ|NE expr",
132787 /* 166 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
132788 /* 167 */ "expr ::= expr PLUS|MINUS expr",
132789 /* 168 */ "expr ::= expr STAR|SLASH|REM expr",
132790 /* 169 */ "expr ::= expr CONCAT expr",
132791 /* 170 */ "likeop ::= LIKE_KW|MATCH",
132792 /* 171 */ "likeop ::= NOT LIKE_KW|MATCH",
132793 /* 172 */ "expr ::= expr likeop expr",
132794 /* 173 */ "expr ::= expr likeop expr ESCAPE expr",
132795 /* 174 */ "expr ::= expr ISNULL|NOTNULL",
132796 /* 175 */ "expr ::= expr NOT NULL",
132797 /* 176 */ "expr ::= expr IS expr",
132798 /* 177 */ "expr ::= expr IS NOT expr",
132799 /* 178 */ "expr ::= NOT expr",
132800 /* 179 */ "expr ::= BITNOT expr",
132801 /* 180 */ "expr ::= MINUS expr",
132802 /* 181 */ "expr ::= PLUS expr",
132803 /* 182 */ "between_op ::= BETWEEN",
132804 /* 183 */ "between_op ::= NOT BETWEEN",
132805 /* 184 */ "expr ::= expr between_op expr AND expr",
132806 /* 185 */ "in_op ::= IN",
132807 /* 186 */ "in_op ::= NOT IN",
132808 /* 187 */ "expr ::= expr in_op LP exprlist RP",
132809 /* 188 */ "expr ::= LP select RP",
132810 /* 189 */ "expr ::= expr in_op LP select RP",
132811 /* 190 */ "expr ::= expr in_op nm dbnm paren_exprlist",
132812 /* 191 */ "expr ::= EXISTS LP select RP",
132813 /* 192 */ "expr ::= CASE case_operand case_exprlist case_else END",
132814 /* 193 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
132815 /* 194 */ "case_exprlist ::= WHEN expr THEN expr",
132816 /* 195 */ "case_else ::= ELSE expr",
132817 /* 196 */ "case_else ::=",
132818 /* 197 */ "case_operand ::= expr",
132819 /* 198 */ "case_operand ::=",
132820 /* 199 */ "exprlist ::=",
132821 /* 200 */ "nexprlist ::= nexprlist COMMA expr",
132822 /* 201 */ "nexprlist ::= expr",
132823 /* 202 */ "paren_exprlist ::=",
132824 /* 203 */ "paren_exprlist ::= LP exprlist RP",
132825 /* 204 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
132826 /* 205 */ "uniqueflag ::= UNIQUE",
132827 /* 206 */ "uniqueflag ::=",
132828 /* 207 */ "eidlist_opt ::=",
132829 /* 208 */ "eidlist_opt ::= LP eidlist RP",
132830 /* 209 */ "eidlist ::= eidlist COMMA nm collate sortorder",
132831 /* 210 */ "eidlist ::= nm collate sortorder",
132832 /* 211 */ "collate ::=",
132833 /* 212 */ "collate ::= COLLATE ID|STRING",
132834 /* 213 */ "cmd ::= DROP INDEX ifexists fullname",
132835 /* 214 */ "cmd ::= VACUUM",
132836 /* 215 */ "cmd ::= VACUUM nm",
132837 /* 216 */ "cmd ::= PRAGMA nm dbnm",
132838 /* 217 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
132839 /* 218 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
132840 /* 219 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
132841 /* 220 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
132842 /* 221 */ "plus_num ::= PLUS INTEGER|FLOAT",
132843 /* 222 */ "minus_num ::= MINUS INTEGER|FLOAT",
132844 /* 223 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
132845 /* 224 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
132846 /* 225 */ "trigger_time ::= BEFORE",
132847 /* 226 */ "trigger_time ::= AFTER",
132848 /* 227 */ "trigger_time ::= INSTEAD OF",
132849 /* 228 */ "trigger_time ::=",
132850 /* 229 */ "trigger_event ::= DELETE|INSERT",
132851 /* 230 */ "trigger_event ::= UPDATE",
132852 /* 231 */ "trigger_event ::= UPDATE OF idlist",
132853 /* 232 */ "when_clause ::=",
132854 /* 233 */ "when_clause ::= WHEN expr",
132855 /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
132856 /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
132857 /* 236 */ "trnm ::= nm DOT nm",
132858 /* 237 */ "tridxby ::= INDEXED BY nm",
132859 /* 238 */ "tridxby ::= NOT INDEXED",
132860 /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
132861 /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
132862 /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
132863 /* 242 */ "trigger_cmd ::= select",
132864 /* 243 */ "expr ::= RAISE LP IGNORE RP",
132865 /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
132866 /* 245 */ "raisetype ::= ROLLBACK",
132867 /* 246 */ "raisetype ::= ABORT",
132868 /* 247 */ "raisetype ::= FAIL",
132869 /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
132870 /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
132871 /* 250 */ "cmd ::= DETACH database_kw_opt expr",
132872 /* 251 */ "key_opt ::=",
132873 /* 252 */ "key_opt ::= KEY expr",
132874 /* 253 */ "cmd ::= REINDEX",
132875 /* 254 */ "cmd ::= REINDEX nm dbnm",
132876 /* 255 */ "cmd ::= ANALYZE",
132877 /* 256 */ "cmd ::= ANALYZE nm dbnm",
132878 /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
132879 /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
132880 /* 259 */ "add_column_fullname ::= fullname",
132881 /* 260 */ "cmd ::= create_vtab",
132882 /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
132883 /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
132884 /* 263 */ "vtabarg ::=",
132885 /* 264 */ "vtabargtoken ::= ANY",
132886 /* 265 */ "vtabargtoken ::= lp anylist RP",
132887 /* 266 */ "lp ::= LP",
132888 /* 267 */ "with ::=",
132889 /* 268 */ "with ::= WITH wqlist",
132890 /* 269 */ "with ::= WITH RECURSIVE wqlist",
132891 /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
132892 /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
132893 /* 272 */ "input ::= cmdlist",
132894 /* 273 */ "cmdlist ::= cmdlist ecmd",
132895 /* 274 */ "cmdlist ::= ecmd",
132896 /* 275 */ "ecmd ::= SEMI",
132897 /* 276 */ "ecmd ::= explain cmdx SEMI",
132898 /* 277 */ "explain ::=",
132899 /* 278 */ "trans_opt ::=",
132900 /* 279 */ "trans_opt ::= TRANSACTION",
132901 /* 280 */ "trans_opt ::= TRANSACTION nm",
132902 /* 281 */ "savepoint_opt ::= SAVEPOINT",
132903 /* 282 */ "savepoint_opt ::=",
132904 /* 283 */ "cmd ::= create_table create_table_args",
132905 /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
132906 /* 285 */ "columnlist ::= columnname carglist",
132907 /* 286 */ "nm ::= ID|INDEXED",
132908 /* 287 */ "nm ::= STRING",
132909 /* 288 */ "nm ::= JOIN_KW",
132910 /* 289 */ "typetoken ::= typename",
132911 /* 290 */ "typename ::= ID|STRING",
132912 /* 291 */ "signed ::= plus_num",
132913 /* 292 */ "signed ::= minus_num",
132914 /* 293 */ "carglist ::= carglist ccons",
132915 /* 294 */ "carglist ::=",
132916 /* 295 */ "ccons ::= NULL onconf",
132917 /* 296 */ "conslist_opt ::= COMMA conslist",
132918 /* 297 */ "conslist ::= conslist tconscomma tcons",
132919 /* 298 */ "conslist ::= tcons",
132920 /* 299 */ "tconscomma ::=",
132921 /* 300 */ "defer_subclause_opt ::= defer_subclause",
132922 /* 301 */ "resolvetype ::= raisetype",
132923 /* 302 */ "selectnowith ::= oneselect",
132924 /* 303 */ "oneselect ::= values",
132925 /* 304 */ "sclp ::= selcollist COMMA",
132926 /* 305 */ "as ::= ID|STRING",
132927 /* 306 */ "expr ::= term",
132928 /* 307 */ "exprlist ::= nexprlist",
132929 /* 308 */ "nmnum ::= plus_num",
132930 /* 309 */ "nmnum ::= nm",
132931 /* 310 */ "nmnum ::= ON",
132932 /* 311 */ "nmnum ::= DELETE",
132933 /* 312 */ "nmnum ::= DEFAULT",
132934 /* 313 */ "plus_num ::= INTEGER|FLOAT",
132935 /* 314 */ "foreach_clause ::=",
132936 /* 315 */ "foreach_clause ::= FOR EACH ROW",
132937 /* 316 */ "trnm ::= nm",
132938 /* 317 */ "tridxby ::=",
132939 /* 318 */ "database_kw_opt ::= DATABASE",
132940 /* 319 */ "database_kw_opt ::=",
132941 /* 320 */ "kwcolumn_opt ::=",
132942 /* 321 */ "kwcolumn_opt ::= COLUMNKW",
132943 /* 322 */ "vtabarglist ::= vtabarg",
132944 /* 323 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
132945 /* 324 */ "vtabarg ::= vtabarg vtabargtoken",
132946 /* 325 */ "anylist ::=",
132947 /* 326 */ "anylist ::= anylist LP anylist RP",
132948 /* 327 */ "anylist ::= anylist ANY",
132949};
132950#endif /* NDEBUG */
132951
132952
132953#if YYSTACKDEPTH<=0
132954/*
132955** Try to increase the size of the parser stack.  Return the number
132956** of errors.  Return 0 on success.
132957*/
132958static int yyGrowStack(yyParser *p){
132959  int newSize;
132960  int idx;
132961  yyStackEntry *pNew;
132962
132963  newSize = p->yystksz*2 + 100;
132964  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
132965  if( p->yystack==&p->yystk0 ){
132966    pNew = malloc(newSize*sizeof(pNew[0]));
132967    if( pNew ) pNew[0] = p->yystk0;
132968  }else{
132969    pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
132970  }
132971  if( pNew ){
132972    p->yystack = pNew;
132973    p->yytos = &p->yystack[idx];
132974#ifndef NDEBUG
132975    if( yyTraceFILE ){
132976      fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
132977              yyTracePrompt, p->yystksz, newSize);
132978    }
132979#endif
132980    p->yystksz = newSize;
132981  }
132982  return pNew==0;
132983}
132984#endif
132985
132986/* Datatype of the argument to the memory allocated passed as the
132987** second argument to sqlite3ParserAlloc() below.  This can be changed by
132988** putting an appropriate #define in the %include section of the input
132989** grammar.
132990*/
132991#ifndef YYMALLOCARGTYPE
132992# define YYMALLOCARGTYPE size_t
132993#endif
132994
132995/*
132996** This function allocates a new parser.
132997** The only argument is a pointer to a function which works like
132998** malloc.
132999**
133000** Inputs:
133001** A pointer to the function used to allocate memory.
133002**
133003** Outputs:
133004** A pointer to a parser.  This pointer is used in subsequent calls
133005** to sqlite3Parser and sqlite3ParserFree.
133006*/
133007SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
133008  yyParser *pParser;
133009  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
133010  if( pParser ){
133011#ifdef YYTRACKMAXSTACKDEPTH
133012    pParser->yyhwm = 0;
133013#endif
133014#if YYSTACKDEPTH<=0
133015    pParser->yytos = NULL;
133016    pParser->yystack = NULL;
133017    pParser->yystksz = 0;
133018    if( yyGrowStack(pParser) ){
133019      pParser->yystack = &pParser->yystk0;
133020      pParser->yystksz = 1;
133021    }
133022#endif
133023#ifndef YYNOERRORRECOVERY
133024    pParser->yyerrcnt = -1;
133025#endif
133026    pParser->yytos = pParser->yystack;
133027    pParser->yystack[0].stateno = 0;
133028    pParser->yystack[0].major = 0;
133029  }
133030  return pParser;
133031}
133032
133033/* The following function deletes the "minor type" or semantic value
133034** associated with a symbol.  The symbol can be either a terminal
133035** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
133036** a pointer to the value to be deleted.  The code used to do the
133037** deletions is derived from the %destructor and/or %token_destructor
133038** directives of the input grammar.
133039*/
133040static void yy_destructor(
133041  yyParser *yypParser,    /* The parser */
133042  YYCODETYPE yymajor,     /* Type code for object to destroy */
133043  YYMINORTYPE *yypminor   /* The object to be destroyed */
133044){
133045  sqlite3ParserARG_FETCH;
133046  switch( yymajor ){
133047    /* Here is inserted the actions which take place when a
133048    ** terminal or non-terminal is destroyed.  This can happen
133049    ** when the symbol is popped from the stack during a
133050    ** reduce or during error processing or when a parser is
133051    ** being destroyed before it is finished parsing.
133052    **
133053    ** Note: during a reduce, the only symbols destroyed are those
133054    ** which appear on the RHS of the rule, but which are *not* used
133055    ** inside the C code.
133056    */
133057/********* Begin destructor definitions ***************************************/
133058    case 163: /* select */
133059    case 194: /* selectnowith */
133060    case 195: /* oneselect */
133061    case 206: /* values */
133062{
133063sqlite3SelectDelete(pParse->db, (yypminor->yy243));
133064}
133065      break;
133066    case 172: /* term */
133067    case 173: /* expr */
133068{
133069sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
133070}
133071      break;
133072    case 177: /* eidlist_opt */
133073    case 186: /* sortlist */
133074    case 187: /* eidlist */
133075    case 199: /* selcollist */
133076    case 202: /* groupby_opt */
133077    case 204: /* orderby_opt */
133078    case 207: /* nexprlist */
133079    case 208: /* exprlist */
133080    case 209: /* sclp */
133081    case 218: /* setlist */
133082    case 224: /* paren_exprlist */
133083    case 226: /* case_exprlist */
133084{
133085sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
133086}
133087      break;
133088    case 193: /* fullname */
133089    case 200: /* from */
133090    case 211: /* seltablist */
133091    case 212: /* stl_prefix */
133092{
133093sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
133094}
133095      break;
133096    case 196: /* with */
133097    case 250: /* wqlist */
133098{
133099sqlite3WithDelete(pParse->db, (yypminor->yy285));
133100}
133101      break;
133102    case 201: /* where_opt */
133103    case 203: /* having_opt */
133104    case 215: /* on_opt */
133105    case 225: /* case_operand */
133106    case 227: /* case_else */
133107    case 236: /* when_clause */
133108    case 241: /* key_opt */
133109{
133110sqlite3ExprDelete(pParse->db, (yypminor->yy72));
133111}
133112      break;
133113    case 216: /* using_opt */
133114    case 217: /* idlist */
133115    case 220: /* idlist_opt */
133116{
133117sqlite3IdListDelete(pParse->db, (yypminor->yy254));
133118}
133119      break;
133120    case 232: /* trigger_cmd_list */
133121    case 237: /* trigger_cmd */
133122{
133123sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
133124}
133125      break;
133126    case 234: /* trigger_event */
133127{
133128sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
133129}
133130      break;
133131/********* End destructor definitions *****************************************/
133132    default:  break;   /* If no destructor action specified: do nothing */
133133  }
133134}
133135
133136/*
133137** Pop the parser's stack once.
133138**
133139** If there is a destructor routine associated with the token which
133140** is popped from the stack, then call it.
133141*/
133142static void yy_pop_parser_stack(yyParser *pParser){
133143  yyStackEntry *yytos;
133144  assert( pParser->yytos!=0 );
133145  assert( pParser->yytos > pParser->yystack );
133146  yytos = pParser->yytos--;
133147#ifndef NDEBUG
133148  if( yyTraceFILE ){
133149    fprintf(yyTraceFILE,"%sPopping %s\n",
133150      yyTracePrompt,
133151      yyTokenName[yytos->major]);
133152  }
133153#endif
133154  yy_destructor(pParser, yytos->major, &yytos->minor);
133155}
133156
133157/*
133158** Deallocate and destroy a parser.  Destructors are called for
133159** all stack elements before shutting the parser down.
133160**
133161** If the YYPARSEFREENEVERNULL macro exists (for example because it
133162** is defined in a %include section of the input grammar) then it is
133163** assumed that the input pointer is never NULL.
133164*/
133165SQLITE_PRIVATE void sqlite3ParserFree(
133166  void *p,                    /* The parser to be deleted */
133167  void (*freeProc)(void*)     /* Function used to reclaim memory */
133168){
133169  yyParser *pParser = (yyParser*)p;
133170#ifndef YYPARSEFREENEVERNULL
133171  if( pParser==0 ) return;
133172#endif
133173  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
133174#if YYSTACKDEPTH<=0
133175  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
133176#endif
133177  (*freeProc)((void*)pParser);
133178}
133179
133180/*
133181** Return the peak depth of the stack for a parser.
133182*/
133183#ifdef YYTRACKMAXSTACKDEPTH
133184SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
133185  yyParser *pParser = (yyParser*)p;
133186  return pParser->yyhwm;
133187}
133188#endif
133189
133190/*
133191** Find the appropriate action for a parser given the terminal
133192** look-ahead token iLookAhead.
133193*/
133194static unsigned int yy_find_shift_action(
133195  yyParser *pParser,        /* The parser */
133196  YYCODETYPE iLookAhead     /* The look-ahead token */
133197){
133198  int i;
133199  int stateno = pParser->yytos->stateno;
133200
133201  if( stateno>=YY_MIN_REDUCE ) return stateno;
133202  assert( stateno <= YY_SHIFT_COUNT );
133203  do{
133204    i = yy_shift_ofst[stateno];
133205    if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
133206    assert( iLookAhead!=YYNOCODE );
133207    i += iLookAhead;
133208    if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
133209      if( iLookAhead>0 ){
133210#ifdef YYFALLBACK
133211        YYCODETYPE iFallback;            /* Fallback token */
133212        if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
133213               && (iFallback = yyFallback[iLookAhead])!=0 ){
133214#ifndef NDEBUG
133215          if( yyTraceFILE ){
133216            fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
133217               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
133218          }
133219#endif
133220          assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
133221          iLookAhead = iFallback;
133222          continue;
133223        }
133224#endif
133225#ifdef YYWILDCARD
133226        {
133227          int j = i - iLookAhead + YYWILDCARD;
133228          if(
133229#if YY_SHIFT_MIN+YYWILDCARD<0
133230            j>=0 &&
133231#endif
133232#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
133233            j<YY_ACTTAB_COUNT &&
133234#endif
133235            yy_lookahead[j]==YYWILDCARD
133236          ){
133237#ifndef NDEBUG
133238            if( yyTraceFILE ){
133239              fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
133240                 yyTracePrompt, yyTokenName[iLookAhead],
133241                 yyTokenName[YYWILDCARD]);
133242            }
133243#endif /* NDEBUG */
133244            return yy_action[j];
133245          }
133246        }
133247#endif /* YYWILDCARD */
133248      }
133249      return yy_default[stateno];
133250    }else{
133251      return yy_action[i];
133252    }
133253  }while(1);
133254}
133255
133256/*
133257** Find the appropriate action for a parser given the non-terminal
133258** look-ahead token iLookAhead.
133259*/
133260static int yy_find_reduce_action(
133261  int stateno,              /* Current state number */
133262  YYCODETYPE iLookAhead     /* The look-ahead token */
133263){
133264  int i;
133265#ifdef YYERRORSYMBOL
133266  if( stateno>YY_REDUCE_COUNT ){
133267    return yy_default[stateno];
133268  }
133269#else
133270  assert( stateno<=YY_REDUCE_COUNT );
133271#endif
133272  i = yy_reduce_ofst[stateno];
133273  assert( i!=YY_REDUCE_USE_DFLT );
133274  assert( iLookAhead!=YYNOCODE );
133275  i += iLookAhead;
133276#ifdef YYERRORSYMBOL
133277  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
133278    return yy_default[stateno];
133279  }
133280#else
133281  assert( i>=0 && i<YY_ACTTAB_COUNT );
133282  assert( yy_lookahead[i]==iLookAhead );
133283#endif
133284  return yy_action[i];
133285}
133286
133287/*
133288** The following routine is called if the stack overflows.
133289*/
133290static void yyStackOverflow(yyParser *yypParser){
133291   sqlite3ParserARG_FETCH;
133292   yypParser->yytos--;
133293#ifndef NDEBUG
133294   if( yyTraceFILE ){
133295     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
133296   }
133297#endif
133298   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
133299   /* Here code is inserted which will execute if the parser
133300   ** stack every overflows */
133301/******** Begin %stack_overflow code ******************************************/
133302
133303  sqlite3ErrorMsg(pParse, "parser stack overflow");
133304/******** End %stack_overflow code ********************************************/
133305   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
133306}
133307
133308/*
133309** Print tracing information for a SHIFT action
133310*/
133311#ifndef NDEBUG
133312static void yyTraceShift(yyParser *yypParser, int yyNewState){
133313  if( yyTraceFILE ){
133314    if( yyNewState<YYNSTATE ){
133315      fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
133316         yyTracePrompt,yyTokenName[yypParser->yytos->major],
133317         yyNewState);
133318    }else{
133319      fprintf(yyTraceFILE,"%sShift '%s'\n",
133320         yyTracePrompt,yyTokenName[yypParser->yytos->major]);
133321    }
133322  }
133323}
133324#else
133325# define yyTraceShift(X,Y)
133326#endif
133327
133328/*
133329** Perform a shift action.
133330*/
133331static void yy_shift(
133332  yyParser *yypParser,          /* The parser to be shifted */
133333  int yyNewState,               /* The new state to shift in */
133334  int yyMajor,                  /* The major token to shift in */
133335  sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
133336){
133337  yyStackEntry *yytos;
133338  yypParser->yytos++;
133339#ifdef YYTRACKMAXSTACKDEPTH
133340  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
133341    yypParser->yyhwm++;
133342    assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
133343  }
133344#endif
133345#if YYSTACKDEPTH>0
133346  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
133347    yyStackOverflow(yypParser);
133348    return;
133349  }
133350#else
133351  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
133352    if( yyGrowStack(yypParser) ){
133353      yyStackOverflow(yypParser);
133354      return;
133355    }
133356  }
133357#endif
133358  if( yyNewState > YY_MAX_SHIFT ){
133359    yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
133360  }
133361  yytos = yypParser->yytos;
133362  yytos->stateno = (YYACTIONTYPE)yyNewState;
133363  yytos->major = (YYCODETYPE)yyMajor;
133364  yytos->minor.yy0 = yyMinor;
133365  yyTraceShift(yypParser, yyNewState);
133366}
133367
133368/* The following table contains information about every rule that
133369** is used during the reduce.
133370*/
133371static const struct {
133372  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
133373  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
133374} yyRuleInfo[] = {
133375  { 147, 1 },
133376  { 147, 3 },
133377  { 148, 1 },
133378  { 149, 3 },
133379  { 150, 0 },
133380  { 150, 1 },
133381  { 150, 1 },
133382  { 150, 1 },
133383  { 149, 2 },
133384  { 149, 2 },
133385  { 149, 2 },
133386  { 149, 2 },
133387  { 149, 3 },
133388  { 149, 5 },
133389  { 154, 6 },
133390  { 156, 1 },
133391  { 158, 0 },
133392  { 158, 3 },
133393  { 157, 1 },
133394  { 157, 0 },
133395  { 155, 5 },
133396  { 155, 2 },
133397  { 162, 0 },
133398  { 162, 2 },
133399  { 164, 2 },
133400  { 166, 0 },
133401  { 166, 4 },
133402  { 166, 6 },
133403  { 167, 2 },
133404  { 171, 2 },
133405  { 171, 2 },
133406  { 171, 4 },
133407  { 171, 3 },
133408  { 171, 3 },
133409  { 171, 2 },
133410  { 171, 3 },
133411  { 171, 5 },
133412  { 171, 2 },
133413  { 171, 4 },
133414  { 171, 4 },
133415  { 171, 1 },
133416  { 171, 2 },
133417  { 176, 0 },
133418  { 176, 1 },
133419  { 178, 0 },
133420  { 178, 2 },
133421  { 180, 2 },
133422  { 180, 3 },
133423  { 180, 3 },
133424  { 180, 3 },
133425  { 181, 2 },
133426  { 181, 2 },
133427  { 181, 1 },
133428  { 181, 1 },
133429  { 181, 2 },
133430  { 179, 3 },
133431  { 179, 2 },
133432  { 182, 0 },
133433  { 182, 2 },
133434  { 182, 2 },
133435  { 161, 0 },
133436  { 184, 1 },
133437  { 185, 2 },
133438  { 185, 7 },
133439  { 185, 5 },
133440  { 185, 5 },
133441  { 185, 10 },
133442  { 188, 0 },
133443  { 174, 0 },
133444  { 174, 3 },
133445  { 189, 0 },
133446  { 189, 2 },
133447  { 190, 1 },
133448  { 190, 1 },
133449  { 149, 4 },
133450  { 192, 2 },
133451  { 192, 0 },
133452  { 149, 9 },
133453  { 149, 4 },
133454  { 149, 1 },
133455  { 163, 2 },
133456  { 194, 3 },
133457  { 197, 1 },
133458  { 197, 2 },
133459  { 197, 1 },
133460  { 195, 9 },
133461  { 206, 4 },
133462  { 206, 5 },
133463  { 198, 1 },
133464  { 198, 1 },
133465  { 198, 0 },
133466  { 209, 0 },
133467  { 199, 3 },
133468  { 199, 2 },
133469  { 199, 4 },
133470  { 210, 2 },
133471  { 210, 0 },
133472  { 200, 0 },
133473  { 200, 2 },
133474  { 212, 2 },
133475  { 212, 0 },
133476  { 211, 7 },
133477  { 211, 9 },
133478  { 211, 7 },
133479  { 211, 7 },
133480  { 159, 0 },
133481  { 159, 2 },
133482  { 193, 2 },
133483  { 213, 1 },
133484  { 213, 2 },
133485  { 213, 3 },
133486  { 213, 4 },
133487  { 215, 2 },
133488  { 215, 0 },
133489  { 214, 0 },
133490  { 214, 3 },
133491  { 214, 2 },
133492  { 216, 4 },
133493  { 216, 0 },
133494  { 204, 0 },
133495  { 204, 3 },
133496  { 186, 4 },
133497  { 186, 2 },
133498  { 175, 1 },
133499  { 175, 1 },
133500  { 175, 0 },
133501  { 202, 0 },
133502  { 202, 3 },
133503  { 203, 0 },
133504  { 203, 2 },
133505  { 205, 0 },
133506  { 205, 2 },
133507  { 205, 4 },
133508  { 205, 4 },
133509  { 149, 6 },
133510  { 201, 0 },
133511  { 201, 2 },
133512  { 149, 8 },
133513  { 218, 5 },
133514  { 218, 3 },
133515  { 149, 6 },
133516  { 149, 7 },
133517  { 219, 2 },
133518  { 219, 1 },
133519  { 220, 0 },
133520  { 220, 3 },
133521  { 217, 3 },
133522  { 217, 1 },
133523  { 173, 3 },
133524  { 172, 1 },
133525  { 173, 1 },
133526  { 173, 1 },
133527  { 173, 3 },
133528  { 173, 5 },
133529  { 172, 1 },
133530  { 172, 1 },
133531  { 173, 1 },
133532  { 173, 3 },
133533  { 173, 6 },
133534  { 173, 5 },
133535  { 173, 4 },
133536  { 172, 1 },
133537  { 173, 3 },
133538  { 173, 3 },
133539  { 173, 3 },
133540  { 173, 3 },
133541  { 173, 3 },
133542  { 173, 3 },
133543  { 173, 3 },
133544  { 173, 3 },
133545  { 221, 1 },
133546  { 221, 2 },
133547  { 173, 3 },
133548  { 173, 5 },
133549  { 173, 2 },
133550  { 173, 3 },
133551  { 173, 3 },
133552  { 173, 4 },
133553  { 173, 2 },
133554  { 173, 2 },
133555  { 173, 2 },
133556  { 173, 2 },
133557  { 222, 1 },
133558  { 222, 2 },
133559  { 173, 5 },
133560  { 223, 1 },
133561  { 223, 2 },
133562  { 173, 5 },
133563  { 173, 3 },
133564  { 173, 5 },
133565  { 173, 5 },
133566  { 173, 4 },
133567  { 173, 5 },
133568  { 226, 5 },
133569  { 226, 4 },
133570  { 227, 2 },
133571  { 227, 0 },
133572  { 225, 1 },
133573  { 225, 0 },
133574  { 208, 0 },
133575  { 207, 3 },
133576  { 207, 1 },
133577  { 224, 0 },
133578  { 224, 3 },
133579  { 149, 12 },
133580  { 228, 1 },
133581  { 228, 0 },
133582  { 177, 0 },
133583  { 177, 3 },
133584  { 187, 5 },
133585  { 187, 3 },
133586  { 229, 0 },
133587  { 229, 2 },
133588  { 149, 4 },
133589  { 149, 1 },
133590  { 149, 2 },
133591  { 149, 3 },
133592  { 149, 5 },
133593  { 149, 6 },
133594  { 149, 5 },
133595  { 149, 6 },
133596  { 169, 2 },
133597  { 170, 2 },
133598  { 149, 5 },
133599  { 231, 11 },
133600  { 233, 1 },
133601  { 233, 1 },
133602  { 233, 2 },
133603  { 233, 0 },
133604  { 234, 1 },
133605  { 234, 1 },
133606  { 234, 3 },
133607  { 236, 0 },
133608  { 236, 2 },
133609  { 232, 3 },
133610  { 232, 2 },
133611  { 238, 3 },
133612  { 239, 3 },
133613  { 239, 2 },
133614  { 237, 7 },
133615  { 237, 5 },
133616  { 237, 5 },
133617  { 237, 1 },
133618  { 173, 4 },
133619  { 173, 6 },
133620  { 191, 1 },
133621  { 191, 1 },
133622  { 191, 1 },
133623  { 149, 4 },
133624  { 149, 6 },
133625  { 149, 3 },
133626  { 241, 0 },
133627  { 241, 2 },
133628  { 149, 1 },
133629  { 149, 3 },
133630  { 149, 1 },
133631  { 149, 3 },
133632  { 149, 6 },
133633  { 149, 7 },
133634  { 242, 1 },
133635  { 149, 1 },
133636  { 149, 4 },
133637  { 244, 8 },
133638  { 246, 0 },
133639  { 247, 1 },
133640  { 247, 3 },
133641  { 248, 1 },
133642  { 196, 0 },
133643  { 196, 2 },
133644  { 196, 3 },
133645  { 250, 6 },
133646  { 250, 8 },
133647  { 144, 1 },
133648  { 145, 2 },
133649  { 145, 1 },
133650  { 146, 1 },
133651  { 146, 3 },
133652  { 147, 0 },
133653  { 151, 0 },
133654  { 151, 1 },
133655  { 151, 2 },
133656  { 153, 1 },
133657  { 153, 0 },
133658  { 149, 2 },
133659  { 160, 4 },
133660  { 160, 2 },
133661  { 152, 1 },
133662  { 152, 1 },
133663  { 152, 1 },
133664  { 166, 1 },
133665  { 167, 1 },
133666  { 168, 1 },
133667  { 168, 1 },
133668  { 165, 2 },
133669  { 165, 0 },
133670  { 171, 2 },
133671  { 161, 2 },
133672  { 183, 3 },
133673  { 183, 1 },
133674  { 184, 0 },
133675  { 188, 1 },
133676  { 190, 1 },
133677  { 194, 1 },
133678  { 195, 1 },
133679  { 209, 2 },
133680  { 210, 1 },
133681  { 173, 1 },
133682  { 208, 1 },
133683  { 230, 1 },
133684  { 230, 1 },
133685  { 230, 1 },
133686  { 230, 1 },
133687  { 230, 1 },
133688  { 169, 1 },
133689  { 235, 0 },
133690  { 235, 3 },
133691  { 238, 1 },
133692  { 239, 0 },
133693  { 240, 1 },
133694  { 240, 0 },
133695  { 243, 0 },
133696  { 243, 1 },
133697  { 245, 1 },
133698  { 245, 3 },
133699  { 246, 2 },
133700  { 249, 0 },
133701  { 249, 4 },
133702  { 249, 2 },
133703};
133704
133705static void yy_accept(yyParser*);  /* Forward Declaration */
133706
133707/*
133708** Perform a reduce action and the shift that must immediately
133709** follow the reduce.
133710*/
133711static void yy_reduce(
133712  yyParser *yypParser,         /* The parser */
133713  unsigned int yyruleno        /* Number of the rule by which to reduce */
133714){
133715  int yygoto;                     /* The next state */
133716  int yyact;                      /* The next action */
133717  yyStackEntry *yymsp;            /* The top of the parser's stack */
133718  int yysize;                     /* Amount to pop the stack */
133719  sqlite3ParserARG_FETCH;
133720  yymsp = yypParser->yytos;
133721#ifndef NDEBUG
133722  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
133723    yysize = yyRuleInfo[yyruleno].nrhs;
133724    fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
133725      yyRuleName[yyruleno], yymsp[-yysize].stateno);
133726  }
133727#endif /* NDEBUG */
133728
133729  /* Check that the stack is large enough to grow by a single entry
133730  ** if the RHS of the rule is empty.  This ensures that there is room
133731  ** enough on the stack to push the LHS value */
133732  if( yyRuleInfo[yyruleno].nrhs==0 ){
133733#ifdef YYTRACKMAXSTACKDEPTH
133734    if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
133735      yypParser->yyhwm++;
133736      assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
133737    }
133738#endif
133739#if YYSTACKDEPTH>0
133740    if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
133741      yyStackOverflow(yypParser);
133742      return;
133743    }
133744#else
133745    if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
133746      if( yyGrowStack(yypParser) ){
133747        yyStackOverflow(yypParser);
133748        return;
133749      }
133750      yymsp = yypParser->yytos;
133751    }
133752#endif
133753  }
133754
133755  switch( yyruleno ){
133756  /* Beginning here are the reduction cases.  A typical example
133757  ** follows:
133758  **   case 0:
133759  **  #line <lineno> <grammarfile>
133760  **     { ... }           // User supplied code
133761  **  #line <lineno> <thisfile>
133762  **     break;
133763  */
133764/********** Begin reduce actions **********************************************/
133765        YYMINORTYPE yylhsminor;
133766      case 0: /* explain ::= EXPLAIN */
133767{ pParse->explain = 1; }
133768        break;
133769      case 1: /* explain ::= EXPLAIN QUERY PLAN */
133770{ pParse->explain = 2; }
133771        break;
133772      case 2: /* cmdx ::= cmd */
133773{ sqlite3FinishCoding(pParse); }
133774        break;
133775      case 3: /* cmd ::= BEGIN transtype trans_opt */
133776{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
133777        break;
133778      case 4: /* transtype ::= */
133779{yymsp[1].minor.yy194 = TK_DEFERRED;}
133780        break;
133781      case 5: /* transtype ::= DEFERRED */
133782      case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
133783      case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
133784{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
133785        break;
133786      case 8: /* cmd ::= COMMIT trans_opt */
133787      case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
133788{sqlite3CommitTransaction(pParse);}
133789        break;
133790      case 10: /* cmd ::= ROLLBACK trans_opt */
133791{sqlite3RollbackTransaction(pParse);}
133792        break;
133793      case 11: /* cmd ::= SAVEPOINT nm */
133794{
133795  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
133796}
133797        break;
133798      case 12: /* cmd ::= RELEASE savepoint_opt nm */
133799{
133800  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
133801}
133802        break;
133803      case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
133804{
133805  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
133806}
133807        break;
133808      case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
133809{
133810   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
133811}
133812        break;
133813      case 15: /* createkw ::= CREATE */
133814{disableLookaside(pParse);}
133815        break;
133816      case 16: /* ifnotexists ::= */
133817      case 19: /* temp ::= */ yytestcase(yyruleno==19);
133818      case 22: /* table_options ::= */ yytestcase(yyruleno==22);
133819      case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
133820      case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
133821      case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
133822      case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
133823      case 90: /* distinct ::= */ yytestcase(yyruleno==90);
133824      case 211: /* collate ::= */ yytestcase(yyruleno==211);
133825{yymsp[1].minor.yy194 = 0;}
133826        break;
133827      case 17: /* ifnotexists ::= IF NOT EXISTS */
133828{yymsp[-2].minor.yy194 = 1;}
133829        break;
133830      case 18: /* temp ::= TEMP */
133831      case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
133832{yymsp[0].minor.yy194 = 1;}
133833        break;
133834      case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
133835{
133836  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
133837}
133838        break;
133839      case 21: /* create_table_args ::= AS select */
133840{
133841  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
133842  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
133843}
133844        break;
133845      case 23: /* table_options ::= WITHOUT nm */
133846{
133847  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
133848    yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
133849  }else{
133850    yymsp[-1].minor.yy194 = 0;
133851    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
133852  }
133853}
133854        break;
133855      case 24: /* columnname ::= nm typetoken */
133856{sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
133857        break;
133858      case 25: /* typetoken ::= */
133859      case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
133860      case 96: /* as ::= */ yytestcase(yyruleno==96);
133861{yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
133862        break;
133863      case 26: /* typetoken ::= typename LP signed RP */
133864{
133865  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
133866}
133867        break;
133868      case 27: /* typetoken ::= typename LP signed COMMA signed RP */
133869{
133870  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
133871}
133872        break;
133873      case 28: /* typename ::= typename ID|STRING */
133874{yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
133875        break;
133876      case 29: /* ccons ::= CONSTRAINT nm */
133877      case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
133878{pParse->constraintName = yymsp[0].minor.yy0;}
133879        break;
133880      case 30: /* ccons ::= DEFAULT term */
133881      case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
133882{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
133883        break;
133884      case 31: /* ccons ::= DEFAULT LP expr RP */
133885{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
133886        break;
133887      case 33: /* ccons ::= DEFAULT MINUS term */
133888{
133889  ExprSpan v;
133890  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0);
133891  v.zStart = yymsp[-1].minor.yy0.z;
133892  v.zEnd = yymsp[0].minor.yy190.zEnd;
133893  sqlite3AddDefaultValue(pParse,&v);
133894}
133895        break;
133896      case 34: /* ccons ::= DEFAULT ID|INDEXED */
133897{
133898  ExprSpan v;
133899  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
133900  sqlite3AddDefaultValue(pParse,&v);
133901}
133902        break;
133903      case 35: /* ccons ::= NOT NULL onconf */
133904{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
133905        break;
133906      case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
133907{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
133908        break;
133909      case 37: /* ccons ::= UNIQUE onconf */
133910{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
133911                                   SQLITE_IDXTYPE_UNIQUE);}
133912        break;
133913      case 38: /* ccons ::= CHECK LP expr RP */
133914{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
133915        break;
133916      case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
133917{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
133918        break;
133919      case 40: /* ccons ::= defer_subclause */
133920{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
133921        break;
133922      case 41: /* ccons ::= COLLATE ID|STRING */
133923{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
133924        break;
133925      case 44: /* refargs ::= */
133926{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
133927        break;
133928      case 45: /* refargs ::= refargs refarg */
133929{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
133930        break;
133931      case 46: /* refarg ::= MATCH nm */
133932{ yymsp[-1].minor.yy497.value = 0;     yymsp[-1].minor.yy497.mask = 0x000000; }
133933        break;
133934      case 47: /* refarg ::= ON INSERT refact */
133935{ yymsp[-2].minor.yy497.value = 0;     yymsp[-2].minor.yy497.mask = 0x000000; }
133936        break;
133937      case 48: /* refarg ::= ON DELETE refact */
133938{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194;     yymsp[-2].minor.yy497.mask = 0x0000ff; }
133939        break;
133940      case 49: /* refarg ::= ON UPDATE refact */
133941{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8;  yymsp[-2].minor.yy497.mask = 0x00ff00; }
133942        break;
133943      case 50: /* refact ::= SET NULL */
133944{ yymsp[-1].minor.yy194 = OE_SetNull;  /* EV: R-33326-45252 */}
133945        break;
133946      case 51: /* refact ::= SET DEFAULT */
133947{ yymsp[-1].minor.yy194 = OE_SetDflt;  /* EV: R-33326-45252 */}
133948        break;
133949      case 52: /* refact ::= CASCADE */
133950{ yymsp[0].minor.yy194 = OE_Cascade;  /* EV: R-33326-45252 */}
133951        break;
133952      case 53: /* refact ::= RESTRICT */
133953{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
133954        break;
133955      case 54: /* refact ::= NO ACTION */
133956{ yymsp[-1].minor.yy194 = OE_None;     /* EV: R-33326-45252 */}
133957        break;
133958      case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
133959{yymsp[-2].minor.yy194 = 0;}
133960        break;
133961      case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
133962      case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
133963      case 142: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==142);
133964{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
133965        break;
133966      case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
133967      case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
133968      case 183: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==183);
133969      case 186: /* in_op ::= NOT IN */ yytestcase(yyruleno==186);
133970      case 212: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==212);
133971{yymsp[-1].minor.yy194 = 1;}
133972        break;
133973      case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
133974{yymsp[-1].minor.yy194 = 0;}
133975        break;
133976      case 61: /* tconscomma ::= COMMA */
133977{pParse->constraintName.n = 0;}
133978        break;
133979      case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
133980{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
133981        break;
133982      case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
133983{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
133984                                       SQLITE_IDXTYPE_UNIQUE);}
133985        break;
133986      case 65: /* tcons ::= CHECK LP expr RP onconf */
133987{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
133988        break;
133989      case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
133990{
133991    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
133992    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
133993}
133994        break;
133995      case 68: /* onconf ::= */
133996      case 70: /* orconf ::= */ yytestcase(yyruleno==70);
133997{yymsp[1].minor.yy194 = OE_Default;}
133998        break;
133999      case 69: /* onconf ::= ON CONFLICT resolvetype */
134000{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
134001        break;
134002      case 72: /* resolvetype ::= IGNORE */
134003{yymsp[0].minor.yy194 = OE_Ignore;}
134004        break;
134005      case 73: /* resolvetype ::= REPLACE */
134006      case 143: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==143);
134007{yymsp[0].minor.yy194 = OE_Replace;}
134008        break;
134009      case 74: /* cmd ::= DROP TABLE ifexists fullname */
134010{
134011  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
134012}
134013        break;
134014      case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
134015{
134016  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);
134017}
134018        break;
134019      case 78: /* cmd ::= DROP VIEW ifexists fullname */
134020{
134021  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
134022}
134023        break;
134024      case 79: /* cmd ::= select */
134025{
134026  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
134027  sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
134028  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
134029}
134030        break;
134031      case 80: /* select ::= with selectnowith */
134032{
134033  Select *p = yymsp[0].minor.yy243;
134034  if( p ){
134035    p->pWith = yymsp[-1].minor.yy285;
134036    parserDoubleLinkSelect(pParse, p);
134037  }else{
134038    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
134039  }
134040  yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
134041}
134042        break;
134043      case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
134044{
134045  Select *pRhs = yymsp[0].minor.yy243;
134046  Select *pLhs = yymsp[-2].minor.yy243;
134047  if( pRhs && pRhs->pPrior ){
134048    SrcList *pFrom;
134049    Token x;
134050    x.n = 0;
134051    parserDoubleLinkSelect(pParse, pRhs);
134052    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
134053    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
134054  }
134055  if( pRhs ){
134056    pRhs->op = (u8)yymsp[-1].minor.yy194;
134057    pRhs->pPrior = pLhs;
134058    if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
134059    pRhs->selFlags &= ~SF_MultiValue;
134060    if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
134061  }else{
134062    sqlite3SelectDelete(pParse->db, pLhs);
134063  }
134064  yymsp[-2].minor.yy243 = pRhs;
134065}
134066        break;
134067      case 82: /* multiselect_op ::= UNION */
134068      case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
134069{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
134070        break;
134071      case 83: /* multiselect_op ::= UNION ALL */
134072{yymsp[-1].minor.yy194 = TK_ALL;}
134073        break;
134074      case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
134075{
134076#if SELECTTRACE_ENABLED
134077  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
134078#endif
134079  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);
134080#if SELECTTRACE_ENABLED
134081  /* Populate the Select.zSelName[] string that is used to help with
134082  ** query planner debugging, to differentiate between multiple Select
134083  ** objects in a complex query.
134084  **
134085  ** If the SELECT keyword is immediately followed by a C-style comment
134086  ** then extract the first few alphanumeric characters from within that
134087  ** comment to be the zSelName value.  Otherwise, the label is #N where
134088  ** is an integer that is incremented with each SELECT statement seen.
134089  */
134090  if( yymsp[-8].minor.yy243!=0 ){
134091    const char *z = s.z+6;
134092    int i;
134093    sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
134094                     ++pParse->nSelect);
134095    while( z[0]==' ' ) z++;
134096    if( z[0]=='/' && z[1]=='*' ){
134097      z += 2;
134098      while( z[0]==' ' ) z++;
134099      for(i=0; sqlite3Isalnum(z[i]); i++){}
134100      sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
134101    }
134102  }
134103#endif /* SELECTRACE_ENABLED */
134104}
134105        break;
134106      case 86: /* values ::= VALUES LP nexprlist RP */
134107{
134108  yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
134109}
134110        break;
134111      case 87: /* values ::= values COMMA LP exprlist RP */
134112{
134113  Select *pRight, *pLeft = yymsp[-4].minor.yy243;
134114  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
134115  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
134116  if( pRight ){
134117    pRight->op = TK_ALL;
134118    pRight->pPrior = pLeft;
134119    yymsp[-4].minor.yy243 = pRight;
134120  }else{
134121    yymsp[-4].minor.yy243 = pLeft;
134122  }
134123}
134124        break;
134125      case 88: /* distinct ::= DISTINCT */
134126{yymsp[0].minor.yy194 = SF_Distinct;}
134127        break;
134128      case 89: /* distinct ::= ALL */
134129{yymsp[0].minor.yy194 = SF_All;}
134130        break;
134131      case 91: /* sclp ::= */
134132      case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
134133      case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
134134      case 199: /* exprlist ::= */ yytestcase(yyruleno==199);
134135      case 202: /* paren_exprlist ::= */ yytestcase(yyruleno==202);
134136      case 207: /* eidlist_opt ::= */ yytestcase(yyruleno==207);
134137{yymsp[1].minor.yy148 = 0;}
134138        break;
134139      case 92: /* selcollist ::= sclp expr as */
134140{
134141   yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
134142   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
134143   sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
134144}
134145        break;
134146      case 93: /* selcollist ::= sclp STAR */
134147{
134148  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
134149  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
134150}
134151        break;
134152      case 94: /* selcollist ::= sclp nm DOT STAR */
134153{
134154  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
134155  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134156  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
134157  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
134158}
134159        break;
134160      case 95: /* as ::= AS nm */
134161      case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
134162      case 221: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==221);
134163      case 222: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
134164{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
134165        break;
134166      case 97: /* from ::= */
134167{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
134168        break;
134169      case 98: /* from ::= FROM seltablist */
134170{
134171  yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
134172  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
134173}
134174        break;
134175      case 99: /* stl_prefix ::= seltablist joinop */
134176{
134177   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;
134178}
134179        break;
134180      case 100: /* stl_prefix ::= */
134181{yymsp[1].minor.yy185 = 0;}
134182        break;
134183      case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
134184{
134185  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);
134186  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
134187}
134188        break;
134189      case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
134190{
134191  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);
134192  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
134193}
134194        break;
134195      case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
134196{
134197    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);
134198  }
134199        break;
134200      case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
134201{
134202    if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
134203      yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
134204    }else if( yymsp[-4].minor.yy185->nSrc==1 ){
134205      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);
134206      if( yymsp[-6].minor.yy185 ){
134207        struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
134208        struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
134209        pNew->zName = pOld->zName;
134210        pNew->zDatabase = pOld->zDatabase;
134211        pNew->pSelect = pOld->pSelect;
134212        pOld->zName = pOld->zDatabase = 0;
134213        pOld->pSelect = 0;
134214      }
134215      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
134216    }else{
134217      Select *pSubquery;
134218      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
134219      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
134220      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);
134221    }
134222  }
134223        break;
134224      case 105: /* dbnm ::= */
134225      case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
134226{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
134227        break;
134228      case 107: /* fullname ::= nm dbnm */
134229{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
134230        break;
134231      case 108: /* joinop ::= COMMA|JOIN */
134232{ yymsp[0].minor.yy194 = JT_INNER; }
134233        break;
134234      case 109: /* joinop ::= JOIN_KW JOIN */
134235{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
134236        break;
134237      case 110: /* joinop ::= JOIN_KW nm JOIN */
134238{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
134239        break;
134240      case 111: /* joinop ::= JOIN_KW nm nm JOIN */
134241{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
134242        break;
134243      case 112: /* on_opt ::= ON expr */
134244      case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
134245      case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
134246      case 195: /* case_else ::= ELSE expr */ yytestcase(yyruleno==195);
134247{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
134248        break;
134249      case 113: /* on_opt ::= */
134250      case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
134251      case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
134252      case 196: /* case_else ::= */ yytestcase(yyruleno==196);
134253      case 198: /* case_operand ::= */ yytestcase(yyruleno==198);
134254{yymsp[1].minor.yy72 = 0;}
134255        break;
134256      case 115: /* indexed_opt ::= INDEXED BY nm */
134257{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
134258        break;
134259      case 116: /* indexed_opt ::= NOT INDEXED */
134260{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
134261        break;
134262      case 117: /* using_opt ::= USING LP idlist RP */
134263{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
134264        break;
134265      case 118: /* using_opt ::= */
134266      case 144: /* idlist_opt ::= */ yytestcase(yyruleno==144);
134267{yymsp[1].minor.yy254 = 0;}
134268        break;
134269      case 120: /* orderby_opt ::= ORDER BY sortlist */
134270      case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
134271{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
134272        break;
134273      case 121: /* sortlist ::= sortlist COMMA expr sortorder */
134274{
134275  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
134276  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
134277}
134278        break;
134279      case 122: /* sortlist ::= expr sortorder */
134280{
134281  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
134282  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
134283}
134284        break;
134285      case 123: /* sortorder ::= ASC */
134286{yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
134287        break;
134288      case 124: /* sortorder ::= DESC */
134289{yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
134290        break;
134291      case 125: /* sortorder ::= */
134292{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
134293        break;
134294      case 130: /* limit_opt ::= */
134295{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
134296        break;
134297      case 131: /* limit_opt ::= LIMIT expr */
134298{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
134299        break;
134300      case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
134301{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
134302        break;
134303      case 133: /* limit_opt ::= LIMIT expr COMMA expr */
134304{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
134305        break;
134306      case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
134307{
134308  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
134309  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
134310  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
134311}
134312        break;
134313      case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
134314{
134315  sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
134316  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
134317  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
134318  sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
134319}
134320        break;
134321      case 138: /* setlist ::= setlist COMMA nm EQ expr */
134322{
134323  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
134324  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
134325}
134326        break;
134327      case 139: /* setlist ::= nm EQ expr */
134328{
134329  yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
134330  sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
134331}
134332  yymsp[-2].minor.yy148 = yylhsminor.yy148;
134333        break;
134334      case 140: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
134335{
134336  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
134337  sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
134338}
134339        break;
134340      case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
134341{
134342  sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
134343  sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
134344}
134345        break;
134346      case 145: /* idlist_opt ::= LP idlist RP */
134347{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
134348        break;
134349      case 146: /* idlist ::= idlist COMMA nm */
134350{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
134351        break;
134352      case 147: /* idlist ::= nm */
134353{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
134354        break;
134355      case 148: /* expr ::= LP expr RP */
134356{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;}
134357        break;
134358      case 149: /* term ::= NULL */
134359      case 154: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==154);
134360      case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
134361{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
134362        break;
134363      case 150: /* expr ::= ID|INDEXED */
134364      case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
134365{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
134366        break;
134367      case 152: /* expr ::= nm DOT nm */
134368{
134369  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134370  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
134371  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134372  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
134373}
134374        break;
134375      case 153: /* expr ::= nm DOT nm DOT nm */
134376{
134377  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
134378  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134379  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
134380  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
134381  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134382  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
134383}
134384        break;
134385      case 156: /* expr ::= VARIABLE */
134386{
134387  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
134388    spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
134389    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr);
134390  }else{
134391    /* When doing a nested parse, one can include terms in an expression
134392    ** that look like this:   #1 #2 ...  These terms refer to registers
134393    ** in the virtual machine.  #N is the N-th register. */
134394    Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
134395    assert( t.n>=2 );
134396    spanSet(&yymsp[0].minor.yy190, &t, &t);
134397    if( pParse->nested==0 ){
134398      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
134399      yymsp[0].minor.yy190.pExpr = 0;
134400    }else{
134401      yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
134402      if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
134403    }
134404  }
134405}
134406        break;
134407      case 157: /* expr ::= expr COLLATE ID|STRING */
134408{
134409  yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
134410  yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134411}
134412        break;
134413      case 158: /* expr ::= CAST LP expr AS typetoken RP */
134414{
134415  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134416  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0);
134417}
134418        break;
134419      case 159: /* expr ::= ID|INDEXED LP distinct exprlist RP */
134420{
134421  if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
134422    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
134423  }
134424  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
134425  spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
134426  if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
134427    yylhsminor.yy190.pExpr->flags |= EP_Distinct;
134428  }
134429}
134430  yymsp[-4].minor.yy190 = yylhsminor.yy190;
134431        break;
134432      case 160: /* expr ::= ID|INDEXED LP STAR RP */
134433{
134434  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
134435  spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
134436}
134437  yymsp[-3].minor.yy190 = yylhsminor.yy190;
134438        break;
134439      case 161: /* term ::= CTIME_KW */
134440{
134441  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
134442  spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
134443}
134444  yymsp[0].minor.yy190 = yylhsminor.yy190;
134445        break;
134446      case 162: /* expr ::= expr AND expr */
134447      case 163: /* expr ::= expr OR expr */ yytestcase(yyruleno==163);
134448      case 164: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==164);
134449      case 165: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==165);
134450      case 166: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==166);
134451      case 167: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==167);
134452      case 168: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==168);
134453      case 169: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==169);
134454{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
134455        break;
134456      case 170: /* likeop ::= LIKE_KW|MATCH */
134457{yymsp[0].minor.yy392.eOperator = yymsp[0].minor.yy0; yymsp[0].minor.yy392.bNot = 0;/*A-overwrites-X*/}
134458        break;
134459      case 171: /* likeop ::= NOT LIKE_KW|MATCH */
134460{yymsp[-1].minor.yy392.eOperator = yymsp[0].minor.yy0; yymsp[-1].minor.yy392.bNot = 1;}
134461        break;
134462      case 172: /* expr ::= expr likeop expr */
134463{
134464  ExprList *pList;
134465  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
134466  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
134467  yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy392.eOperator);
134468  exprNot(pParse, yymsp[-1].minor.yy392.bNot, &yymsp[-2].minor.yy190);
134469  yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134470  if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
134471}
134472        break;
134473      case 173: /* expr ::= expr likeop expr ESCAPE expr */
134474{
134475  ExprList *pList;
134476  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134477  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
134478  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
134479  yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy392.eOperator);
134480  exprNot(pParse, yymsp[-3].minor.yy392.bNot, &yymsp[-4].minor.yy190);
134481  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134482  if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
134483}
134484        break;
134485      case 174: /* expr ::= expr ISNULL|NOTNULL */
134486{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
134487        break;
134488      case 175: /* expr ::= expr NOT NULL */
134489{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
134490        break;
134491      case 176: /* expr ::= expr IS expr */
134492{
134493  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
134494  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
134495}
134496        break;
134497      case 177: /* expr ::= expr IS NOT expr */
134498{
134499  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
134500  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
134501}
134502        break;
134503      case 178: /* expr ::= NOT expr */
134504      case 179: /* expr ::= BITNOT expr */ yytestcase(yyruleno==179);
134505{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134506        break;
134507      case 180: /* expr ::= MINUS expr */
134508{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134509        break;
134510      case 181: /* expr ::= PLUS expr */
134511{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134512        break;
134513      case 182: /* between_op ::= BETWEEN */
134514      case 185: /* in_op ::= IN */ yytestcase(yyruleno==185);
134515{yymsp[0].minor.yy194 = 0;}
134516        break;
134517      case 184: /* expr ::= expr between_op expr AND expr */
134518{
134519  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134520  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
134521  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134522  if( yymsp[-4].minor.yy190.pExpr ){
134523    yymsp[-4].minor.yy190.pExpr->x.pList = pList;
134524  }else{
134525    sqlite3ExprListDelete(pParse->db, pList);
134526  }
134527  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134528  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134529}
134530        break;
134531      case 187: /* expr ::= expr in_op LP exprlist RP */
134532{
134533    if( yymsp[-1].minor.yy148==0 ){
134534      /* Expressions of the form
134535      **
134536      **      expr1 IN ()
134537      **      expr1 NOT IN ()
134538      **
134539      ** simplify to constants 0 (false) and 1 (true), respectively,
134540      ** regardless of the value of expr1.
134541      */
134542      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
134543      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]);
134544    }else if( yymsp[-1].minor.yy148->nExpr==1 ){
134545      /* Expressions of the form:
134546      **
134547      **      expr1 IN (?1)
134548      **      expr1 NOT IN (?2)
134549      **
134550      ** with exactly one value on the RHS can be simplified to something
134551      ** like this:
134552      **
134553      **      expr1 == ?1
134554      **      expr1 <> ?2
134555      **
134556      ** But, the RHS of the == or <> is marked with the EP_Generic flag
134557      ** so that it may not contribute to the computation of comparison
134558      ** affinity or the collating sequence to use for comparison.  Otherwise,
134559      ** the semantics would be subtly different from IN or NOT IN.
134560      */
134561      Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
134562      yymsp[-1].minor.yy148->a[0].pExpr = 0;
134563      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
134564      /* pRHS cannot be NULL because a malloc error would have been detected
134565      ** before now and control would have never reached this point */
134566      if( ALWAYS(pRHS) ){
134567        pRHS->flags &= ~EP_Collate;
134568        pRHS->flags |= EP_Generic;
134569      }
134570      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0);
134571    }else{
134572      yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134573      if( yymsp[-4].minor.yy190.pExpr ){
134574        yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
134575        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
134576      }else{
134577        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
134578      }
134579      exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134580    }
134581    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134582  }
134583        break;
134584      case 188: /* expr ::= LP select RP */
134585{
134586    spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
134587    yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
134588    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
134589  }
134590        break;
134591      case 189: /* expr ::= expr in_op LP select RP */
134592{
134593    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134594    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
134595    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134596    yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134597  }
134598        break;
134599      case 190: /* expr ::= expr in_op nm dbnm paren_exprlist */
134600{
134601    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
134602    Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
134603    if( yymsp[0].minor.yy148 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
134604    yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134605    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
134606    exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134607    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];
134608  }
134609        break;
134610      case 191: /* expr ::= EXISTS LP select RP */
134611{
134612    Expr *p;
134613    spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
134614    p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
134615    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
134616  }
134617        break;
134618      case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
134619{
134620  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-C*/
134621  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0);
134622  if( yymsp[-4].minor.yy190.pExpr ){
134623    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;
134624    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
134625  }else{
134626    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
134627    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
134628  }
134629}
134630        break;
134631      case 193: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
134632{
134633  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
134634  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
134635}
134636        break;
134637      case 194: /* case_exprlist ::= WHEN expr THEN expr */
134638{
134639  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134640  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
134641}
134642        break;
134643      case 197: /* case_operand ::= expr */
134644{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
134645        break;
134646      case 200: /* nexprlist ::= nexprlist COMMA expr */
134647{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
134648        break;
134649      case 201: /* nexprlist ::= expr */
134650{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
134651        break;
134652      case 203: /* paren_exprlist ::= LP exprlist RP */
134653      case 208: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==208);
134654{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
134655        break;
134656      case 204: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
134657{
134658  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
134659                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
134660                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
134661}
134662        break;
134663      case 205: /* uniqueflag ::= UNIQUE */
134664      case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
134665{yymsp[0].minor.yy194 = OE_Abort;}
134666        break;
134667      case 206: /* uniqueflag ::= */
134668{yymsp[1].minor.yy194 = OE_None;}
134669        break;
134670      case 209: /* eidlist ::= eidlist COMMA nm collate sortorder */
134671{
134672  yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
134673}
134674        break;
134675      case 210: /* eidlist ::= nm collate sortorder */
134676{
134677  yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
134678}
134679        break;
134680      case 213: /* cmd ::= DROP INDEX ifexists fullname */
134681{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
134682        break;
134683      case 214: /* cmd ::= VACUUM */
134684      case 215: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==215);
134685{sqlite3Vacuum(pParse);}
134686        break;
134687      case 216: /* cmd ::= PRAGMA nm dbnm */
134688{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
134689        break;
134690      case 217: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
134691{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
134692        break;
134693      case 218: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
134694{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
134695        break;
134696      case 219: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
134697{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
134698        break;
134699      case 220: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
134700{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
134701        break;
134702      case 223: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
134703{
134704  Token all;
134705  all.z = yymsp[-3].minor.yy0.z;
134706  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
134707  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
134708}
134709        break;
134710      case 224: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
134711{
134712  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);
134713  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
134714}
134715        break;
134716      case 225: /* trigger_time ::= BEFORE */
134717{ yymsp[0].minor.yy194 = TK_BEFORE; }
134718        break;
134719      case 226: /* trigger_time ::= AFTER */
134720{ yymsp[0].minor.yy194 = TK_AFTER;  }
134721        break;
134722      case 227: /* trigger_time ::= INSTEAD OF */
134723{ yymsp[-1].minor.yy194 = TK_INSTEAD;}
134724        break;
134725      case 228: /* trigger_time ::= */
134726{ yymsp[1].minor.yy194 = TK_BEFORE; }
134727        break;
134728      case 229: /* trigger_event ::= DELETE|INSERT */
134729      case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
134730{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
134731        break;
134732      case 231: /* trigger_event ::= UPDATE OF idlist */
134733{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
134734        break;
134735      case 232: /* when_clause ::= */
134736      case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
134737{ yymsp[1].minor.yy72 = 0; }
134738        break;
134739      case 233: /* when_clause ::= WHEN expr */
134740      case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
134741{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
134742        break;
134743      case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
134744{
134745  assert( yymsp[-2].minor.yy145!=0 );
134746  yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
134747  yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
134748}
134749        break;
134750      case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
134751{
134752  assert( yymsp[-1].minor.yy145!=0 );
134753  yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
134754}
134755        break;
134756      case 236: /* trnm ::= nm DOT nm */
134757{
134758  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
134759  sqlite3ErrorMsg(pParse,
134760        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
134761        "statements within triggers");
134762}
134763        break;
134764      case 237: /* tridxby ::= INDEXED BY nm */
134765{
134766  sqlite3ErrorMsg(pParse,
134767        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
134768        "within triggers");
134769}
134770        break;
134771      case 238: /* tridxby ::= NOT INDEXED */
134772{
134773  sqlite3ErrorMsg(pParse,
134774        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
134775        "within triggers");
134776}
134777        break;
134778      case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
134779{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
134780        break;
134781      case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
134782{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*/}
134783        break;
134784      case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
134785{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
134786        break;
134787      case 242: /* trigger_cmd ::= select */
134788{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
134789        break;
134790      case 243: /* expr ::= RAISE LP IGNORE RP */
134791{
134792  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
134793  yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
134794  if( yymsp[-3].minor.yy190.pExpr ){
134795    yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
134796  }
134797}
134798        break;
134799      case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
134800{
134801  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
134802  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
134803  if( yymsp[-5].minor.yy190.pExpr ) {
134804    yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
134805  }
134806}
134807        break;
134808      case 245: /* raisetype ::= ROLLBACK */
134809{yymsp[0].minor.yy194 = OE_Rollback;}
134810        break;
134811      case 247: /* raisetype ::= FAIL */
134812{yymsp[0].minor.yy194 = OE_Fail;}
134813        break;
134814      case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
134815{
134816  sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
134817}
134818        break;
134819      case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
134820{
134821  sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
134822}
134823        break;
134824      case 250: /* cmd ::= DETACH database_kw_opt expr */
134825{
134826  sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
134827}
134828        break;
134829      case 253: /* cmd ::= REINDEX */
134830{sqlite3Reindex(pParse, 0, 0);}
134831        break;
134832      case 254: /* cmd ::= REINDEX nm dbnm */
134833{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
134834        break;
134835      case 255: /* cmd ::= ANALYZE */
134836{sqlite3Analyze(pParse, 0, 0);}
134837        break;
134838      case 256: /* cmd ::= ANALYZE nm dbnm */
134839{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
134840        break;
134841      case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
134842{
134843  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
134844}
134845        break;
134846      case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
134847{
134848  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
134849  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
134850}
134851        break;
134852      case 259: /* add_column_fullname ::= fullname */
134853{
134854  disableLookaside(pParse);
134855  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
134856}
134857        break;
134858      case 260: /* cmd ::= create_vtab */
134859{sqlite3VtabFinishParse(pParse,0);}
134860        break;
134861      case 261: /* cmd ::= create_vtab LP vtabarglist RP */
134862{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
134863        break;
134864      case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
134865{
134866    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
134867}
134868        break;
134869      case 263: /* vtabarg ::= */
134870{sqlite3VtabArgInit(pParse);}
134871        break;
134872      case 264: /* vtabargtoken ::= ANY */
134873      case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
134874      case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
134875{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
134876        break;
134877      case 267: /* with ::= */
134878{yymsp[1].minor.yy285 = 0;}
134879        break;
134880      case 268: /* with ::= WITH wqlist */
134881{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
134882        break;
134883      case 269: /* with ::= WITH RECURSIVE wqlist */
134884{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
134885        break;
134886      case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
134887{
134888  yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
134889}
134890        break;
134891      case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
134892{
134893  yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
134894}
134895        break;
134896      default:
134897      /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
134898      /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
134899      /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
134900      /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
134901      /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
134902      /* (277) explain ::= */ yytestcase(yyruleno==277);
134903      /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
134904      /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
134905      /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
134906      /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
134907      /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
134908      /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
134909      /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
134910      /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
134911      /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
134912      /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
134913      /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
134914      /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
134915      /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
134916      /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
134917      /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
134918      /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
134919      /* (294) carglist ::= */ yytestcase(yyruleno==294);
134920      /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
134921      /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
134922      /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
134923      /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
134924      /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
134925      /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
134926      /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
134927      /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
134928      /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
134929      /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
134930      /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
134931      /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
134932      /* (307) exprlist ::= nexprlist */ yytestcase(yyruleno==307);
134933      /* (308) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=308);
134934      /* (309) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=309);
134935      /* (310) nmnum ::= ON */ yytestcase(yyruleno==310);
134936      /* (311) nmnum ::= DELETE */ yytestcase(yyruleno==311);
134937      /* (312) nmnum ::= DEFAULT */ yytestcase(yyruleno==312);
134938      /* (313) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==313);
134939      /* (314) foreach_clause ::= */ yytestcase(yyruleno==314);
134940      /* (315) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==315);
134941      /* (316) trnm ::= nm */ yytestcase(yyruleno==316);
134942      /* (317) tridxby ::= */ yytestcase(yyruleno==317);
134943      /* (318) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==318);
134944      /* (319) database_kw_opt ::= */ yytestcase(yyruleno==319);
134945      /* (320) kwcolumn_opt ::= */ yytestcase(yyruleno==320);
134946      /* (321) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==321);
134947      /* (322) vtabarglist ::= vtabarg */ yytestcase(yyruleno==322);
134948      /* (323) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==323);
134949      /* (324) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==324);
134950      /* (325) anylist ::= */ yytestcase(yyruleno==325);
134951      /* (326) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==326);
134952      /* (327) anylist ::= anylist ANY */ yytestcase(yyruleno==327);
134953        break;
134954/********** End reduce actions ************************************************/
134955  };
134956  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
134957  yygoto = yyRuleInfo[yyruleno].lhs;
134958  yysize = yyRuleInfo[yyruleno].nrhs;
134959  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
134960  if( yyact <= YY_MAX_SHIFTREDUCE ){
134961    if( yyact>YY_MAX_SHIFT ){
134962      yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134963    }
134964    yymsp -= yysize-1;
134965    yypParser->yytos = yymsp;
134966    yymsp->stateno = (YYACTIONTYPE)yyact;
134967    yymsp->major = (YYCODETYPE)yygoto;
134968    yyTraceShift(yypParser, yyact);
134969  }else{
134970    assert( yyact == YY_ACCEPT_ACTION );
134971    yypParser->yytos -= yysize;
134972    yy_accept(yypParser);
134973  }
134974}
134975
134976/*
134977** The following code executes when the parse fails
134978*/
134979#ifndef YYNOERRORRECOVERY
134980static void yy_parse_failed(
134981  yyParser *yypParser           /* The parser */
134982){
134983  sqlite3ParserARG_FETCH;
134984#ifndef NDEBUG
134985  if( yyTraceFILE ){
134986    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
134987  }
134988#endif
134989  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
134990  /* Here code is inserted which will be executed whenever the
134991  ** parser fails */
134992/************ Begin %parse_failure code ***************************************/
134993/************ End %parse_failure code *****************************************/
134994  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
134995}
134996#endif /* YYNOERRORRECOVERY */
134997
134998/*
134999** The following code executes when a syntax error first occurs.
135000*/
135001static void yy_syntax_error(
135002  yyParser *yypParser,           /* The parser */
135003  int yymajor,                   /* The major type of the error token */
135004  sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
135005){
135006  sqlite3ParserARG_FETCH;
135007#define TOKEN yyminor
135008/************ Begin %syntax_error code ****************************************/
135009
135010  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
135011  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
135012  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
135013/************ End %syntax_error code ******************************************/
135014  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
135015}
135016
135017/*
135018** The following is executed when the parser accepts
135019*/
135020static void yy_accept(
135021  yyParser *yypParser           /* The parser */
135022){
135023  sqlite3ParserARG_FETCH;
135024#ifndef NDEBUG
135025  if( yyTraceFILE ){
135026    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
135027  }
135028#endif
135029#ifndef YYNOERRORRECOVERY
135030  yypParser->yyerrcnt = -1;
135031#endif
135032  assert( yypParser->yytos==yypParser->yystack );
135033  /* Here code is inserted which will be executed whenever the
135034  ** parser accepts */
135035/*********** Begin %parse_accept code *****************************************/
135036/*********** End %parse_accept code *******************************************/
135037  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
135038}
135039
135040/* The main parser program.
135041** The first argument is a pointer to a structure obtained from
135042** "sqlite3ParserAlloc" which describes the current state of the parser.
135043** The second argument is the major token number.  The third is
135044** the minor token.  The fourth optional argument is whatever the
135045** user wants (and specified in the grammar) and is available for
135046** use by the action routines.
135047**
135048** Inputs:
135049** <ul>
135050** <li> A pointer to the parser (an opaque structure.)
135051** <li> The major token number.
135052** <li> The minor token number.
135053** <li> An option argument of a grammar-specified type.
135054** </ul>
135055**
135056** Outputs:
135057** None.
135058*/
135059SQLITE_PRIVATE void sqlite3Parser(
135060  void *yyp,                   /* The parser */
135061  int yymajor,                 /* The major token code number */
135062  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
135063  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
135064){
135065  YYMINORTYPE yyminorunion;
135066  unsigned int yyact;   /* The parser action. */
135067#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
135068  int yyendofinput;     /* True if we are at the end of input */
135069#endif
135070#ifdef YYERRORSYMBOL
135071  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
135072#endif
135073  yyParser *yypParser;  /* The parser */
135074
135075  yypParser = (yyParser*)yyp;
135076  assert( yypParser->yytos!=0 );
135077#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
135078  yyendofinput = (yymajor==0);
135079#endif
135080  sqlite3ParserARG_STORE;
135081
135082#ifndef NDEBUG
135083  if( yyTraceFILE ){
135084    fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
135085  }
135086#endif
135087
135088  do{
135089    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
135090    if( yyact <= YY_MAX_SHIFTREDUCE ){
135091      yy_shift(yypParser,yyact,yymajor,yyminor);
135092#ifndef YYNOERRORRECOVERY
135093      yypParser->yyerrcnt--;
135094#endif
135095      yymajor = YYNOCODE;
135096    }else if( yyact <= YY_MAX_REDUCE ){
135097      yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
135098    }else{
135099      assert( yyact == YY_ERROR_ACTION );
135100      yyminorunion.yy0 = yyminor;
135101#ifdef YYERRORSYMBOL
135102      int yymx;
135103#endif
135104#ifndef NDEBUG
135105      if( yyTraceFILE ){
135106        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
135107      }
135108#endif
135109#ifdef YYERRORSYMBOL
135110      /* A syntax error has occurred.
135111      ** The response to an error depends upon whether or not the
135112      ** grammar defines an error token "ERROR".
135113      **
135114      ** This is what we do if the grammar does define ERROR:
135115      **
135116      **  * Call the %syntax_error function.
135117      **
135118      **  * Begin popping the stack until we enter a state where
135119      **    it is legal to shift the error symbol, then shift
135120      **    the error symbol.
135121      **
135122      **  * Set the error count to three.
135123      **
135124      **  * Begin accepting and shifting new tokens.  No new error
135125      **    processing will occur until three tokens have been
135126      **    shifted successfully.
135127      **
135128      */
135129      if( yypParser->yyerrcnt<0 ){
135130        yy_syntax_error(yypParser,yymajor,yyminor);
135131      }
135132      yymx = yypParser->yytos->major;
135133      if( yymx==YYERRORSYMBOL || yyerrorhit ){
135134#ifndef NDEBUG
135135        if( yyTraceFILE ){
135136          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
135137             yyTracePrompt,yyTokenName[yymajor]);
135138        }
135139#endif
135140        yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
135141        yymajor = YYNOCODE;
135142      }else{
135143        while( yypParser->yytos >= &yypParser->yystack
135144            && yymx != YYERRORSYMBOL
135145            && (yyact = yy_find_reduce_action(
135146                        yypParser->yytos->stateno,
135147                        YYERRORSYMBOL)) >= YY_MIN_REDUCE
135148        ){
135149          yy_pop_parser_stack(yypParser);
135150        }
135151        if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
135152          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135153          yy_parse_failed(yypParser);
135154#ifndef YYNOERRORRECOVERY
135155          yypParser->yyerrcnt = -1;
135156#endif
135157          yymajor = YYNOCODE;
135158        }else if( yymx!=YYERRORSYMBOL ){
135159          yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
135160        }
135161      }
135162      yypParser->yyerrcnt = 3;
135163      yyerrorhit = 1;
135164#elif defined(YYNOERRORRECOVERY)
135165      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
135166      ** do any kind of error recovery.  Instead, simply invoke the syntax
135167      ** error routine and continue going as if nothing had happened.
135168      **
135169      ** Applications can set this macro (for example inside %include) if
135170      ** they intend to abandon the parse upon the first syntax error seen.
135171      */
135172      yy_syntax_error(yypParser,yymajor, yyminor);
135173      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135174      yymajor = YYNOCODE;
135175
135176#else  /* YYERRORSYMBOL is not defined */
135177      /* This is what we do if the grammar does not define ERROR:
135178      **
135179      **  * Report an error message, and throw away the input token.
135180      **
135181      **  * If the input token is $, then fail the parse.
135182      **
135183      ** As before, subsequent error messages are suppressed until
135184      ** three input tokens have been successfully shifted.
135185      */
135186      if( yypParser->yyerrcnt<=0 ){
135187        yy_syntax_error(yypParser,yymajor, yyminor);
135188      }
135189      yypParser->yyerrcnt = 3;
135190      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135191      if( yyendofinput ){
135192        yy_parse_failed(yypParser);
135193#ifndef YYNOERRORRECOVERY
135194        yypParser->yyerrcnt = -1;
135195#endif
135196      }
135197      yymajor = YYNOCODE;
135198#endif
135199    }
135200  }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
135201#ifndef NDEBUG
135202  if( yyTraceFILE ){
135203    yyStackEntry *i;
135204    char cDiv = '[';
135205    fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
135206    for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
135207      fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
135208      cDiv = ' ';
135209    }
135210    fprintf(yyTraceFILE,"]\n");
135211  }
135212#endif
135213  return;
135214}
135215
135216/************** End of parse.c ***********************************************/
135217/************** Begin file tokenize.c ****************************************/
135218/*
135219** 2001 September 15
135220**
135221** The author disclaims copyright to this source code.  In place of
135222** a legal notice, here is a blessing:
135223**
135224**    May you do good and not evil.
135225**    May you find forgiveness for yourself and forgive others.
135226**    May you share freely, never taking more than you give.
135227**
135228*************************************************************************
135229** An tokenizer for SQL
135230**
135231** This file contains C code that splits an SQL input string up into
135232** individual tokens and sends those tokens one-by-one over to the
135233** parser for analysis.
135234*/
135235/* #include "sqliteInt.h" */
135236/* #include <stdlib.h> */
135237
135238/* Character classes for tokenizing
135239**
135240** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
135241** using a lookup table, whereas a switch() directly on c uses a binary search.
135242** The lookup table is much faster.  To maximize speed, and to ensure that
135243** a lookup table is used, all of the classes need to be small integers and
135244** all of them need to be used within the switch.
135245*/
135246#define CC_X          0    /* The letter 'x', or start of BLOB literal */
135247#define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
135248#define CC_ID         2    /* unicode characters usable in IDs */
135249#define CC_DIGIT      3    /* Digits */
135250#define CC_DOLLAR     4    /* '$' */
135251#define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
135252#define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
135253#define CC_SPACE      7    /* Space characters */
135254#define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
135255#define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
135256#define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
135257#define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
135258#define CC_LT        12    /* '<'.  Part of < or <= or <> */
135259#define CC_GT        13    /* '>'.  Part of > or >= */
135260#define CC_EQ        14    /* '='.  Part of = or == */
135261#define CC_BANG      15    /* '!'.  Part of != */
135262#define CC_SLASH     16    /* '/'.  / or c-style comment */
135263#define CC_LP        17    /* '(' */
135264#define CC_RP        18    /* ')' */
135265#define CC_SEMI      19    /* ';' */
135266#define CC_PLUS      20    /* '+' */
135267#define CC_STAR      21    /* '*' */
135268#define CC_PERCENT   22    /* '%' */
135269#define CC_COMMA     23    /* ',' */
135270#define CC_AND       24    /* '&' */
135271#define CC_TILDA     25    /* '~' */
135272#define CC_DOT       26    /* '.' */
135273#define CC_ILLEGAL   27    /* Illegal character */
135274
135275static const unsigned char aiClass[] = {
135276#ifdef SQLITE_ASCII
135277/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
135278/* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
135279/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135280/* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
135281/* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
135282/* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
135283/* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
135284/* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
135285/* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
135286/* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135287/* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135288/* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135289/* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135290/* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135291/* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135292/* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135293/* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
135294#endif
135295#ifdef SQLITE_EBCDIC
135296/*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
135297/* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
135298/* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135299/* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135300/* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135301/* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
135302/* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
135303/* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  7,
135304/* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
135305/* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135306/* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135307/* 9x */   25,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
135308/* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
135309/* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135310/* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135311/* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
135312/* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
135313#endif
135314};
135315
135316/*
135317** The charMap() macro maps alphabetic characters (only) into their
135318** lower-case ASCII equivalent.  On ASCII machines, this is just
135319** an upper-to-lower case map.  On EBCDIC machines we also need
135320** to adjust the encoding.  The mapping is only valid for alphabetics
135321** which are the only characters for which this feature is used.
135322**
135323** Used by keywordhash.h
135324*/
135325#ifdef SQLITE_ASCII
135326# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
135327#endif
135328#ifdef SQLITE_EBCDIC
135329# define charMap(X) ebcdicToAscii[(unsigned char)X]
135330const unsigned char ebcdicToAscii[] = {
135331/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
135332   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
135333   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
135334   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
135335   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
135336   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
135337   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
135338   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
135339   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
135340   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
135341   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
135342   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
135343   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
135344   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
135345   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
135346   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
135347   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
135348};
135349#endif
135350
135351/*
135352** The sqlite3KeywordCode function looks up an identifier to determine if
135353** it is a keyword.  If it is a keyword, the token code of that keyword is
135354** returned.  If the input is not a keyword, TK_ID is returned.
135355**
135356** The implementation of this routine was generated by a program,
135357** mkkeywordhash.c, located in the tool subdirectory of the distribution.
135358** The output of the mkkeywordhash.c program is written into a file
135359** named keywordhash.h and then included into this source file by
135360** the #include below.
135361*/
135362/************** Include keywordhash.h in the middle of tokenize.c ************/
135363/************** Begin file keywordhash.h *************************************/
135364/***** This file contains automatically generated code ******
135365**
135366** The code in this file has been automatically generated by
135367**
135368**   sqlite/tool/mkkeywordhash.c
135369**
135370** The code in this file implements a function that determines whether
135371** or not a given identifier is really an SQL keyword.  The same thing
135372** might be implemented more directly using a hand-written hash table.
135373** But by using this automatically generated code, the size of the code
135374** is substantially reduced.  This is important for embedded applications
135375** on platforms with limited memory.
135376*/
135377/* Hash score: 182 */
135378static int keywordCode(const char *z, int n, int *pType){
135379  /* zText[] encodes 834 bytes of keywords in 554 bytes */
135380  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
135381  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
135382  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
135383  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
135384  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
135385  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
135386  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
135387  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
135388  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
135389  /*   VACUUMVIEWINITIALLY                                                */
135390  static const char zText[553] = {
135391    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
135392    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
135393    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
135394    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
135395    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
135396    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
135397    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
135398    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
135399    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
135400    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
135401    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
135402    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
135403    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
135404    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
135405    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
135406    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
135407    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
135408    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
135409    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
135410    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
135411    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
135412    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
135413    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
135414    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
135415    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
135416    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
135417    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
135418    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
135419    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
135420    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
135421    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
135422  };
135423  static const unsigned char aHash[127] = {
135424      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
135425      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
135426     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
135427       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
135428       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
135429      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
135430     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
135431      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
135432      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
135433      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
135434  };
135435  static const unsigned char aNext[124] = {
135436       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
135437       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
135438       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
135439       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
135440       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
135441       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
135442       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
135443      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
135444       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
135445      73,  83,   0,  35,  68,   0,   0,
135446  };
135447  static const unsigned char aLen[124] = {
135448       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
135449       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
135450      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
135451       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
135452       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
135453       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
135454       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
135455      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
135456       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
135457       3,   5,   5,   6,   4,   9,   3,
135458  };
135459  static const unsigned short int aOffset[124] = {
135460       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
135461      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
135462      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
135463     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
135464     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
135465     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
135466     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
135467     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
135468     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
135469     521, 524, 529, 534, 540, 544, 549,
135470  };
135471  static const unsigned char aCode[124] = {
135472    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
135473    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
135474    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
135475    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
135476    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
135477    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
135478    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
135479    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
135480    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
135481    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
135482    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
135483    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
135484    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
135485    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
135486    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
135487    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
135488    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
135489    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
135490    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
135491    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
135492    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
135493    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
135494    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
135495    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
135496    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
135497  };
135498  int i, j;
135499  const char *zKW;
135500  if( n>=2 ){
135501    i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
135502    for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
135503      if( aLen[i]!=n ) continue;
135504      j = 0;
135505      zKW = &zText[aOffset[i]];
135506#ifdef SQLITE_ASCII
135507      while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
135508#endif
135509#ifdef SQLITE_EBCDIC
135510      while( j<n && toupper(z[j])==zKW[j] ){ j++; }
135511#endif
135512      if( j<n ) continue;
135513      testcase( i==0 ); /* REINDEX */
135514      testcase( i==1 ); /* INDEXED */
135515      testcase( i==2 ); /* INDEX */
135516      testcase( i==3 ); /* DESC */
135517      testcase( i==4 ); /* ESCAPE */
135518      testcase( i==5 ); /* EACH */
135519      testcase( i==6 ); /* CHECK */
135520      testcase( i==7 ); /* KEY */
135521      testcase( i==8 ); /* BEFORE */
135522      testcase( i==9 ); /* FOREIGN */
135523      testcase( i==10 ); /* FOR */
135524      testcase( i==11 ); /* IGNORE */
135525      testcase( i==12 ); /* REGEXP */
135526      testcase( i==13 ); /* EXPLAIN */
135527      testcase( i==14 ); /* INSTEAD */
135528      testcase( i==15 ); /* ADD */
135529      testcase( i==16 ); /* DATABASE */
135530      testcase( i==17 ); /* AS */
135531      testcase( i==18 ); /* SELECT */
135532      testcase( i==19 ); /* TABLE */
135533      testcase( i==20 ); /* LEFT */
135534      testcase( i==21 ); /* THEN */
135535      testcase( i==22 ); /* END */
135536      testcase( i==23 ); /* DEFERRABLE */
135537      testcase( i==24 ); /* ELSE */
135538      testcase( i==25 ); /* EXCEPT */
135539      testcase( i==26 ); /* TRANSACTION */
135540      testcase( i==27 ); /* ACTION */
135541      testcase( i==28 ); /* ON */
135542      testcase( i==29 ); /* NATURAL */
135543      testcase( i==30 ); /* ALTER */
135544      testcase( i==31 ); /* RAISE */
135545      testcase( i==32 ); /* EXCLUSIVE */
135546      testcase( i==33 ); /* EXISTS */
135547      testcase( i==34 ); /* SAVEPOINT */
135548      testcase( i==35 ); /* INTERSECT */
135549      testcase( i==36 ); /* TRIGGER */
135550      testcase( i==37 ); /* REFERENCES */
135551      testcase( i==38 ); /* CONSTRAINT */
135552      testcase( i==39 ); /* INTO */
135553      testcase( i==40 ); /* OFFSET */
135554      testcase( i==41 ); /* OF */
135555      testcase( i==42 ); /* SET */
135556      testcase( i==43 ); /* TEMPORARY */
135557      testcase( i==44 ); /* TEMP */
135558      testcase( i==45 ); /* OR */
135559      testcase( i==46 ); /* UNIQUE */
135560      testcase( i==47 ); /* QUERY */
135561      testcase( i==48 ); /* WITHOUT */
135562      testcase( i==49 ); /* WITH */
135563      testcase( i==50 ); /* OUTER */
135564      testcase( i==51 ); /* RELEASE */
135565      testcase( i==52 ); /* ATTACH */
135566      testcase( i==53 ); /* HAVING */
135567      testcase( i==54 ); /* GROUP */
135568      testcase( i==55 ); /* UPDATE */
135569      testcase( i==56 ); /* BEGIN */
135570      testcase( i==57 ); /* INNER */
135571      testcase( i==58 ); /* RECURSIVE */
135572      testcase( i==59 ); /* BETWEEN */
135573      testcase( i==60 ); /* NOTNULL */
135574      testcase( i==61 ); /* NOT */
135575      testcase( i==62 ); /* NO */
135576      testcase( i==63 ); /* NULL */
135577      testcase( i==64 ); /* LIKE */
135578      testcase( i==65 ); /* CASCADE */
135579      testcase( i==66 ); /* ASC */
135580      testcase( i==67 ); /* DELETE */
135581      testcase( i==68 ); /* CASE */
135582      testcase( i==69 ); /* COLLATE */
135583      testcase( i==70 ); /* CREATE */
135584      testcase( i==71 ); /* CURRENT_DATE */
135585      testcase( i==72 ); /* DETACH */
135586      testcase( i==73 ); /* IMMEDIATE */
135587      testcase( i==74 ); /* JOIN */
135588      testcase( i==75 ); /* INSERT */
135589      testcase( i==76 ); /* MATCH */
135590      testcase( i==77 ); /* PLAN */
135591      testcase( i==78 ); /* ANALYZE */
135592      testcase( i==79 ); /* PRAGMA */
135593      testcase( i==80 ); /* ABORT */
135594      testcase( i==81 ); /* VALUES */
135595      testcase( i==82 ); /* VIRTUAL */
135596      testcase( i==83 ); /* LIMIT */
135597      testcase( i==84 ); /* WHEN */
135598      testcase( i==85 ); /* WHERE */
135599      testcase( i==86 ); /* RENAME */
135600      testcase( i==87 ); /* AFTER */
135601      testcase( i==88 ); /* REPLACE */
135602      testcase( i==89 ); /* AND */
135603      testcase( i==90 ); /* DEFAULT */
135604      testcase( i==91 ); /* AUTOINCREMENT */
135605      testcase( i==92 ); /* TO */
135606      testcase( i==93 ); /* IN */
135607      testcase( i==94 ); /* CAST */
135608      testcase( i==95 ); /* COLUMN */
135609      testcase( i==96 ); /* COMMIT */
135610      testcase( i==97 ); /* CONFLICT */
135611      testcase( i==98 ); /* CROSS */
135612      testcase( i==99 ); /* CURRENT_TIMESTAMP */
135613      testcase( i==100 ); /* CURRENT_TIME */
135614      testcase( i==101 ); /* PRIMARY */
135615      testcase( i==102 ); /* DEFERRED */
135616      testcase( i==103 ); /* DISTINCT */
135617      testcase( i==104 ); /* IS */
135618      testcase( i==105 ); /* DROP */
135619      testcase( i==106 ); /* FAIL */
135620      testcase( i==107 ); /* FROM */
135621      testcase( i==108 ); /* FULL */
135622      testcase( i==109 ); /* GLOB */
135623      testcase( i==110 ); /* BY */
135624      testcase( i==111 ); /* IF */
135625      testcase( i==112 ); /* ISNULL */
135626      testcase( i==113 ); /* ORDER */
135627      testcase( i==114 ); /* RESTRICT */
135628      testcase( i==115 ); /* RIGHT */
135629      testcase( i==116 ); /* ROLLBACK */
135630      testcase( i==117 ); /* ROW */
135631      testcase( i==118 ); /* UNION */
135632      testcase( i==119 ); /* USING */
135633      testcase( i==120 ); /* VACUUM */
135634      testcase( i==121 ); /* VIEW */
135635      testcase( i==122 ); /* INITIALLY */
135636      testcase( i==123 ); /* ALL */
135637      *pType = aCode[i];
135638      break;
135639    }
135640  }
135641  return n;
135642}
135643SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
135644  int id = TK_ID;
135645  keywordCode((char*)z, n, &id);
135646  return id;
135647}
135648#define SQLITE_N_KEYWORD 124
135649
135650/************** End of keywordhash.h *****************************************/
135651/************** Continuing where we left off in tokenize.c *******************/
135652
135653
135654/*
135655** If X is a character that can be used in an identifier then
135656** IdChar(X) will be true.  Otherwise it is false.
135657**
135658** For ASCII, any character with the high-order bit set is
135659** allowed in an identifier.  For 7-bit characters,
135660** sqlite3IsIdChar[X] must be 1.
135661**
135662** For EBCDIC, the rules are more complex but have the same
135663** end result.
135664**
135665** Ticket #1066.  the SQL standard does not allow '$' in the
135666** middle of identifiers.  But many SQL implementations do.
135667** SQLite will allow '$' in identifiers for compatibility.
135668** But the feature is undocumented.
135669*/
135670#ifdef SQLITE_ASCII
135671#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
135672#endif
135673#ifdef SQLITE_EBCDIC
135674SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
135675/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
135676    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
135677    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
135678    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
135679    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
135680    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
135681    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
135682    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
135683    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
135684    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
135685    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
135686    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
135687    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
135688};
135689#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
135690#endif
135691
135692/* Make the IdChar function accessible from ctime.c */
135693#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
135694SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
135695#endif
135696
135697
135698/*
135699** Return the length (in bytes) of the token that begins at z[0].
135700** Store the token type in *tokenType before returning.
135701*/
135702SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
135703  int i, c;
135704  switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
135705                          ** of the token. See the comment on the CC_ defines
135706                          ** above. */
135707    case CC_SPACE: {
135708      testcase( z[0]==' ' );
135709      testcase( z[0]=='\t' );
135710      testcase( z[0]=='\n' );
135711      testcase( z[0]=='\f' );
135712      testcase( z[0]=='\r' );
135713      for(i=1; sqlite3Isspace(z[i]); i++){}
135714      *tokenType = TK_SPACE;
135715      return i;
135716    }
135717    case CC_MINUS: {
135718      if( z[1]=='-' ){
135719        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
135720        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
135721        return i;
135722      }
135723      *tokenType = TK_MINUS;
135724      return 1;
135725    }
135726    case CC_LP: {
135727      *tokenType = TK_LP;
135728      return 1;
135729    }
135730    case CC_RP: {
135731      *tokenType = TK_RP;
135732      return 1;
135733    }
135734    case CC_SEMI: {
135735      *tokenType = TK_SEMI;
135736      return 1;
135737    }
135738    case CC_PLUS: {
135739      *tokenType = TK_PLUS;
135740      return 1;
135741    }
135742    case CC_STAR: {
135743      *tokenType = TK_STAR;
135744      return 1;
135745    }
135746    case CC_SLASH: {
135747      if( z[1]!='*' || z[2]==0 ){
135748        *tokenType = TK_SLASH;
135749        return 1;
135750      }
135751      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
135752      if( c ) i++;
135753      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
135754      return i;
135755    }
135756    case CC_PERCENT: {
135757      *tokenType = TK_REM;
135758      return 1;
135759    }
135760    case CC_EQ: {
135761      *tokenType = TK_EQ;
135762      return 1 + (z[1]=='=');
135763    }
135764    case CC_LT: {
135765      if( (c=z[1])=='=' ){
135766        *tokenType = TK_LE;
135767        return 2;
135768      }else if( c=='>' ){
135769        *tokenType = TK_NE;
135770        return 2;
135771      }else if( c=='<' ){
135772        *tokenType = TK_LSHIFT;
135773        return 2;
135774      }else{
135775        *tokenType = TK_LT;
135776        return 1;
135777      }
135778    }
135779    case CC_GT: {
135780      if( (c=z[1])=='=' ){
135781        *tokenType = TK_GE;
135782        return 2;
135783      }else if( c=='>' ){
135784        *tokenType = TK_RSHIFT;
135785        return 2;
135786      }else{
135787        *tokenType = TK_GT;
135788        return 1;
135789      }
135790    }
135791    case CC_BANG: {
135792      if( z[1]!='=' ){
135793        *tokenType = TK_ILLEGAL;
135794        return 1;
135795      }else{
135796        *tokenType = TK_NE;
135797        return 2;
135798      }
135799    }
135800    case CC_PIPE: {
135801      if( z[1]!='|' ){
135802        *tokenType = TK_BITOR;
135803        return 1;
135804      }else{
135805        *tokenType = TK_CONCAT;
135806        return 2;
135807      }
135808    }
135809    case CC_COMMA: {
135810      *tokenType = TK_COMMA;
135811      return 1;
135812    }
135813    case CC_AND: {
135814      *tokenType = TK_BITAND;
135815      return 1;
135816    }
135817    case CC_TILDA: {
135818      *tokenType = TK_BITNOT;
135819      return 1;
135820    }
135821    case CC_QUOTE: {
135822      int delim = z[0];
135823      testcase( delim=='`' );
135824      testcase( delim=='\'' );
135825      testcase( delim=='"' );
135826      for(i=1; (c=z[i])!=0; i++){
135827        if( c==delim ){
135828          if( z[i+1]==delim ){
135829            i++;
135830          }else{
135831            break;
135832          }
135833        }
135834      }
135835      if( c=='\'' ){
135836        *tokenType = TK_STRING;
135837        return i+1;
135838      }else if( c!=0 ){
135839        *tokenType = TK_ID;
135840        return i+1;
135841      }else{
135842        *tokenType = TK_ILLEGAL;
135843        return i;
135844      }
135845    }
135846    case CC_DOT: {
135847#ifndef SQLITE_OMIT_FLOATING_POINT
135848      if( !sqlite3Isdigit(z[1]) )
135849#endif
135850      {
135851        *tokenType = TK_DOT;
135852        return 1;
135853      }
135854      /* If the next character is a digit, this is a floating point
135855      ** number that begins with ".".  Fall thru into the next case */
135856    }
135857    case CC_DIGIT: {
135858      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
135859      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
135860      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
135861      testcase( z[0]=='9' );
135862      *tokenType = TK_INTEGER;
135863#ifndef SQLITE_OMIT_HEX_INTEGER
135864      if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
135865        for(i=3; sqlite3Isxdigit(z[i]); i++){}
135866        return i;
135867      }
135868#endif
135869      for(i=0; sqlite3Isdigit(z[i]); i++){}
135870#ifndef SQLITE_OMIT_FLOATING_POINT
135871      if( z[i]=='.' ){
135872        i++;
135873        while( sqlite3Isdigit(z[i]) ){ i++; }
135874        *tokenType = TK_FLOAT;
135875      }
135876      if( (z[i]=='e' || z[i]=='E') &&
135877           ( sqlite3Isdigit(z[i+1])
135878            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
135879           )
135880      ){
135881        i += 2;
135882        while( sqlite3Isdigit(z[i]) ){ i++; }
135883        *tokenType = TK_FLOAT;
135884      }
135885#endif
135886      while( IdChar(z[i]) ){
135887        *tokenType = TK_ILLEGAL;
135888        i++;
135889      }
135890      return i;
135891    }
135892    case CC_QUOTE2: {
135893      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
135894      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
135895      return i;
135896    }
135897    case CC_VARNUM: {
135898      *tokenType = TK_VARIABLE;
135899      for(i=1; sqlite3Isdigit(z[i]); i++){}
135900      return i;
135901    }
135902    case CC_DOLLAR:
135903    case CC_VARALPHA: {
135904      int n = 0;
135905      testcase( z[0]=='$' );  testcase( z[0]=='@' );
135906      testcase( z[0]==':' );  testcase( z[0]=='#' );
135907      *tokenType = TK_VARIABLE;
135908      for(i=1; (c=z[i])!=0; i++){
135909        if( IdChar(c) ){
135910          n++;
135911#ifndef SQLITE_OMIT_TCL_VARIABLE
135912        }else if( c=='(' && n>0 ){
135913          do{
135914            i++;
135915          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
135916          if( c==')' ){
135917            i++;
135918          }else{
135919            *tokenType = TK_ILLEGAL;
135920          }
135921          break;
135922        }else if( c==':' && z[i+1]==':' ){
135923          i++;
135924#endif
135925        }else{
135926          break;
135927        }
135928      }
135929      if( n==0 ) *tokenType = TK_ILLEGAL;
135930      return i;
135931    }
135932    case CC_KYWD: {
135933      for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
135934      if( IdChar(z[i]) ){
135935        /* This token started out using characters that can appear in keywords,
135936        ** but z[i] is a character not allowed within keywords, so this must
135937        ** be an identifier instead */
135938        i++;
135939        break;
135940      }
135941      *tokenType = TK_ID;
135942      return keywordCode((char*)z, i, tokenType);
135943    }
135944    case CC_X: {
135945#ifndef SQLITE_OMIT_BLOB_LITERAL
135946      testcase( z[0]=='x' ); testcase( z[0]=='X' );
135947      if( z[1]=='\'' ){
135948        *tokenType = TK_BLOB;
135949        for(i=2; sqlite3Isxdigit(z[i]); i++){}
135950        if( z[i]!='\'' || i%2 ){
135951          *tokenType = TK_ILLEGAL;
135952          while( z[i] && z[i]!='\'' ){ i++; }
135953        }
135954        if( z[i] ) i++;
135955        return i;
135956      }
135957#endif
135958      /* If it is not a BLOB literal, then it must be an ID, since no
135959      ** SQL keywords start with the letter 'x'.  Fall through */
135960    }
135961    case CC_ID: {
135962      i = 1;
135963      break;
135964    }
135965    default: {
135966      *tokenType = TK_ILLEGAL;
135967      return 1;
135968    }
135969  }
135970  while( IdChar(z[i]) ){ i++; }
135971  *tokenType = TK_ID;
135972  return i;
135973}
135974
135975/*
135976** Run the parser on the given SQL string.  The parser structure is
135977** passed in.  An SQLITE_ status code is returned.  If an error occurs
135978** then an and attempt is made to write an error message into
135979** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
135980** error message.
135981*/
135982SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
135983  int nErr = 0;                   /* Number of errors encountered */
135984  int i;                          /* Loop counter */
135985  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
135986  int tokenType;                  /* type of the next token */
135987  int lastTokenParsed = -1;       /* type of the previous token */
135988  sqlite3 *db = pParse->db;       /* The database connection */
135989  int mxSqlLen;                   /* Max length of an SQL string */
135990
135991  assert( zSql!=0 );
135992  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
135993  if( db->nVdbeActive==0 ){
135994    db->u1.isInterrupted = 0;
135995  }
135996  pParse->rc = SQLITE_OK;
135997  pParse->zTail = zSql;
135998  i = 0;
135999  assert( pzErrMsg!=0 );
136000  /* sqlite3ParserTrace(stdout, "parser: "); */
136001  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
136002  if( pEngine==0 ){
136003    sqlite3OomFault(db);
136004    return SQLITE_NOMEM_BKPT;
136005  }
136006  assert( pParse->pNewTable==0 );
136007  assert( pParse->pNewTrigger==0 );
136008  assert( pParse->nVar==0 );
136009  assert( pParse->nzVar==0 );
136010  assert( pParse->azVar==0 );
136011  while( zSql[i]!=0 ){
136012    assert( i>=0 );
136013    pParse->sLastToken.z = &zSql[i];
136014    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
136015    i += pParse->sLastToken.n;
136016    if( i>mxSqlLen ){
136017      pParse->rc = SQLITE_TOOBIG;
136018      break;
136019    }
136020    if( tokenType>=TK_SPACE ){
136021      assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
136022      if( db->u1.isInterrupted ){
136023        pParse->rc = SQLITE_INTERRUPT;
136024        break;
136025      }
136026      if( tokenType==TK_ILLEGAL ){
136027        sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
136028                        &pParse->sLastToken);
136029        break;
136030      }
136031    }else{
136032      sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
136033      lastTokenParsed = tokenType;
136034      if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
136035    }
136036  }
136037  assert( nErr==0 );
136038  pParse->zTail = &zSql[i];
136039  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
136040    assert( zSql[i]==0 );
136041    if( lastTokenParsed!=TK_SEMI ){
136042      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
136043    }
136044    if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
136045      sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
136046    }
136047  }
136048#ifdef YYTRACKMAXSTACKDEPTH
136049  sqlite3_mutex_enter(sqlite3MallocMutex());
136050  sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
136051      sqlite3ParserStackPeak(pEngine)
136052  );
136053  sqlite3_mutex_leave(sqlite3MallocMutex());
136054#endif /* YYDEBUG */
136055  sqlite3ParserFree(pEngine, sqlite3_free);
136056  if( db->mallocFailed ){
136057    pParse->rc = SQLITE_NOMEM_BKPT;
136058  }
136059  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
136060    pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
136061  }
136062  assert( pzErrMsg!=0 );
136063  if( pParse->zErrMsg ){
136064    *pzErrMsg = pParse->zErrMsg;
136065    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
136066    pParse->zErrMsg = 0;
136067    nErr++;
136068  }
136069  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
136070    sqlite3VdbeDelete(pParse->pVdbe);
136071    pParse->pVdbe = 0;
136072  }
136073#ifndef SQLITE_OMIT_SHARED_CACHE
136074  if( pParse->nested==0 ){
136075    sqlite3DbFree(db, pParse->aTableLock);
136076    pParse->aTableLock = 0;
136077    pParse->nTableLock = 0;
136078  }
136079#endif
136080#ifndef SQLITE_OMIT_VIRTUALTABLE
136081  sqlite3_free(pParse->apVtabLock);
136082#endif
136083
136084  if( !IN_DECLARE_VTAB ){
136085    /* If the pParse->declareVtab flag is set, do not delete any table
136086    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
136087    ** will take responsibility for freeing the Table structure.
136088    */
136089    sqlite3DeleteTable(db, pParse->pNewTable);
136090  }
136091
136092  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
136093  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
136094  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
136095  sqlite3DbFree(db, pParse->azVar);
136096  while( pParse->pAinc ){
136097    AutoincInfo *p = pParse->pAinc;
136098    pParse->pAinc = p->pNext;
136099    sqlite3DbFree(db, p);
136100  }
136101  while( pParse->pZombieTab ){
136102    Table *p = pParse->pZombieTab;
136103    pParse->pZombieTab = p->pNextZombie;
136104    sqlite3DeleteTable(db, p);
136105  }
136106  assert( nErr==0 || pParse->rc!=SQLITE_OK );
136107  return nErr;
136108}
136109
136110/************** End of tokenize.c ********************************************/
136111/************** Begin file complete.c ****************************************/
136112/*
136113** 2001 September 15
136114**
136115** The author disclaims copyright to this source code.  In place of
136116** a legal notice, here is a blessing:
136117**
136118**    May you do good and not evil.
136119**    May you find forgiveness for yourself and forgive others.
136120**    May you share freely, never taking more than you give.
136121**
136122*************************************************************************
136123** An tokenizer for SQL
136124**
136125** This file contains C code that implements the sqlite3_complete() API.
136126** This code used to be part of the tokenizer.c source file.  But by
136127** separating it out, the code will be automatically omitted from
136128** static links that do not use it.
136129*/
136130/* #include "sqliteInt.h" */
136131#ifndef SQLITE_OMIT_COMPLETE
136132
136133/*
136134** This is defined in tokenize.c.  We just have to import the definition.
136135*/
136136#ifndef SQLITE_AMALGAMATION
136137#ifdef SQLITE_ASCII
136138#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
136139#endif
136140#ifdef SQLITE_EBCDIC
136141SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
136142#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
136143#endif
136144#endif /* SQLITE_AMALGAMATION */
136145
136146
136147/*
136148** Token types used by the sqlite3_complete() routine.  See the header
136149** comments on that procedure for additional information.
136150*/
136151#define tkSEMI    0
136152#define tkWS      1
136153#define tkOTHER   2
136154#ifndef SQLITE_OMIT_TRIGGER
136155#define tkEXPLAIN 3
136156#define tkCREATE  4
136157#define tkTEMP    5
136158#define tkTRIGGER 6
136159#define tkEND     7
136160#endif
136161
136162/*
136163** Return TRUE if the given SQL string ends in a semicolon.
136164**
136165** Special handling is require for CREATE TRIGGER statements.
136166** Whenever the CREATE TRIGGER keywords are seen, the statement
136167** must end with ";END;".
136168**
136169** This implementation uses a state machine with 8 states:
136170**
136171**   (0) INVALID   We have not yet seen a non-whitespace character.
136172**
136173**   (1) START     At the beginning or end of an SQL statement.  This routine
136174**                 returns 1 if it ends in the START state and 0 if it ends
136175**                 in any other state.
136176**
136177**   (2) NORMAL    We are in the middle of statement which ends with a single
136178**                 semicolon.
136179**
136180**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
136181**                 a statement.
136182**
136183**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
136184**                 statement, possibly preceded by EXPLAIN and/or followed by
136185**                 TEMP or TEMPORARY
136186**
136187**   (5) TRIGGER   We are in the middle of a trigger definition that must be
136188**                 ended by a semicolon, the keyword END, and another semicolon.
136189**
136190**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
136191**                 the end of a trigger definition.
136192**
136193**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
136194**                 of a trigger definition.
136195**
136196** Transitions between states above are determined by tokens extracted
136197** from the input.  The following tokens are significant:
136198**
136199**   (0) tkSEMI      A semicolon.
136200**   (1) tkWS        Whitespace.
136201**   (2) tkOTHER     Any other SQL token.
136202**   (3) tkEXPLAIN   The "explain" keyword.
136203**   (4) tkCREATE    The "create" keyword.
136204**   (5) tkTEMP      The "temp" or "temporary" keyword.
136205**   (6) tkTRIGGER   The "trigger" keyword.
136206**   (7) tkEND       The "end" keyword.
136207**
136208** Whitespace never causes a state transition and is always ignored.
136209** This means that a SQL string of all whitespace is invalid.
136210**
136211** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
136212** to recognize the end of a trigger can be omitted.  All we have to do
136213** is look for a semicolon that is not part of an string or comment.
136214*/
136215SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
136216  u8 state = 0;   /* Current state, using numbers defined in header comment */
136217  u8 token;       /* Value of the next token */
136218
136219#ifndef SQLITE_OMIT_TRIGGER
136220  /* A complex statement machine used to detect the end of a CREATE TRIGGER
136221  ** statement.  This is the normal case.
136222  */
136223  static const u8 trans[8][8] = {
136224                     /* Token:                                                */
136225     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
136226     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
136227     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
136228     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
136229     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
136230     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
136231     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
136232     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
136233     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
136234  };
136235#else
136236  /* If triggers are not supported by this compile then the statement machine
136237  ** used to detect the end of a statement is much simpler
136238  */
136239  static const u8 trans[3][3] = {
136240                     /* Token:           */
136241     /* State:       **  SEMI  WS  OTHER */
136242     /* 0 INVALID: */ {    1,  0,     2, },
136243     /* 1   START: */ {    1,  1,     2, },
136244     /* 2  NORMAL: */ {    1,  2,     2, },
136245  };
136246#endif /* SQLITE_OMIT_TRIGGER */
136247
136248#ifdef SQLITE_ENABLE_API_ARMOR
136249  if( zSql==0 ){
136250    (void)SQLITE_MISUSE_BKPT;
136251    return 0;
136252  }
136253#endif
136254
136255  while( *zSql ){
136256    switch( *zSql ){
136257      case ';': {  /* A semicolon */
136258        token = tkSEMI;
136259        break;
136260      }
136261      case ' ':
136262      case '\r':
136263      case '\t':
136264      case '\n':
136265      case '\f': {  /* White space is ignored */
136266        token = tkWS;
136267        break;
136268      }
136269      case '/': {   /* C-style comments */
136270        if( zSql[1]!='*' ){
136271          token = tkOTHER;
136272          break;
136273        }
136274        zSql += 2;
136275        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
136276        if( zSql[0]==0 ) return 0;
136277        zSql++;
136278        token = tkWS;
136279        break;
136280      }
136281      case '-': {   /* SQL-style comments from "--" to end of line */
136282        if( zSql[1]!='-' ){
136283          token = tkOTHER;
136284          break;
136285        }
136286        while( *zSql && *zSql!='\n' ){ zSql++; }
136287        if( *zSql==0 ) return state==1;
136288        token = tkWS;
136289        break;
136290      }
136291      case '[': {   /* Microsoft-style identifiers in [...] */
136292        zSql++;
136293        while( *zSql && *zSql!=']' ){ zSql++; }
136294        if( *zSql==0 ) return 0;
136295        token = tkOTHER;
136296        break;
136297      }
136298      case '`':     /* Grave-accent quoted symbols used by MySQL */
136299      case '"':     /* single- and double-quoted strings */
136300      case '\'': {
136301        int c = *zSql;
136302        zSql++;
136303        while( *zSql && *zSql!=c ){ zSql++; }
136304        if( *zSql==0 ) return 0;
136305        token = tkOTHER;
136306        break;
136307      }
136308      default: {
136309#ifdef SQLITE_EBCDIC
136310        unsigned char c;
136311#endif
136312        if( IdChar((u8)*zSql) ){
136313          /* Keywords and unquoted identifiers */
136314          int nId;
136315          for(nId=1; IdChar(zSql[nId]); nId++){}
136316#ifdef SQLITE_OMIT_TRIGGER
136317          token = tkOTHER;
136318#else
136319          switch( *zSql ){
136320            case 'c': case 'C': {
136321              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
136322                token = tkCREATE;
136323              }else{
136324                token = tkOTHER;
136325              }
136326              break;
136327            }
136328            case 't': case 'T': {
136329              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
136330                token = tkTRIGGER;
136331              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
136332                token = tkTEMP;
136333              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
136334                token = tkTEMP;
136335              }else{
136336                token = tkOTHER;
136337              }
136338              break;
136339            }
136340            case 'e':  case 'E': {
136341              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
136342                token = tkEND;
136343              }else
136344#ifndef SQLITE_OMIT_EXPLAIN
136345              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
136346                token = tkEXPLAIN;
136347              }else
136348#endif
136349              {
136350                token = tkOTHER;
136351              }
136352              break;
136353            }
136354            default: {
136355              token = tkOTHER;
136356              break;
136357            }
136358          }
136359#endif /* SQLITE_OMIT_TRIGGER */
136360          zSql += nId-1;
136361        }else{
136362          /* Operators and special symbols */
136363          token = tkOTHER;
136364        }
136365        break;
136366      }
136367    }
136368    state = trans[state][token];
136369    zSql++;
136370  }
136371  return state==1;
136372}
136373
136374#ifndef SQLITE_OMIT_UTF16
136375/*
136376** This routine is the same as the sqlite3_complete() routine described
136377** above, except that the parameter is required to be UTF-16 encoded, not
136378** UTF-8.
136379*/
136380SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
136381  sqlite3_value *pVal;
136382  char const *zSql8;
136383  int rc;
136384
136385#ifndef SQLITE_OMIT_AUTOINIT
136386  rc = sqlite3_initialize();
136387  if( rc ) return rc;
136388#endif
136389  pVal = sqlite3ValueNew(0);
136390  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
136391  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
136392  if( zSql8 ){
136393    rc = sqlite3_complete(zSql8);
136394  }else{
136395    rc = SQLITE_NOMEM_BKPT;
136396  }
136397  sqlite3ValueFree(pVal);
136398  return rc & 0xff;
136399}
136400#endif /* SQLITE_OMIT_UTF16 */
136401#endif /* SQLITE_OMIT_COMPLETE */
136402
136403/************** End of complete.c ********************************************/
136404/************** Begin file main.c ********************************************/
136405/*
136406** 2001 September 15
136407**
136408** The author disclaims copyright to this source code.  In place of
136409** a legal notice, here is a blessing:
136410**
136411**    May you do good and not evil.
136412**    May you find forgiveness for yourself and forgive others.
136413**    May you share freely, never taking more than you give.
136414**
136415*************************************************************************
136416** Main file for the SQLite library.  The routines in this file
136417** implement the programmer interface to the library.  Routines in
136418** other files are for internal use by SQLite and should not be
136419** accessed by users of the library.
136420*/
136421/* #include "sqliteInt.h" */
136422
136423#ifdef SQLITE_ENABLE_FTS3
136424/************** Include fts3.h in the middle of main.c ***********************/
136425/************** Begin file fts3.h ********************************************/
136426/*
136427** 2006 Oct 10
136428**
136429** The author disclaims copyright to this source code.  In place of
136430** a legal notice, here is a blessing:
136431**
136432**    May you do good and not evil.
136433**    May you find forgiveness for yourself and forgive others.
136434**    May you share freely, never taking more than you give.
136435**
136436******************************************************************************
136437**
136438** This header file is used by programs that want to link against the
136439** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
136440*/
136441/* #include "sqlite3.h" */
136442
136443#if 0
136444extern "C" {
136445#endif  /* __cplusplus */
136446
136447SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
136448
136449#if 0
136450}  /* extern "C" */
136451#endif  /* __cplusplus */
136452
136453/************** End of fts3.h ************************************************/
136454/************** Continuing where we left off in main.c ***********************/
136455#endif
136456#ifdef SQLITE_ENABLE_RTREE
136457/************** Include rtree.h in the middle of main.c **********************/
136458/************** Begin file rtree.h *******************************************/
136459/*
136460** 2008 May 26
136461**
136462** The author disclaims copyright to this source code.  In place of
136463** a legal notice, here is a blessing:
136464**
136465**    May you do good and not evil.
136466**    May you find forgiveness for yourself and forgive others.
136467**    May you share freely, never taking more than you give.
136468**
136469******************************************************************************
136470**
136471** This header file is used by programs that want to link against the
136472** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
136473*/
136474/* #include "sqlite3.h" */
136475
136476#if 0
136477extern "C" {
136478#endif  /* __cplusplus */
136479
136480SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
136481
136482#if 0
136483}  /* extern "C" */
136484#endif  /* __cplusplus */
136485
136486/************** End of rtree.h ***********************************************/
136487/************** Continuing where we left off in main.c ***********************/
136488#endif
136489#ifdef SQLITE_ENABLE_ICU
136490/************** Include sqliteicu.h in the middle of main.c ******************/
136491/************** Begin file sqliteicu.h ***************************************/
136492/*
136493** 2008 May 26
136494**
136495** The author disclaims copyright to this source code.  In place of
136496** a legal notice, here is a blessing:
136497**
136498**    May you do good and not evil.
136499**    May you find forgiveness for yourself and forgive others.
136500**    May you share freely, never taking more than you give.
136501**
136502******************************************************************************
136503**
136504** This header file is used by programs that want to link against the
136505** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
136506*/
136507/* #include "sqlite3.h" */
136508
136509#if 0
136510extern "C" {
136511#endif  /* __cplusplus */
136512
136513SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
136514
136515#if 0
136516}  /* extern "C" */
136517#endif  /* __cplusplus */
136518
136519
136520/************** End of sqliteicu.h *******************************************/
136521/************** Continuing where we left off in main.c ***********************/
136522#endif
136523#ifdef SQLITE_ENABLE_JSON1
136524SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
136525#endif
136526#ifdef SQLITE_ENABLE_FTS5
136527SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
136528#endif
136529
136530#ifndef SQLITE_AMALGAMATION
136531/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
136532** contains the text of SQLITE_VERSION macro.
136533*/
136534SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
136535#endif
136536
136537/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
136538** a pointer to the to the sqlite3_version[] string constant.
136539*/
136540SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
136541
136542/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
136543** pointer to a string constant whose value is the same as the
136544** SQLITE_SOURCE_ID C preprocessor macro.
136545*/
136546SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
136547
136548/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
136549** returns an integer equal to SQLITE_VERSION_NUMBER.
136550*/
136551SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
136552
136553/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
136554** zero if and only if SQLite was compiled with mutexing code omitted due to
136555** the SQLITE_THREADSAFE compile-time option being set to 0.
136556*/
136557SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
136558
136559/*
136560** When compiling the test fixture or with debugging enabled (on Win32),
136561** this variable being set to non-zero will cause OSTRACE macros to emit
136562** extra diagnostic information.
136563*/
136564#ifdef SQLITE_HAVE_OS_TRACE
136565# ifndef SQLITE_DEBUG_OS_TRACE
136566#   define SQLITE_DEBUG_OS_TRACE 0
136567# endif
136568  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
136569#endif
136570
136571#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
136572/*
136573** If the following function pointer is not NULL and if
136574** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
136575** I/O active are written using this function.  These messages
136576** are intended for debugging activity only.
136577*/
136578SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
136579#endif
136580
136581/*
136582** If the following global variable points to a string which is the
136583** name of a directory, then that directory will be used to store
136584** temporary files.
136585**
136586** See also the "PRAGMA temp_store_directory" SQL command.
136587*/
136588SQLITE_API char *sqlite3_temp_directory = 0;
136589
136590/*
136591** If the following global variable points to a string which is the
136592** name of a directory, then that directory will be used to store
136593** all database files specified with a relative pathname.
136594**
136595** See also the "PRAGMA data_store_directory" SQL command.
136596*/
136597SQLITE_API char *sqlite3_data_directory = 0;
136598
136599/*
136600** Initialize SQLite.
136601**
136602** This routine must be called to initialize the memory allocation,
136603** VFS, and mutex subsystems prior to doing any serious work with
136604** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
136605** this routine will be called automatically by key routines such as
136606** sqlite3_open().
136607**
136608** This routine is a no-op except on its very first call for the process,
136609** or for the first call after a call to sqlite3_shutdown.
136610**
136611** The first thread to call this routine runs the initialization to
136612** completion.  If subsequent threads call this routine before the first
136613** thread has finished the initialization process, then the subsequent
136614** threads must block until the first thread finishes with the initialization.
136615**
136616** The first thread might call this routine recursively.  Recursive
136617** calls to this routine should not block, of course.  Otherwise the
136618** initialization process would never complete.
136619**
136620** Let X be the first thread to enter this routine.  Let Y be some other
136621** thread.  Then while the initial invocation of this routine by X is
136622** incomplete, it is required that:
136623**
136624**    *  Calls to this routine from Y must block until the outer-most
136625**       call by X completes.
136626**
136627**    *  Recursive calls to this routine from thread X return immediately
136628**       without blocking.
136629*/
136630SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
136631  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
136632  int rc;                                      /* Result code */
136633#ifdef SQLITE_EXTRA_INIT
136634  int bRunExtraInit = 0;                       /* Extra initialization needed */
136635#endif
136636
136637#ifdef SQLITE_OMIT_WSD
136638  rc = sqlite3_wsd_init(4096, 24);
136639  if( rc!=SQLITE_OK ){
136640    return rc;
136641  }
136642#endif
136643
136644  /* If the following assert() fails on some obscure processor/compiler
136645  ** combination, the work-around is to set the correct pointer
136646  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
136647  assert( SQLITE_PTRSIZE==sizeof(char*) );
136648
136649  /* If SQLite is already completely initialized, then this call
136650  ** to sqlite3_initialize() should be a no-op.  But the initialization
136651  ** must be complete.  So isInit must not be set until the very end
136652  ** of this routine.
136653  */
136654  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
136655
136656  /* Make sure the mutex subsystem is initialized.  If unable to
136657  ** initialize the mutex subsystem, return early with the error.
136658  ** If the system is so sick that we are unable to allocate a mutex,
136659  ** there is not much SQLite is going to be able to do.
136660  **
136661  ** The mutex subsystem must take care of serializing its own
136662  ** initialization.
136663  */
136664  rc = sqlite3MutexInit();
136665  if( rc ) return rc;
136666
136667  /* Initialize the malloc() system and the recursive pInitMutex mutex.
136668  ** This operation is protected by the STATIC_MASTER mutex.  Note that
136669  ** MutexAlloc() is called for a static mutex prior to initializing the
136670  ** malloc subsystem - this implies that the allocation of a static
136671  ** mutex must not require support from the malloc subsystem.
136672  */
136673  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
136674  sqlite3_mutex_enter(pMaster);
136675  sqlite3GlobalConfig.isMutexInit = 1;
136676  if( !sqlite3GlobalConfig.isMallocInit ){
136677    rc = sqlite3MallocInit();
136678  }
136679  if( rc==SQLITE_OK ){
136680    sqlite3GlobalConfig.isMallocInit = 1;
136681    if( !sqlite3GlobalConfig.pInitMutex ){
136682      sqlite3GlobalConfig.pInitMutex =
136683           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
136684      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
136685        rc = SQLITE_NOMEM_BKPT;
136686      }
136687    }
136688  }
136689  if( rc==SQLITE_OK ){
136690    sqlite3GlobalConfig.nRefInitMutex++;
136691  }
136692  sqlite3_mutex_leave(pMaster);
136693
136694  /* If rc is not SQLITE_OK at this point, then either the malloc
136695  ** subsystem could not be initialized or the system failed to allocate
136696  ** the pInitMutex mutex. Return an error in either case.  */
136697  if( rc!=SQLITE_OK ){
136698    return rc;
136699  }
136700
136701  /* Do the rest of the initialization under the recursive mutex so
136702  ** that we will be able to handle recursive calls into
136703  ** sqlite3_initialize().  The recursive calls normally come through
136704  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
136705  ** recursive calls might also be possible.
136706  **
136707  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
136708  ** to the xInit method, so the xInit method need not be threadsafe.
136709  **
136710  ** The following mutex is what serializes access to the appdef pcache xInit
136711  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
136712  ** call to sqlite3PcacheInitialize().
136713  */
136714  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
136715  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
136716    sqlite3GlobalConfig.inProgress = 1;
136717#ifdef SQLITE_ENABLE_SQLLOG
136718    {
136719      extern void sqlite3_init_sqllog(void);
136720      sqlite3_init_sqllog();
136721    }
136722#endif
136723    memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
136724    sqlite3RegisterBuiltinFunctions();
136725    if( sqlite3GlobalConfig.isPCacheInit==0 ){
136726      rc = sqlite3PcacheInitialize();
136727    }
136728    if( rc==SQLITE_OK ){
136729      sqlite3GlobalConfig.isPCacheInit = 1;
136730      rc = sqlite3OsInit();
136731    }
136732    if( rc==SQLITE_OK ){
136733      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
136734          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
136735      sqlite3GlobalConfig.isInit = 1;
136736#ifdef SQLITE_EXTRA_INIT
136737      bRunExtraInit = 1;
136738#endif
136739    }
136740    sqlite3GlobalConfig.inProgress = 0;
136741  }
136742  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
136743
136744  /* Go back under the static mutex and clean up the recursive
136745  ** mutex to prevent a resource leak.
136746  */
136747  sqlite3_mutex_enter(pMaster);
136748  sqlite3GlobalConfig.nRefInitMutex--;
136749  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
136750    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
136751    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
136752    sqlite3GlobalConfig.pInitMutex = 0;
136753  }
136754  sqlite3_mutex_leave(pMaster);
136755
136756  /* The following is just a sanity check to make sure SQLite has
136757  ** been compiled correctly.  It is important to run this code, but
136758  ** we don't want to run it too often and soak up CPU cycles for no
136759  ** reason.  So we run it once during initialization.
136760  */
136761#ifndef NDEBUG
136762#ifndef SQLITE_OMIT_FLOATING_POINT
136763  /* This section of code's only "output" is via assert() statements. */
136764  if ( rc==SQLITE_OK ){
136765    u64 x = (((u64)1)<<63)-1;
136766    double y;
136767    assert(sizeof(x)==8);
136768    assert(sizeof(x)==sizeof(y));
136769    memcpy(&y, &x, 8);
136770    assert( sqlite3IsNaN(y) );
136771  }
136772#endif
136773#endif
136774
136775  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
136776  ** compile-time option.
136777  */
136778#ifdef SQLITE_EXTRA_INIT
136779  if( bRunExtraInit ){
136780    int SQLITE_EXTRA_INIT(const char*);
136781    rc = SQLITE_EXTRA_INIT(0);
136782  }
136783#endif
136784
136785  return rc;
136786}
136787
136788/*
136789** Undo the effects of sqlite3_initialize().  Must not be called while
136790** there are outstanding database connections or memory allocations or
136791** while any part of SQLite is otherwise in use in any thread.  This
136792** routine is not threadsafe.  But it is safe to invoke this routine
136793** on when SQLite is already shut down.  If SQLite is already shut down
136794** when this routine is invoked, then this routine is a harmless no-op.
136795*/
136796SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
136797#ifdef SQLITE_OMIT_WSD
136798  int rc = sqlite3_wsd_init(4096, 24);
136799  if( rc!=SQLITE_OK ){
136800    return rc;
136801  }
136802#endif
136803
136804  if( sqlite3GlobalConfig.isInit ){
136805#ifdef SQLITE_EXTRA_SHUTDOWN
136806    void SQLITE_EXTRA_SHUTDOWN(void);
136807    SQLITE_EXTRA_SHUTDOWN();
136808#endif
136809    sqlite3_os_end();
136810    sqlite3_reset_auto_extension();
136811    sqlite3GlobalConfig.isInit = 0;
136812  }
136813  if( sqlite3GlobalConfig.isPCacheInit ){
136814    sqlite3PcacheShutdown();
136815    sqlite3GlobalConfig.isPCacheInit = 0;
136816  }
136817  if( sqlite3GlobalConfig.isMallocInit ){
136818    sqlite3MallocEnd();
136819    sqlite3GlobalConfig.isMallocInit = 0;
136820
136821#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
136822    /* The heap subsystem has now been shutdown and these values are supposed
136823    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
136824    ** which would rely on that heap subsystem; therefore, make sure these
136825    ** values cannot refer to heap memory that was just invalidated when the
136826    ** heap subsystem was shutdown.  This is only done if the current call to
136827    ** this function resulted in the heap subsystem actually being shutdown.
136828    */
136829    sqlite3_data_directory = 0;
136830    sqlite3_temp_directory = 0;
136831#endif
136832  }
136833  if( sqlite3GlobalConfig.isMutexInit ){
136834    sqlite3MutexEnd();
136835    sqlite3GlobalConfig.isMutexInit = 0;
136836  }
136837
136838  return SQLITE_OK;
136839}
136840
136841/*
136842** This API allows applications to modify the global configuration of
136843** the SQLite library at run-time.
136844**
136845** This routine should only be called when there are no outstanding
136846** database connections or memory allocations.  This routine is not
136847** threadsafe.  Failure to heed these warnings can lead to unpredictable
136848** behavior.
136849*/
136850SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
136851  va_list ap;
136852  int rc = SQLITE_OK;
136853
136854  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
136855  ** the SQLite library is in use. */
136856  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
136857
136858  va_start(ap, op);
136859  switch( op ){
136860
136861    /* Mutex configuration options are only available in a threadsafe
136862    ** compile.
136863    */
136864#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
136865    case SQLITE_CONFIG_SINGLETHREAD: {
136866      /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
136867      ** Single-thread. */
136868      sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
136869      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
136870      break;
136871    }
136872#endif
136873#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
136874    case SQLITE_CONFIG_MULTITHREAD: {
136875      /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
136876      ** Multi-thread. */
136877      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
136878      sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
136879      break;
136880    }
136881#endif
136882#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
136883    case SQLITE_CONFIG_SERIALIZED: {
136884      /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
136885      ** Serialized. */
136886      sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
136887      sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
136888      break;
136889    }
136890#endif
136891#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
136892    case SQLITE_CONFIG_MUTEX: {
136893      /* Specify an alternative mutex implementation */
136894      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
136895      break;
136896    }
136897#endif
136898#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
136899    case SQLITE_CONFIG_GETMUTEX: {
136900      /* Retrieve the current mutex implementation */
136901      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
136902      break;
136903    }
136904#endif
136905
136906    case SQLITE_CONFIG_MALLOC: {
136907      /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
136908      ** single argument which is a pointer to an instance of the
136909      ** sqlite3_mem_methods structure. The argument specifies alternative
136910      ** low-level memory allocation routines to be used in place of the memory
136911      ** allocation routines built into SQLite. */
136912      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
136913      break;
136914    }
136915    case SQLITE_CONFIG_GETMALLOC: {
136916      /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
136917      ** single argument which is a pointer to an instance of the
136918      ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
136919      ** filled with the currently defined memory allocation routines. */
136920      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
136921      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
136922      break;
136923    }
136924    case SQLITE_CONFIG_MEMSTATUS: {
136925      /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
136926      ** single argument of type int, interpreted as a boolean, which enables
136927      ** or disables the collection of memory allocation statistics. */
136928      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
136929      break;
136930    }
136931    case SQLITE_CONFIG_SCRATCH: {
136932      /* EVIDENCE-OF: R-08404-60887 There are three arguments to
136933      ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
136934      ** which the scratch allocations will be drawn, the size of each scratch
136935      ** allocation (sz), and the maximum number of scratch allocations (N). */
136936      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
136937      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
136938      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
136939      break;
136940    }
136941    case SQLITE_CONFIG_PAGECACHE: {
136942      /* EVIDENCE-OF: R-18761-36601 There are three arguments to
136943      ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
136944      ** the size of each page cache line (sz), and the number of cache lines
136945      ** (N). */
136946      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
136947      sqlite3GlobalConfig.szPage = va_arg(ap, int);
136948      sqlite3GlobalConfig.nPage = va_arg(ap, int);
136949      break;
136950    }
136951    case SQLITE_CONFIG_PCACHE_HDRSZ: {
136952      /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
136953      ** a single parameter which is a pointer to an integer and writes into
136954      ** that integer the number of extra bytes per page required for each page
136955      ** in SQLITE_CONFIG_PAGECACHE. */
136956      *va_arg(ap, int*) =
136957          sqlite3HeaderSizeBtree() +
136958          sqlite3HeaderSizePcache() +
136959          sqlite3HeaderSizePcache1();
136960      break;
136961    }
136962
136963    case SQLITE_CONFIG_PCACHE: {
136964      /* no-op */
136965      break;
136966    }
136967    case SQLITE_CONFIG_GETPCACHE: {
136968      /* now an error */
136969      rc = SQLITE_ERROR;
136970      break;
136971    }
136972
136973    case SQLITE_CONFIG_PCACHE2: {
136974      /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
136975      ** single argument which is a pointer to an sqlite3_pcache_methods2
136976      ** object. This object specifies the interface to a custom page cache
136977      ** implementation. */
136978      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
136979      break;
136980    }
136981    case SQLITE_CONFIG_GETPCACHE2: {
136982      /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
136983      ** single argument which is a pointer to an sqlite3_pcache_methods2
136984      ** object. SQLite copies of the current page cache implementation into
136985      ** that object. */
136986      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
136987        sqlite3PCacheSetDefault();
136988      }
136989      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
136990      break;
136991    }
136992
136993/* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
136994** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
136995** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
136996#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
136997    case SQLITE_CONFIG_HEAP: {
136998      /* EVIDENCE-OF: R-19854-42126 There are three arguments to
136999      ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
137000      ** number of bytes in the memory buffer, and the minimum allocation size.
137001      */
137002      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
137003      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
137004      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
137005
137006      if( sqlite3GlobalConfig.mnReq<1 ){
137007        sqlite3GlobalConfig.mnReq = 1;
137008      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
137009        /* cap min request size at 2^12 */
137010        sqlite3GlobalConfig.mnReq = (1<<12);
137011      }
137012
137013      if( sqlite3GlobalConfig.pHeap==0 ){
137014        /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
137015        ** is NULL, then SQLite reverts to using its default memory allocator
137016        ** (the system malloc() implementation), undoing any prior invocation of
137017        ** SQLITE_CONFIG_MALLOC.
137018        **
137019        ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
137020        ** revert to its default implementation when sqlite3_initialize() is run
137021        */
137022        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
137023      }else{
137024        /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
137025        ** alternative memory allocator is engaged to handle all of SQLites
137026        ** memory allocation needs. */
137027#ifdef SQLITE_ENABLE_MEMSYS3
137028        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
137029#endif
137030#ifdef SQLITE_ENABLE_MEMSYS5
137031        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
137032#endif
137033      }
137034      break;
137035    }
137036#endif
137037
137038    case SQLITE_CONFIG_LOOKASIDE: {
137039      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
137040      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
137041      break;
137042    }
137043
137044    /* Record a pointer to the logger function and its first argument.
137045    ** The default is NULL.  Logging is disabled if the function pointer is
137046    ** NULL.
137047    */
137048    case SQLITE_CONFIG_LOG: {
137049      /* MSVC is picky about pulling func ptrs from va lists.
137050      ** http://support.microsoft.com/kb/47961
137051      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
137052      */
137053      typedef void(*LOGFUNC_t)(void*,int,const char*);
137054      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
137055      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
137056      break;
137057    }
137058
137059    /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
137060    ** can be changed at start-time using the
137061    ** sqlite3_config(SQLITE_CONFIG_URI,1) or
137062    ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
137063    */
137064    case SQLITE_CONFIG_URI: {
137065      /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
137066      ** argument of type int. If non-zero, then URI handling is globally
137067      ** enabled. If the parameter is zero, then URI handling is globally
137068      ** disabled. */
137069      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
137070      break;
137071    }
137072
137073    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
137074      /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
137075      ** option takes a single integer argument which is interpreted as a
137076      ** boolean in order to enable or disable the use of covering indices for
137077      ** full table scans in the query optimizer. */
137078      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
137079      break;
137080    }
137081
137082#ifdef SQLITE_ENABLE_SQLLOG
137083    case SQLITE_CONFIG_SQLLOG: {
137084      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
137085      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
137086      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
137087      break;
137088    }
137089#endif
137090
137091    case SQLITE_CONFIG_MMAP_SIZE: {
137092      /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
137093      ** integer (sqlite3_int64) values that are the default mmap size limit
137094      ** (the default setting for PRAGMA mmap_size) and the maximum allowed
137095      ** mmap size limit. */
137096      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
137097      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
137098      /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
137099      ** negative, then that argument is changed to its compile-time default.
137100      **
137101      ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
137102      ** silently truncated if necessary so that it does not exceed the
137103      ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
137104      ** compile-time option.
137105      */
137106      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
137107        mxMmap = SQLITE_MAX_MMAP_SIZE;
137108      }
137109      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
137110      if( szMmap>mxMmap) szMmap = mxMmap;
137111      sqlite3GlobalConfig.mxMmap = mxMmap;
137112      sqlite3GlobalConfig.szMmap = szMmap;
137113      break;
137114    }
137115
137116#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
137117    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
137118      /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
137119      ** unsigned integer value that specifies the maximum size of the created
137120      ** heap. */
137121      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
137122      break;
137123    }
137124#endif
137125
137126    case SQLITE_CONFIG_PMASZ: {
137127      sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
137128      break;
137129    }
137130
137131    case SQLITE_CONFIG_STMTJRNL_SPILL: {
137132      sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
137133      break;
137134    }
137135
137136    default: {
137137      rc = SQLITE_ERROR;
137138      break;
137139    }
137140  }
137141  va_end(ap);
137142  return rc;
137143}
137144
137145/*
137146** Set up the lookaside buffers for a database connection.
137147** Return SQLITE_OK on success.
137148** If lookaside is already active, return SQLITE_BUSY.
137149**
137150** The sz parameter is the number of bytes in each lookaside slot.
137151** The cnt parameter is the number of slots.  If pStart is NULL the
137152** space for the lookaside memory is obtained from sqlite3_malloc().
137153** If pStart is not NULL then it is sz*cnt bytes of memory to use for
137154** the lookaside memory.
137155*/
137156static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
137157#ifndef SQLITE_OMIT_LOOKASIDE
137158  void *pStart;
137159  if( db->lookaside.nOut ){
137160    return SQLITE_BUSY;
137161  }
137162  /* Free any existing lookaside buffer for this handle before
137163  ** allocating a new one so we don't have to have space for
137164  ** both at the same time.
137165  */
137166  if( db->lookaside.bMalloced ){
137167    sqlite3_free(db->lookaside.pStart);
137168  }
137169  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
137170  ** than a pointer to be useful.
137171  */
137172  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
137173  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
137174  if( cnt<0 ) cnt = 0;
137175  if( sz==0 || cnt==0 ){
137176    sz = 0;
137177    pStart = 0;
137178  }else if( pBuf==0 ){
137179    sqlite3BeginBenignMalloc();
137180    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
137181    sqlite3EndBenignMalloc();
137182    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
137183  }else{
137184    pStart = pBuf;
137185  }
137186  db->lookaside.pStart = pStart;
137187  db->lookaside.pFree = 0;
137188  db->lookaside.sz = (u16)sz;
137189  if( pStart ){
137190    int i;
137191    LookasideSlot *p;
137192    assert( sz > (int)sizeof(LookasideSlot*) );
137193    p = (LookasideSlot*)pStart;
137194    for(i=cnt-1; i>=0; i--){
137195      p->pNext = db->lookaside.pFree;
137196      db->lookaside.pFree = p;
137197      p = (LookasideSlot*)&((u8*)p)[sz];
137198    }
137199    db->lookaside.pEnd = p;
137200    db->lookaside.bDisable = 0;
137201    db->lookaside.bMalloced = pBuf==0 ?1:0;
137202  }else{
137203    db->lookaside.pStart = db;
137204    db->lookaside.pEnd = db;
137205    db->lookaside.bDisable = 1;
137206    db->lookaside.bMalloced = 0;
137207  }
137208#endif /* SQLITE_OMIT_LOOKASIDE */
137209  return SQLITE_OK;
137210}
137211
137212/*
137213** Return the mutex associated with a database connection.
137214*/
137215SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
137216#ifdef SQLITE_ENABLE_API_ARMOR
137217  if( !sqlite3SafetyCheckOk(db) ){
137218    (void)SQLITE_MISUSE_BKPT;
137219    return 0;
137220  }
137221#endif
137222  return db->mutex;
137223}
137224
137225/*
137226** Free up as much memory as we can from the given database
137227** connection.
137228*/
137229SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
137230  int i;
137231
137232#ifdef SQLITE_ENABLE_API_ARMOR
137233  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137234#endif
137235  sqlite3_mutex_enter(db->mutex);
137236  sqlite3BtreeEnterAll(db);
137237  for(i=0; i<db->nDb; i++){
137238    Btree *pBt = db->aDb[i].pBt;
137239    if( pBt ){
137240      Pager *pPager = sqlite3BtreePager(pBt);
137241      sqlite3PagerShrink(pPager);
137242    }
137243  }
137244  sqlite3BtreeLeaveAll(db);
137245  sqlite3_mutex_leave(db->mutex);
137246  return SQLITE_OK;
137247}
137248
137249/*
137250** Flush any dirty pages in the pager-cache for any attached database
137251** to disk.
137252*/
137253SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3 *db){
137254  int i;
137255  int rc = SQLITE_OK;
137256  int bSeenBusy = 0;
137257
137258#ifdef SQLITE_ENABLE_API_ARMOR
137259  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137260#endif
137261  sqlite3_mutex_enter(db->mutex);
137262  sqlite3BtreeEnterAll(db);
137263  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
137264    Btree *pBt = db->aDb[i].pBt;
137265    if( pBt && sqlite3BtreeIsInTrans(pBt) ){
137266      Pager *pPager = sqlite3BtreePager(pBt);
137267      rc = sqlite3PagerFlush(pPager);
137268      if( rc==SQLITE_BUSY ){
137269        bSeenBusy = 1;
137270        rc = SQLITE_OK;
137271      }
137272    }
137273  }
137274  sqlite3BtreeLeaveAll(db);
137275  sqlite3_mutex_leave(db->mutex);
137276  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
137277}
137278
137279/*
137280** Configuration settings for an individual database connection
137281*/
137282SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
137283  va_list ap;
137284  int rc;
137285  va_start(ap, op);
137286  switch( op ){
137287    case SQLITE_DBCONFIG_LOOKASIDE: {
137288      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
137289      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
137290      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
137291      rc = setupLookaside(db, pBuf, sz, cnt);
137292      break;
137293    }
137294    default: {
137295      static const struct {
137296        int op;      /* The opcode */
137297        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
137298      } aFlagOp[] = {
137299        { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
137300        { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
137301        { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
137302        { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
137303      };
137304      unsigned int i;
137305      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
137306      for(i=0; i<ArraySize(aFlagOp); i++){
137307        if( aFlagOp[i].op==op ){
137308          int onoff = va_arg(ap, int);
137309          int *pRes = va_arg(ap, int*);
137310          int oldFlags = db->flags;
137311          if( onoff>0 ){
137312            db->flags |= aFlagOp[i].mask;
137313          }else if( onoff==0 ){
137314            db->flags &= ~aFlagOp[i].mask;
137315          }
137316          if( oldFlags!=db->flags ){
137317            sqlite3ExpirePreparedStatements(db);
137318          }
137319          if( pRes ){
137320            *pRes = (db->flags & aFlagOp[i].mask)!=0;
137321          }
137322          rc = SQLITE_OK;
137323          break;
137324        }
137325      }
137326      break;
137327    }
137328  }
137329  va_end(ap);
137330  return rc;
137331}
137332
137333
137334/*
137335** Return true if the buffer z[0..n-1] contains all spaces.
137336*/
137337static int allSpaces(const char *z, int n){
137338  while( n>0 && z[n-1]==' ' ){ n--; }
137339  return n==0;
137340}
137341
137342/*
137343** This is the default collating function named "BINARY" which is always
137344** available.
137345**
137346** If the padFlag argument is not NULL then space padding at the end
137347** of strings is ignored.  This implements the RTRIM collation.
137348*/
137349static int binCollFunc(
137350  void *padFlag,
137351  int nKey1, const void *pKey1,
137352  int nKey2, const void *pKey2
137353){
137354  int rc, n;
137355  n = nKey1<nKey2 ? nKey1 : nKey2;
137356  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
137357  ** strings byte by byte using the memcmp() function from the standard C
137358  ** library. */
137359  rc = memcmp(pKey1, pKey2, n);
137360  if( rc==0 ){
137361    if( padFlag
137362     && allSpaces(((char*)pKey1)+n, nKey1-n)
137363     && allSpaces(((char*)pKey2)+n, nKey2-n)
137364    ){
137365      /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
137366      ** spaces at the end of either string do not change the result. In other
137367      ** words, strings will compare equal to one another as long as they
137368      ** differ only in the number of spaces at the end.
137369      */
137370    }else{
137371      rc = nKey1 - nKey2;
137372    }
137373  }
137374  return rc;
137375}
137376
137377/*
137378** Another built-in collating sequence: NOCASE.
137379**
137380** This collating sequence is intended to be used for "case independent
137381** comparison". SQLite's knowledge of upper and lower case equivalents
137382** extends only to the 26 characters used in the English language.
137383**
137384** At the moment there is only a UTF-8 implementation.
137385*/
137386static int nocaseCollatingFunc(
137387  void *NotUsed,
137388  int nKey1, const void *pKey1,
137389  int nKey2, const void *pKey2
137390){
137391  int r = sqlite3StrNICmp(
137392      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
137393  UNUSED_PARAMETER(NotUsed);
137394  if( 0==r ){
137395    r = nKey1-nKey2;
137396  }
137397  return r;
137398}
137399
137400/*
137401** Return the ROWID of the most recent insert
137402*/
137403SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
137404#ifdef SQLITE_ENABLE_API_ARMOR
137405  if( !sqlite3SafetyCheckOk(db) ){
137406    (void)SQLITE_MISUSE_BKPT;
137407    return 0;
137408  }
137409#endif
137410  return db->lastRowid;
137411}
137412
137413/*
137414** Return the number of changes in the most recent call to sqlite3_exec().
137415*/
137416SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
137417#ifdef SQLITE_ENABLE_API_ARMOR
137418  if( !sqlite3SafetyCheckOk(db) ){
137419    (void)SQLITE_MISUSE_BKPT;
137420    return 0;
137421  }
137422#endif
137423  return db->nChange;
137424}
137425
137426/*
137427** Return the number of changes since the database handle was opened.
137428*/
137429SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
137430#ifdef SQLITE_ENABLE_API_ARMOR
137431  if( !sqlite3SafetyCheckOk(db) ){
137432    (void)SQLITE_MISUSE_BKPT;
137433    return 0;
137434  }
137435#endif
137436  return db->nTotalChange;
137437}
137438
137439/*
137440** Close all open savepoints. This function only manipulates fields of the
137441** database handle object, it does not close any savepoints that may be open
137442** at the b-tree/pager level.
137443*/
137444SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
137445  while( db->pSavepoint ){
137446    Savepoint *pTmp = db->pSavepoint;
137447    db->pSavepoint = pTmp->pNext;
137448    sqlite3DbFree(db, pTmp);
137449  }
137450  db->nSavepoint = 0;
137451  db->nStatement = 0;
137452  db->isTransactionSavepoint = 0;
137453}
137454
137455/*
137456** Invoke the destructor function associated with FuncDef p, if any. Except,
137457** if this is not the last copy of the function, do not invoke it. Multiple
137458** copies of a single function are created when create_function() is called
137459** with SQLITE_ANY as the encoding.
137460*/
137461static void functionDestroy(sqlite3 *db, FuncDef *p){
137462  FuncDestructor *pDestructor = p->u.pDestructor;
137463  if( pDestructor ){
137464    pDestructor->nRef--;
137465    if( pDestructor->nRef==0 ){
137466      pDestructor->xDestroy(pDestructor->pUserData);
137467      sqlite3DbFree(db, pDestructor);
137468    }
137469  }
137470}
137471
137472/*
137473** Disconnect all sqlite3_vtab objects that belong to database connection
137474** db. This is called when db is being closed.
137475*/
137476static void disconnectAllVtab(sqlite3 *db){
137477#ifndef SQLITE_OMIT_VIRTUALTABLE
137478  int i;
137479  HashElem *p;
137480  sqlite3BtreeEnterAll(db);
137481  for(i=0; i<db->nDb; i++){
137482    Schema *pSchema = db->aDb[i].pSchema;
137483    if( db->aDb[i].pSchema ){
137484      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
137485        Table *pTab = (Table *)sqliteHashData(p);
137486        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
137487      }
137488    }
137489  }
137490  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
137491    Module *pMod = (Module *)sqliteHashData(p);
137492    if( pMod->pEpoTab ){
137493      sqlite3VtabDisconnect(db, pMod->pEpoTab);
137494    }
137495  }
137496  sqlite3VtabUnlockList(db);
137497  sqlite3BtreeLeaveAll(db);
137498#else
137499  UNUSED_PARAMETER(db);
137500#endif
137501}
137502
137503/*
137504** Return TRUE if database connection db has unfinalized prepared
137505** statements or unfinished sqlite3_backup objects.
137506*/
137507static int connectionIsBusy(sqlite3 *db){
137508  int j;
137509  assert( sqlite3_mutex_held(db->mutex) );
137510  if( db->pVdbe ) return 1;
137511  for(j=0; j<db->nDb; j++){
137512    Btree *pBt = db->aDb[j].pBt;
137513    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
137514  }
137515  return 0;
137516}
137517
137518/*
137519** Close an existing SQLite database
137520*/
137521static int sqlite3Close(sqlite3 *db, int forceZombie){
137522  if( !db ){
137523    /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
137524    ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
137525    return SQLITE_OK;
137526  }
137527  if( !sqlite3SafetyCheckSickOrOk(db) ){
137528    return SQLITE_MISUSE_BKPT;
137529  }
137530  sqlite3_mutex_enter(db->mutex);
137531  if( db->mTrace & SQLITE_TRACE_CLOSE ){
137532    db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
137533  }
137534
137535  /* Force xDisconnect calls on all virtual tables */
137536  disconnectAllVtab(db);
137537
137538  /* If a transaction is open, the disconnectAllVtab() call above
137539  ** will not have called the xDisconnect() method on any virtual
137540  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
137541  ** call will do so. We need to do this before the check for active
137542  ** SQL statements below, as the v-table implementation may be storing
137543  ** some prepared statements internally.
137544  */
137545  sqlite3VtabRollback(db);
137546
137547  /* Legacy behavior (sqlite3_close() behavior) is to return
137548  ** SQLITE_BUSY if the connection can not be closed immediately.
137549  */
137550  if( !forceZombie && connectionIsBusy(db) ){
137551    sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
137552       "statements or unfinished backups");
137553    sqlite3_mutex_leave(db->mutex);
137554    return SQLITE_BUSY;
137555  }
137556
137557#ifdef SQLITE_ENABLE_SQLLOG
137558  if( sqlite3GlobalConfig.xSqllog ){
137559    /* Closing the handle. Fourth parameter is passed the value 2. */
137560    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
137561  }
137562#endif
137563
137564  /* Convert the connection into a zombie and then close it.
137565  */
137566  db->magic = SQLITE_MAGIC_ZOMBIE;
137567  sqlite3LeaveMutexAndCloseZombie(db);
137568  return SQLITE_OK;
137569}
137570
137571/*
137572** Two variations on the public interface for closing a database
137573** connection. The sqlite3_close() version returns SQLITE_BUSY and
137574** leaves the connection option if there are unfinalized prepared
137575** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
137576** version forces the connection to become a zombie if there are
137577** unclosed resources, and arranges for deallocation when the last
137578** prepare statement or sqlite3_backup closes.
137579*/
137580SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
137581SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
137582
137583
137584/*
137585** Close the mutex on database connection db.
137586**
137587** Furthermore, if database connection db is a zombie (meaning that there
137588** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
137589** every sqlite3_stmt has now been finalized and every sqlite3_backup has
137590** finished, then free all resources.
137591*/
137592SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
137593  HashElem *i;                    /* Hash table iterator */
137594  int j;
137595
137596  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
137597  ** or if the connection has not yet been closed by sqlite3_close_v2(),
137598  ** then just leave the mutex and return.
137599  */
137600  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
137601    sqlite3_mutex_leave(db->mutex);
137602    return;
137603  }
137604
137605  /* If we reach this point, it means that the database connection has
137606  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
137607  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
137608  ** go ahead and free all resources.
137609  */
137610
137611  /* If a transaction is open, roll it back. This also ensures that if
137612  ** any database schemas have been modified by an uncommitted transaction
137613  ** they are reset. And that the required b-tree mutex is held to make
137614  ** the pager rollback and schema reset an atomic operation. */
137615  sqlite3RollbackAll(db, SQLITE_OK);
137616
137617  /* Free any outstanding Savepoint structures. */
137618  sqlite3CloseSavepoints(db);
137619
137620  /* Close all database connections */
137621  for(j=0; j<db->nDb; j++){
137622    struct Db *pDb = &db->aDb[j];
137623    if( pDb->pBt ){
137624      sqlite3BtreeClose(pDb->pBt);
137625      pDb->pBt = 0;
137626      if( j!=1 ){
137627        pDb->pSchema = 0;
137628      }
137629    }
137630  }
137631  /* Clear the TEMP schema separately and last */
137632  if( db->aDb[1].pSchema ){
137633    sqlite3SchemaClear(db->aDb[1].pSchema);
137634  }
137635  sqlite3VtabUnlockList(db);
137636
137637  /* Free up the array of auxiliary databases */
137638  sqlite3CollapseDatabaseArray(db);
137639  assert( db->nDb<=2 );
137640  assert( db->aDb==db->aDbStatic );
137641
137642  /* Tell the code in notify.c that the connection no longer holds any
137643  ** locks and does not require any further unlock-notify callbacks.
137644  */
137645  sqlite3ConnectionClosed(db);
137646
137647  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
137648    FuncDef *pNext, *p;
137649    p = sqliteHashData(i);
137650    do{
137651      functionDestroy(db, p);
137652      pNext = p->pNext;
137653      sqlite3DbFree(db, p);
137654      p = pNext;
137655    }while( p );
137656  }
137657  sqlite3HashClear(&db->aFunc);
137658  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
137659    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
137660    /* Invoke any destructors registered for collation sequence user data. */
137661    for(j=0; j<3; j++){
137662      if( pColl[j].xDel ){
137663        pColl[j].xDel(pColl[j].pUser);
137664      }
137665    }
137666    sqlite3DbFree(db, pColl);
137667  }
137668  sqlite3HashClear(&db->aCollSeq);
137669#ifndef SQLITE_OMIT_VIRTUALTABLE
137670  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
137671    Module *pMod = (Module *)sqliteHashData(i);
137672    if( pMod->xDestroy ){
137673      pMod->xDestroy(pMod->pAux);
137674    }
137675    sqlite3VtabEponymousTableClear(db, pMod);
137676    sqlite3DbFree(db, pMod);
137677  }
137678  sqlite3HashClear(&db->aModule);
137679#endif
137680
137681  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
137682  sqlite3ValueFree(db->pErr);
137683  sqlite3CloseExtensions(db);
137684#if SQLITE_USER_AUTHENTICATION
137685  sqlite3_free(db->auth.zAuthUser);
137686  sqlite3_free(db->auth.zAuthPW);
137687#endif
137688
137689  db->magic = SQLITE_MAGIC_ERROR;
137690
137691  /* The temp-database schema is allocated differently from the other schema
137692  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
137693  ** So it needs to be freed here. Todo: Why not roll the temp schema into
137694  ** the same sqliteMalloc() as the one that allocates the database
137695  ** structure?
137696  */
137697  sqlite3DbFree(db, db->aDb[1].pSchema);
137698  sqlite3_mutex_leave(db->mutex);
137699  db->magic = SQLITE_MAGIC_CLOSED;
137700  sqlite3_mutex_free(db->mutex);
137701  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
137702  if( db->lookaside.bMalloced ){
137703    sqlite3_free(db->lookaside.pStart);
137704  }
137705  sqlite3_free(db);
137706}
137707
137708/*
137709** Rollback all database files.  If tripCode is not SQLITE_OK, then
137710** any write cursors are invalidated ("tripped" - as in "tripping a circuit
137711** breaker") and made to return tripCode if there are any further
137712** attempts to use that cursor.  Read cursors remain open and valid
137713** but are "saved" in case the table pages are moved around.
137714*/
137715SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
137716  int i;
137717  int inTrans = 0;
137718  int schemaChange;
137719  assert( sqlite3_mutex_held(db->mutex) );
137720  sqlite3BeginBenignMalloc();
137721
137722  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
137723  ** This is important in case the transaction being rolled back has
137724  ** modified the database schema. If the b-tree mutexes are not taken
137725  ** here, then another shared-cache connection might sneak in between
137726  ** the database rollback and schema reset, which can cause false
137727  ** corruption reports in some cases.  */
137728  sqlite3BtreeEnterAll(db);
137729  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
137730
137731  for(i=0; i<db->nDb; i++){
137732    Btree *p = db->aDb[i].pBt;
137733    if( p ){
137734      if( sqlite3BtreeIsInTrans(p) ){
137735        inTrans = 1;
137736      }
137737      sqlite3BtreeRollback(p, tripCode, !schemaChange);
137738    }
137739  }
137740  sqlite3VtabRollback(db);
137741  sqlite3EndBenignMalloc();
137742
137743  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
137744    sqlite3ExpirePreparedStatements(db);
137745    sqlite3ResetAllSchemasOfConnection(db);
137746  }
137747  sqlite3BtreeLeaveAll(db);
137748
137749  /* Any deferred constraint violations have now been resolved. */
137750  db->nDeferredCons = 0;
137751  db->nDeferredImmCons = 0;
137752  db->flags &= ~SQLITE_DeferFKs;
137753
137754  /* If one has been configured, invoke the rollback-hook callback */
137755  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
137756    db->xRollbackCallback(db->pRollbackArg);
137757  }
137758}
137759
137760/*
137761** Return a static string containing the name corresponding to the error code
137762** specified in the argument.
137763*/
137764#if defined(SQLITE_NEED_ERR_NAME)
137765SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
137766  const char *zName = 0;
137767  int i, origRc = rc;
137768  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
137769    switch( rc ){
137770      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
137771      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
137772      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
137773      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
137774      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
137775      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
137776      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
137777      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
137778      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
137779      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
137780      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
137781      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
137782      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
137783      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
137784      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
137785      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
137786      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
137787      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
137788      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
137789      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
137790      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
137791      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
137792      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
137793      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
137794      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
137795      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
137796      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
137797      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
137798      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
137799      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
137800      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
137801      case SQLITE_IOERR_CHECKRESERVEDLOCK:
137802                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
137803      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
137804      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
137805      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
137806      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
137807      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
137808      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
137809      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
137810      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
137811      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
137812      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
137813      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
137814      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
137815      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
137816      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
137817      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
137818      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
137819      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
137820      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
137821      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
137822      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
137823      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
137824      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
137825      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
137826      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
137827      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
137828      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
137829      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
137830      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
137831      case SQLITE_CONSTRAINT_FOREIGNKEY:
137832                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
137833      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
137834      case SQLITE_CONSTRAINT_PRIMARYKEY:
137835                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
137836      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
137837      case SQLITE_CONSTRAINT_COMMITHOOK:
137838                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
137839      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
137840      case SQLITE_CONSTRAINT_FUNCTION:
137841                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
137842      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
137843      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
137844      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
137845      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
137846      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
137847      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
137848      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
137849      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
137850      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
137851      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
137852      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
137853      case SQLITE_NOTICE_RECOVER_ROLLBACK:
137854                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
137855      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
137856      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
137857      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
137858    }
137859  }
137860  if( zName==0 ){
137861    static char zBuf[50];
137862    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
137863    zName = zBuf;
137864  }
137865  return zName;
137866}
137867#endif
137868
137869/*
137870** Return a static string that describes the kind of error specified in the
137871** argument.
137872*/
137873SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
137874  static const char* const aMsg[] = {
137875    /* SQLITE_OK          */ "not an error",
137876    /* SQLITE_ERROR       */ "SQL logic error or missing database",
137877    /* SQLITE_INTERNAL    */ 0,
137878    /* SQLITE_PERM        */ "access permission denied",
137879    /* SQLITE_ABORT       */ "callback requested query abort",
137880    /* SQLITE_BUSY        */ "database is locked",
137881    /* SQLITE_LOCKED      */ "database table is locked",
137882    /* SQLITE_NOMEM       */ "out of memory",
137883    /* SQLITE_READONLY    */ "attempt to write a readonly database",
137884    /* SQLITE_INTERRUPT   */ "interrupted",
137885    /* SQLITE_IOERR       */ "disk I/O error",
137886    /* SQLITE_CORRUPT     */ "database disk image is malformed",
137887    /* SQLITE_NOTFOUND    */ "unknown operation",
137888    /* SQLITE_FULL        */ "database or disk is full",
137889    /* SQLITE_CANTOPEN    */ "unable to open database file",
137890    /* SQLITE_PROTOCOL    */ "locking protocol",
137891    /* SQLITE_EMPTY       */ "table contains no data",
137892    /* SQLITE_SCHEMA      */ "database schema has changed",
137893    /* SQLITE_TOOBIG      */ "string or blob too big",
137894    /* SQLITE_CONSTRAINT  */ "constraint failed",
137895    /* SQLITE_MISMATCH    */ "datatype mismatch",
137896    /* SQLITE_MISUSE      */ "library routine called out of sequence",
137897    /* SQLITE_NOLFS       */ "large file support is disabled",
137898    /* SQLITE_AUTH        */ "authorization denied",
137899    /* SQLITE_FORMAT      */ "auxiliary database format error",
137900    /* SQLITE_RANGE       */ "bind or column index out of range",
137901    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
137902  };
137903  const char *zErr = "unknown error";
137904  switch( rc ){
137905    case SQLITE_ABORT_ROLLBACK: {
137906      zErr = "abort due to ROLLBACK";
137907      break;
137908    }
137909    default: {
137910      rc &= 0xff;
137911      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
137912        zErr = aMsg[rc];
137913      }
137914      break;
137915    }
137916  }
137917  return zErr;
137918}
137919
137920/*
137921** This routine implements a busy callback that sleeps and tries
137922** again until a timeout value is reached.  The timeout value is
137923** an integer number of milliseconds passed in as the first
137924** argument.
137925*/
137926static int sqliteDefaultBusyCallback(
137927 void *ptr,               /* Database connection */
137928 int count                /* Number of times table has been busy */
137929){
137930#if SQLITE_OS_WIN || HAVE_USLEEP
137931  static const u8 delays[] =
137932     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
137933  static const u8 totals[] =
137934     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
137935# define NDELAY ArraySize(delays)
137936  sqlite3 *db = (sqlite3 *)ptr;
137937  int timeout = db->busyTimeout;
137938  int delay, prior;
137939
137940  assert( count>=0 );
137941  if( count < NDELAY ){
137942    delay = delays[count];
137943    prior = totals[count];
137944  }else{
137945    delay = delays[NDELAY-1];
137946    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
137947  }
137948  if( prior + delay > timeout ){
137949    delay = timeout - prior;
137950    if( delay<=0 ) return 0;
137951  }
137952  sqlite3OsSleep(db->pVfs, delay*1000);
137953  return 1;
137954#else
137955  sqlite3 *db = (sqlite3 *)ptr;
137956  int timeout = ((sqlite3 *)ptr)->busyTimeout;
137957  if( (count+1)*1000 > timeout ){
137958    return 0;
137959  }
137960  sqlite3OsSleep(db->pVfs, 1000000);
137961  return 1;
137962#endif
137963}
137964
137965/*
137966** Invoke the given busy handler.
137967**
137968** This routine is called when an operation failed with a lock.
137969** If this routine returns non-zero, the lock is retried.  If it
137970** returns 0, the operation aborts with an SQLITE_BUSY error.
137971*/
137972SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
137973  int rc;
137974  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
137975  rc = p->xFunc(p->pArg, p->nBusy);
137976  if( rc==0 ){
137977    p->nBusy = -1;
137978  }else{
137979    p->nBusy++;
137980  }
137981  return rc;
137982}
137983
137984/*
137985** This routine sets the busy callback for an Sqlite database to the
137986** given callback function with the given argument.
137987*/
137988SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
137989  sqlite3 *db,
137990  int (*xBusy)(void*,int),
137991  void *pArg
137992){
137993#ifdef SQLITE_ENABLE_API_ARMOR
137994  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137995#endif
137996  sqlite3_mutex_enter(db->mutex);
137997  db->busyHandler.xFunc = xBusy;
137998  db->busyHandler.pArg = pArg;
137999  db->busyHandler.nBusy = 0;
138000  db->busyTimeout = 0;
138001  sqlite3_mutex_leave(db->mutex);
138002  return SQLITE_OK;
138003}
138004
138005#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
138006/*
138007** This routine sets the progress callback for an Sqlite database to the
138008** given callback function with the given argument. The progress callback will
138009** be invoked every nOps opcodes.
138010*/
138011SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
138012  sqlite3 *db,
138013  int nOps,
138014  int (*xProgress)(void*),
138015  void *pArg
138016){
138017#ifdef SQLITE_ENABLE_API_ARMOR
138018  if( !sqlite3SafetyCheckOk(db) ){
138019    (void)SQLITE_MISUSE_BKPT;
138020    return;
138021  }
138022#endif
138023  sqlite3_mutex_enter(db->mutex);
138024  if( nOps>0 ){
138025    db->xProgress = xProgress;
138026    db->nProgressOps = (unsigned)nOps;
138027    db->pProgressArg = pArg;
138028  }else{
138029    db->xProgress = 0;
138030    db->nProgressOps = 0;
138031    db->pProgressArg = 0;
138032  }
138033  sqlite3_mutex_leave(db->mutex);
138034}
138035#endif
138036
138037
138038/*
138039** This routine installs a default busy handler that waits for the
138040** specified number of milliseconds before returning 0.
138041*/
138042SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
138043#ifdef SQLITE_ENABLE_API_ARMOR
138044  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138045#endif
138046  if( ms>0 ){
138047    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
138048    db->busyTimeout = ms;
138049  }else{
138050    sqlite3_busy_handler(db, 0, 0);
138051  }
138052  return SQLITE_OK;
138053}
138054
138055/*
138056** Cause any pending operation to stop at its earliest opportunity.
138057*/
138058SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
138059#ifdef SQLITE_ENABLE_API_ARMOR
138060  if( !sqlite3SafetyCheckOk(db) ){
138061    (void)SQLITE_MISUSE_BKPT;
138062    return;
138063  }
138064#endif
138065  db->u1.isInterrupted = 1;
138066}
138067
138068
138069/*
138070** This function is exactly the same as sqlite3_create_function(), except
138071** that it is designed to be called by internal code. The difference is
138072** that if a malloc() fails in sqlite3_create_function(), an error code
138073** is returned and the mallocFailed flag cleared.
138074*/
138075SQLITE_PRIVATE int sqlite3CreateFunc(
138076  sqlite3 *db,
138077  const char *zFunctionName,
138078  int nArg,
138079  int enc,
138080  void *pUserData,
138081  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138082  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138083  void (*xFinal)(sqlite3_context*),
138084  FuncDestructor *pDestructor
138085){
138086  FuncDef *p;
138087  int nName;
138088  int extraFlags;
138089
138090  assert( sqlite3_mutex_held(db->mutex) );
138091  if( zFunctionName==0 ||
138092      (xSFunc && (xFinal || xStep)) ||
138093      (!xSFunc && (xFinal && !xStep)) ||
138094      (!xSFunc && (!xFinal && xStep)) ||
138095      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
138096      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
138097    return SQLITE_MISUSE_BKPT;
138098  }
138099
138100  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
138101  extraFlags = enc &  SQLITE_DETERMINISTIC;
138102  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
138103
138104#ifndef SQLITE_OMIT_UTF16
138105  /* If SQLITE_UTF16 is specified as the encoding type, transform this
138106  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
138107  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
138108  **
138109  ** If SQLITE_ANY is specified, add three versions of the function
138110  ** to the hash table.
138111  */
138112  if( enc==SQLITE_UTF16 ){
138113    enc = SQLITE_UTF16NATIVE;
138114  }else if( enc==SQLITE_ANY ){
138115    int rc;
138116    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
138117         pUserData, xSFunc, xStep, xFinal, pDestructor);
138118    if( rc==SQLITE_OK ){
138119      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
138120          pUserData, xSFunc, xStep, xFinal, pDestructor);
138121    }
138122    if( rc!=SQLITE_OK ){
138123      return rc;
138124    }
138125    enc = SQLITE_UTF16BE;
138126  }
138127#else
138128  enc = SQLITE_UTF8;
138129#endif
138130
138131  /* Check if an existing function is being overridden or deleted. If so,
138132  ** and there are active VMs, then return SQLITE_BUSY. If a function
138133  ** is being overridden/deleted but there are no active VMs, allow the
138134  ** operation to continue but invalidate all precompiled statements.
138135  */
138136  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
138137  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
138138    if( db->nVdbeActive ){
138139      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
138140        "unable to delete/modify user-function due to active statements");
138141      assert( !db->mallocFailed );
138142      return SQLITE_BUSY;
138143    }else{
138144      sqlite3ExpirePreparedStatements(db);
138145    }
138146  }
138147
138148  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
138149  assert(p || db->mallocFailed);
138150  if( !p ){
138151    return SQLITE_NOMEM_BKPT;
138152  }
138153
138154  /* If an older version of the function with a configured destructor is
138155  ** being replaced invoke the destructor function here. */
138156  functionDestroy(db, p);
138157
138158  if( pDestructor ){
138159    pDestructor->nRef++;
138160  }
138161  p->u.pDestructor = pDestructor;
138162  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
138163  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
138164  p->xSFunc = xSFunc ? xSFunc : xStep;
138165  p->xFinalize = xFinal;
138166  p->pUserData = pUserData;
138167  p->nArg = (u16)nArg;
138168  return SQLITE_OK;
138169}
138170
138171/*
138172** Create new user functions.
138173*/
138174SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
138175  sqlite3 *db,
138176  const char *zFunc,
138177  int nArg,
138178  int enc,
138179  void *p,
138180  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138181  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138182  void (*xFinal)(sqlite3_context*)
138183){
138184  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
138185                                    xFinal, 0);
138186}
138187
138188SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
138189  sqlite3 *db,
138190  const char *zFunc,
138191  int nArg,
138192  int enc,
138193  void *p,
138194  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138195  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138196  void (*xFinal)(sqlite3_context*),
138197  void (*xDestroy)(void *)
138198){
138199  int rc = SQLITE_ERROR;
138200  FuncDestructor *pArg = 0;
138201
138202#ifdef SQLITE_ENABLE_API_ARMOR
138203  if( !sqlite3SafetyCheckOk(db) ){
138204    return SQLITE_MISUSE_BKPT;
138205  }
138206#endif
138207  sqlite3_mutex_enter(db->mutex);
138208  if( xDestroy ){
138209    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
138210    if( !pArg ){
138211      xDestroy(p);
138212      goto out;
138213    }
138214    pArg->xDestroy = xDestroy;
138215    pArg->pUserData = p;
138216  }
138217  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
138218  if( pArg && pArg->nRef==0 ){
138219    assert( rc!=SQLITE_OK );
138220    xDestroy(p);
138221    sqlite3DbFree(db, pArg);
138222  }
138223
138224 out:
138225  rc = sqlite3ApiExit(db, rc);
138226  sqlite3_mutex_leave(db->mutex);
138227  return rc;
138228}
138229
138230#ifndef SQLITE_OMIT_UTF16
138231SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
138232  sqlite3 *db,
138233  const void *zFunctionName,
138234  int nArg,
138235  int eTextRep,
138236  void *p,
138237  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
138238  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
138239  void (*xFinal)(sqlite3_context*)
138240){
138241  int rc;
138242  char *zFunc8;
138243
138244#ifdef SQLITE_ENABLE_API_ARMOR
138245  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
138246#endif
138247  sqlite3_mutex_enter(db->mutex);
138248  assert( !db->mallocFailed );
138249  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
138250  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
138251  sqlite3DbFree(db, zFunc8);
138252  rc = sqlite3ApiExit(db, rc);
138253  sqlite3_mutex_leave(db->mutex);
138254  return rc;
138255}
138256#endif
138257
138258
138259/*
138260** Declare that a function has been overloaded by a virtual table.
138261**
138262** If the function already exists as a regular global function, then
138263** this routine is a no-op.  If the function does not exist, then create
138264** a new one that always throws a run-time error.
138265**
138266** When virtual tables intend to provide an overloaded function, they
138267** should call this routine to make sure the global function exists.
138268** A global function must exist in order for name resolution to work
138269** properly.
138270*/
138271SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
138272  sqlite3 *db,
138273  const char *zName,
138274  int nArg
138275){
138276  int rc = SQLITE_OK;
138277
138278#ifdef SQLITE_ENABLE_API_ARMOR
138279  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
138280    return SQLITE_MISUSE_BKPT;
138281  }
138282#endif
138283  sqlite3_mutex_enter(db->mutex);
138284  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
138285    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
138286                           0, sqlite3InvalidFunction, 0, 0, 0);
138287  }
138288  rc = sqlite3ApiExit(db, rc);
138289  sqlite3_mutex_leave(db->mutex);
138290  return rc;
138291}
138292
138293#ifndef SQLITE_OMIT_TRACE
138294/*
138295** Register a trace function.  The pArg from the previously registered trace
138296** is returned.
138297**
138298** A NULL trace function means that no tracing is executes.  A non-NULL
138299** trace is a pointer to a function that is invoked at the start of each
138300** SQL statement.
138301*/
138302#ifndef SQLITE_OMIT_DEPRECATED
138303SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
138304  void *pOld;
138305
138306#ifdef SQLITE_ENABLE_API_ARMOR
138307  if( !sqlite3SafetyCheckOk(db) ){
138308    (void)SQLITE_MISUSE_BKPT;
138309    return 0;
138310  }
138311#endif
138312  sqlite3_mutex_enter(db->mutex);
138313  pOld = db->pTraceArg;
138314  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
138315  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
138316  db->pTraceArg = pArg;
138317  sqlite3_mutex_leave(db->mutex);
138318  return pOld;
138319}
138320#endif /* SQLITE_OMIT_DEPRECATED */
138321
138322/* Register a trace callback using the version-2 interface.
138323*/
138324SQLITE_API int SQLITE_STDCALL sqlite3_trace_v2(
138325  sqlite3 *db,                               /* Trace this connection */
138326  unsigned mTrace,                           /* Mask of events to be traced */
138327  int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
138328  void *pArg                                 /* Context */
138329){
138330#ifdef SQLITE_ENABLE_API_ARMOR
138331  if( !sqlite3SafetyCheckOk(db) ){
138332    return SQLITE_MISUSE_BKPT;
138333  }
138334#endif
138335  sqlite3_mutex_enter(db->mutex);
138336  db->mTrace = mTrace;
138337  db->xTrace = xTrace;
138338  db->pTraceArg = pArg;
138339  sqlite3_mutex_leave(db->mutex);
138340  return SQLITE_OK;
138341}
138342
138343#ifndef SQLITE_OMIT_DEPRECATED
138344/*
138345** Register a profile function.  The pArg from the previously registered
138346** profile function is returned.
138347**
138348** A NULL profile function means that no profiling is executes.  A non-NULL
138349** profile is a pointer to a function that is invoked at the conclusion of
138350** each SQL statement that is run.
138351*/
138352SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
138353  sqlite3 *db,
138354  void (*xProfile)(void*,const char*,sqlite_uint64),
138355  void *pArg
138356){
138357  void *pOld;
138358
138359#ifdef SQLITE_ENABLE_API_ARMOR
138360  if( !sqlite3SafetyCheckOk(db) ){
138361    (void)SQLITE_MISUSE_BKPT;
138362    return 0;
138363  }
138364#endif
138365  sqlite3_mutex_enter(db->mutex);
138366  pOld = db->pProfileArg;
138367  db->xProfile = xProfile;
138368  db->pProfileArg = pArg;
138369  sqlite3_mutex_leave(db->mutex);
138370  return pOld;
138371}
138372#endif /* SQLITE_OMIT_DEPRECATED */
138373#endif /* SQLITE_OMIT_TRACE */
138374
138375/*
138376** Register a function to be invoked when a transaction commits.
138377** If the invoked function returns non-zero, then the commit becomes a
138378** rollback.
138379*/
138380SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
138381  sqlite3 *db,              /* Attach the hook to this database */
138382  int (*xCallback)(void*),  /* Function to invoke on each commit */
138383  void *pArg                /* Argument to the function */
138384){
138385  void *pOld;
138386
138387#ifdef SQLITE_ENABLE_API_ARMOR
138388  if( !sqlite3SafetyCheckOk(db) ){
138389    (void)SQLITE_MISUSE_BKPT;
138390    return 0;
138391  }
138392#endif
138393  sqlite3_mutex_enter(db->mutex);
138394  pOld = db->pCommitArg;
138395  db->xCommitCallback = xCallback;
138396  db->pCommitArg = pArg;
138397  sqlite3_mutex_leave(db->mutex);
138398  return pOld;
138399}
138400
138401/*
138402** Register a callback to be invoked each time a row is updated,
138403** inserted or deleted using this database connection.
138404*/
138405SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
138406  sqlite3 *db,              /* Attach the hook to this database */
138407  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
138408  void *pArg                /* Argument to the function */
138409){
138410  void *pRet;
138411
138412#ifdef SQLITE_ENABLE_API_ARMOR
138413  if( !sqlite3SafetyCheckOk(db) ){
138414    (void)SQLITE_MISUSE_BKPT;
138415    return 0;
138416  }
138417#endif
138418  sqlite3_mutex_enter(db->mutex);
138419  pRet = db->pUpdateArg;
138420  db->xUpdateCallback = xCallback;
138421  db->pUpdateArg = pArg;
138422  sqlite3_mutex_leave(db->mutex);
138423  return pRet;
138424}
138425
138426/*
138427** Register a callback to be invoked each time a transaction is rolled
138428** back by this database connection.
138429*/
138430SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
138431  sqlite3 *db,              /* Attach the hook to this database */
138432  void (*xCallback)(void*), /* Callback function */
138433  void *pArg                /* Argument to the function */
138434){
138435  void *pRet;
138436
138437#ifdef SQLITE_ENABLE_API_ARMOR
138438  if( !sqlite3SafetyCheckOk(db) ){
138439    (void)SQLITE_MISUSE_BKPT;
138440    return 0;
138441  }
138442#endif
138443  sqlite3_mutex_enter(db->mutex);
138444  pRet = db->pRollbackArg;
138445  db->xRollbackCallback = xCallback;
138446  db->pRollbackArg = pArg;
138447  sqlite3_mutex_leave(db->mutex);
138448  return pRet;
138449}
138450
138451#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
138452/*
138453** Register a callback to be invoked each time a row is updated,
138454** inserted or deleted using this database connection.
138455*/
138456SQLITE_API void *SQLITE_STDCALL sqlite3_preupdate_hook(
138457  sqlite3 *db,              /* Attach the hook to this database */
138458  void(*xCallback)(         /* Callback function */
138459    void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
138460  void *pArg                /* First callback argument */
138461){
138462  void *pRet;
138463  sqlite3_mutex_enter(db->mutex);
138464  pRet = db->pPreUpdateArg;
138465  db->xPreUpdateCallback = xCallback;
138466  db->pPreUpdateArg = pArg;
138467  sqlite3_mutex_leave(db->mutex);
138468  return pRet;
138469}
138470#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
138471
138472#ifndef SQLITE_OMIT_WAL
138473/*
138474** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
138475** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
138476** is greater than sqlite3.pWalArg cast to an integer (the value configured by
138477** wal_autocheckpoint()).
138478*/
138479SQLITE_PRIVATE int sqlite3WalDefaultHook(
138480  void *pClientData,     /* Argument */
138481  sqlite3 *db,           /* Connection */
138482  const char *zDb,       /* Database */
138483  int nFrame             /* Size of WAL */
138484){
138485  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
138486    sqlite3BeginBenignMalloc();
138487    sqlite3_wal_checkpoint(db, zDb);
138488    sqlite3EndBenignMalloc();
138489  }
138490  return SQLITE_OK;
138491}
138492#endif /* SQLITE_OMIT_WAL */
138493
138494/*
138495** Configure an sqlite3_wal_hook() callback to automatically checkpoint
138496** a database after committing a transaction if there are nFrame or
138497** more frames in the log file. Passing zero or a negative value as the
138498** nFrame parameter disables automatic checkpoints entirely.
138499**
138500** The callback registered by this function replaces any existing callback
138501** registered using sqlite3_wal_hook(). Likewise, registering a callback
138502** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
138503** configured by this function.
138504*/
138505SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
138506#ifdef SQLITE_OMIT_WAL
138507  UNUSED_PARAMETER(db);
138508  UNUSED_PARAMETER(nFrame);
138509#else
138510#ifdef SQLITE_ENABLE_API_ARMOR
138511  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138512#endif
138513  if( nFrame>0 ){
138514    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
138515  }else{
138516    sqlite3_wal_hook(db, 0, 0);
138517  }
138518#endif
138519  return SQLITE_OK;
138520}
138521
138522/*
138523** Register a callback to be invoked each time a transaction is written
138524** into the write-ahead-log by this database connection.
138525*/
138526SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
138527  sqlite3 *db,                    /* Attach the hook to this db handle */
138528  int(*xCallback)(void *, sqlite3*, const char*, int),
138529  void *pArg                      /* First argument passed to xCallback() */
138530){
138531#ifndef SQLITE_OMIT_WAL
138532  void *pRet;
138533#ifdef SQLITE_ENABLE_API_ARMOR
138534  if( !sqlite3SafetyCheckOk(db) ){
138535    (void)SQLITE_MISUSE_BKPT;
138536    return 0;
138537  }
138538#endif
138539  sqlite3_mutex_enter(db->mutex);
138540  pRet = db->pWalArg;
138541  db->xWalCallback = xCallback;
138542  db->pWalArg = pArg;
138543  sqlite3_mutex_leave(db->mutex);
138544  return pRet;
138545#else
138546  return 0;
138547#endif
138548}
138549
138550/*
138551** Checkpoint database zDb.
138552*/
138553SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
138554  sqlite3 *db,                    /* Database handle */
138555  const char *zDb,                /* Name of attached database (or NULL) */
138556  int eMode,                      /* SQLITE_CHECKPOINT_* value */
138557  int *pnLog,                     /* OUT: Size of WAL log in frames */
138558  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
138559){
138560#ifdef SQLITE_OMIT_WAL
138561  return SQLITE_OK;
138562#else
138563  int rc;                         /* Return code */
138564  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
138565
138566#ifdef SQLITE_ENABLE_API_ARMOR
138567  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138568#endif
138569
138570  /* Initialize the output variables to -1 in case an error occurs. */
138571  if( pnLog ) *pnLog = -1;
138572  if( pnCkpt ) *pnCkpt = -1;
138573
138574  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
138575  assert( SQLITE_CHECKPOINT_FULL==1 );
138576  assert( SQLITE_CHECKPOINT_RESTART==2 );
138577  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
138578  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
138579    /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
138580    ** mode: */
138581    return SQLITE_MISUSE;
138582  }
138583
138584  sqlite3_mutex_enter(db->mutex);
138585  if( zDb && zDb[0] ){
138586    iDb = sqlite3FindDbName(db, zDb);
138587  }
138588  if( iDb<0 ){
138589    rc = SQLITE_ERROR;
138590    sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
138591  }else{
138592    db->busyHandler.nBusy = 0;
138593    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
138594    sqlite3Error(db, rc);
138595  }
138596  rc = sqlite3ApiExit(db, rc);
138597  sqlite3_mutex_leave(db->mutex);
138598  return rc;
138599#endif
138600}
138601
138602
138603/*
138604** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
138605** to contains a zero-length string, all attached databases are
138606** checkpointed.
138607*/
138608SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
138609  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
138610  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
138611  return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
138612}
138613
138614#ifndef SQLITE_OMIT_WAL
138615/*
138616** Run a checkpoint on database iDb. This is a no-op if database iDb is
138617** not currently open in WAL mode.
138618**
138619** If a transaction is open on the database being checkpointed, this
138620** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
138621** an error occurs while running the checkpoint, an SQLite error code is
138622** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
138623**
138624** The mutex on database handle db should be held by the caller. The mutex
138625** associated with the specific b-tree being checkpointed is taken by
138626** this function while the checkpoint is running.
138627**
138628** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
138629** checkpointed. If an error is encountered it is returned immediately -
138630** no attempt is made to checkpoint any remaining databases.
138631**
138632** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
138633*/
138634SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
138635  int rc = SQLITE_OK;             /* Return code */
138636  int i;                          /* Used to iterate through attached dbs */
138637  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
138638
138639  assert( sqlite3_mutex_held(db->mutex) );
138640  assert( !pnLog || *pnLog==-1 );
138641  assert( !pnCkpt || *pnCkpt==-1 );
138642
138643  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
138644    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
138645      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
138646      pnLog = 0;
138647      pnCkpt = 0;
138648      if( rc==SQLITE_BUSY ){
138649        bBusy = 1;
138650        rc = SQLITE_OK;
138651      }
138652    }
138653  }
138654
138655  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
138656}
138657#endif /* SQLITE_OMIT_WAL */
138658
138659/*
138660** This function returns true if main-memory should be used instead of
138661** a temporary file for transient pager files and statement journals.
138662** The value returned depends on the value of db->temp_store (runtime
138663** parameter) and the compile time value of SQLITE_TEMP_STORE. The
138664** following table describes the relationship between these two values
138665** and this functions return value.
138666**
138667**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
138668**   -----------------     --------------     ------------------------------
138669**   0                     any                file      (return 0)
138670**   1                     1                  file      (return 0)
138671**   1                     2                  memory    (return 1)
138672**   1                     0                  file      (return 0)
138673**   2                     1                  file      (return 0)
138674**   2                     2                  memory    (return 1)
138675**   2                     0                  memory    (return 1)
138676**   3                     any                memory    (return 1)
138677*/
138678SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
138679#if SQLITE_TEMP_STORE==1
138680  return ( db->temp_store==2 );
138681#endif
138682#if SQLITE_TEMP_STORE==2
138683  return ( db->temp_store!=1 );
138684#endif
138685#if SQLITE_TEMP_STORE==3
138686  UNUSED_PARAMETER(db);
138687  return 1;
138688#endif
138689#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
138690  UNUSED_PARAMETER(db);
138691  return 0;
138692#endif
138693}
138694
138695/*
138696** Return UTF-8 encoded English language explanation of the most recent
138697** error.
138698*/
138699SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
138700  const char *z;
138701  if( !db ){
138702    return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
138703  }
138704  if( !sqlite3SafetyCheckSickOrOk(db) ){
138705    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
138706  }
138707  sqlite3_mutex_enter(db->mutex);
138708  if( db->mallocFailed ){
138709    z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
138710  }else{
138711    testcase( db->pErr==0 );
138712    z = (char*)sqlite3_value_text(db->pErr);
138713    assert( !db->mallocFailed );
138714    if( z==0 ){
138715      z = sqlite3ErrStr(db->errCode);
138716    }
138717  }
138718  sqlite3_mutex_leave(db->mutex);
138719  return z;
138720}
138721
138722#ifndef SQLITE_OMIT_UTF16
138723/*
138724** Return UTF-16 encoded English language explanation of the most recent
138725** error.
138726*/
138727SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
138728  static const u16 outOfMem[] = {
138729    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
138730  };
138731  static const u16 misuse[] = {
138732    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
138733    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
138734    'c', 'a', 'l', 'l', 'e', 'd', ' ',
138735    'o', 'u', 't', ' ',
138736    'o', 'f', ' ',
138737    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
138738  };
138739
138740  const void *z;
138741  if( !db ){
138742    return (void *)outOfMem;
138743  }
138744  if( !sqlite3SafetyCheckSickOrOk(db) ){
138745    return (void *)misuse;
138746  }
138747  sqlite3_mutex_enter(db->mutex);
138748  if( db->mallocFailed ){
138749    z = (void *)outOfMem;
138750  }else{
138751    z = sqlite3_value_text16(db->pErr);
138752    if( z==0 ){
138753      sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
138754      z = sqlite3_value_text16(db->pErr);
138755    }
138756    /* A malloc() may have failed within the call to sqlite3_value_text16()
138757    ** above. If this is the case, then the db->mallocFailed flag needs to
138758    ** be cleared before returning. Do this directly, instead of via
138759    ** sqlite3ApiExit(), to avoid setting the database handle error message.
138760    */
138761    sqlite3OomClear(db);
138762  }
138763  sqlite3_mutex_leave(db->mutex);
138764  return z;
138765}
138766#endif /* SQLITE_OMIT_UTF16 */
138767
138768/*
138769** Return the most recent error code generated by an SQLite routine. If NULL is
138770** passed to this function, we assume a malloc() failed during sqlite3_open().
138771*/
138772SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
138773  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
138774    return SQLITE_MISUSE_BKPT;
138775  }
138776  if( !db || db->mallocFailed ){
138777    return SQLITE_NOMEM_BKPT;
138778  }
138779  return db->errCode & db->errMask;
138780}
138781SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
138782  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
138783    return SQLITE_MISUSE_BKPT;
138784  }
138785  if( !db || db->mallocFailed ){
138786    return SQLITE_NOMEM_BKPT;
138787  }
138788  return db->errCode;
138789}
138790SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3 *db){
138791  return db ? db->iSysErrno : 0;
138792}
138793
138794/*
138795** Return a string that describes the kind of error specified in the
138796** argument.  For now, this simply calls the internal sqlite3ErrStr()
138797** function.
138798*/
138799SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
138800  return sqlite3ErrStr(rc);
138801}
138802
138803/*
138804** Create a new collating function for database "db".  The name is zName
138805** and the encoding is enc.
138806*/
138807static int createCollation(
138808  sqlite3* db,
138809  const char *zName,
138810  u8 enc,
138811  void* pCtx,
138812  int(*xCompare)(void*,int,const void*,int,const void*),
138813  void(*xDel)(void*)
138814){
138815  CollSeq *pColl;
138816  int enc2;
138817
138818  assert( sqlite3_mutex_held(db->mutex) );
138819
138820  /* If SQLITE_UTF16 is specified as the encoding type, transform this
138821  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
138822  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
138823  */
138824  enc2 = enc;
138825  testcase( enc2==SQLITE_UTF16 );
138826  testcase( enc2==SQLITE_UTF16_ALIGNED );
138827  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
138828    enc2 = SQLITE_UTF16NATIVE;
138829  }
138830  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
138831    return SQLITE_MISUSE_BKPT;
138832  }
138833
138834  /* Check if this call is removing or replacing an existing collation
138835  ** sequence. If so, and there are active VMs, return busy. If there
138836  ** are no active VMs, invalidate any pre-compiled statements.
138837  */
138838  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
138839  if( pColl && pColl->xCmp ){
138840    if( db->nVdbeActive ){
138841      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
138842        "unable to delete/modify collation sequence due to active statements");
138843      return SQLITE_BUSY;
138844    }
138845    sqlite3ExpirePreparedStatements(db);
138846
138847    /* If collation sequence pColl was created directly by a call to
138848    ** sqlite3_create_collation, and not generated by synthCollSeq(),
138849    ** then any copies made by synthCollSeq() need to be invalidated.
138850    ** Also, collation destructor - CollSeq.xDel() - function may need
138851    ** to be called.
138852    */
138853    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
138854      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
138855      int j;
138856      for(j=0; j<3; j++){
138857        CollSeq *p = &aColl[j];
138858        if( p->enc==pColl->enc ){
138859          if( p->xDel ){
138860            p->xDel(p->pUser);
138861          }
138862          p->xCmp = 0;
138863        }
138864      }
138865    }
138866  }
138867
138868  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
138869  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
138870  pColl->xCmp = xCompare;
138871  pColl->pUser = pCtx;
138872  pColl->xDel = xDel;
138873  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
138874  sqlite3Error(db, SQLITE_OK);
138875  return SQLITE_OK;
138876}
138877
138878
138879/*
138880** This array defines hard upper bounds on limit values.  The
138881** initializer must be kept in sync with the SQLITE_LIMIT_*
138882** #defines in sqlite3.h.
138883*/
138884static const int aHardLimit[] = {
138885  SQLITE_MAX_LENGTH,
138886  SQLITE_MAX_SQL_LENGTH,
138887  SQLITE_MAX_COLUMN,
138888  SQLITE_MAX_EXPR_DEPTH,
138889  SQLITE_MAX_COMPOUND_SELECT,
138890  SQLITE_MAX_VDBE_OP,
138891  SQLITE_MAX_FUNCTION_ARG,
138892  SQLITE_MAX_ATTACHED,
138893  SQLITE_MAX_LIKE_PATTERN_LENGTH,
138894  SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
138895  SQLITE_MAX_TRIGGER_DEPTH,
138896  SQLITE_MAX_WORKER_THREADS,
138897};
138898
138899/*
138900** Make sure the hard limits are set to reasonable values
138901*/
138902#if SQLITE_MAX_LENGTH<100
138903# error SQLITE_MAX_LENGTH must be at least 100
138904#endif
138905#if SQLITE_MAX_SQL_LENGTH<100
138906# error SQLITE_MAX_SQL_LENGTH must be at least 100
138907#endif
138908#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
138909# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
138910#endif
138911#if SQLITE_MAX_COMPOUND_SELECT<2
138912# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
138913#endif
138914#if SQLITE_MAX_VDBE_OP<40
138915# error SQLITE_MAX_VDBE_OP must be at least 40
138916#endif
138917#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
138918# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
138919#endif
138920#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
138921# error SQLITE_MAX_ATTACHED must be between 0 and 125
138922#endif
138923#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
138924# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
138925#endif
138926#if SQLITE_MAX_COLUMN>32767
138927# error SQLITE_MAX_COLUMN must not exceed 32767
138928#endif
138929#if SQLITE_MAX_TRIGGER_DEPTH<1
138930# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
138931#endif
138932#if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
138933# error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
138934#endif
138935
138936
138937/*
138938** Change the value of a limit.  Report the old value.
138939** If an invalid limit index is supplied, report -1.
138940** Make no changes but still report the old value if the
138941** new limit is negative.
138942**
138943** A new lower limit does not shrink existing constructs.
138944** It merely prevents new constructs that exceed the limit
138945** from forming.
138946*/
138947SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
138948  int oldLimit;
138949
138950#ifdef SQLITE_ENABLE_API_ARMOR
138951  if( !sqlite3SafetyCheckOk(db) ){
138952    (void)SQLITE_MISUSE_BKPT;
138953    return -1;
138954  }
138955#endif
138956
138957  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
138958  ** there is a hard upper bound set at compile-time by a C preprocessor
138959  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
138960  ** "_MAX_".)
138961  */
138962  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
138963  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
138964  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
138965  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
138966  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
138967  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
138968  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
138969  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
138970  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
138971                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
138972  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
138973  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
138974  assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
138975  assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
138976
138977
138978  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
138979    return -1;
138980  }
138981  oldLimit = db->aLimit[limitId];
138982  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
138983    if( newLimit>aHardLimit[limitId] ){
138984      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
138985    }
138986    db->aLimit[limitId] = newLimit;
138987  }
138988  return oldLimit;                     /* IMP: R-53341-35419 */
138989}
138990
138991/*
138992** This function is used to parse both URIs and non-URI filenames passed by the
138993** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
138994** URIs specified as part of ATTACH statements.
138995**
138996** The first argument to this function is the name of the VFS to use (or
138997** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
138998** query parameter. The second argument contains the URI (or non-URI filename)
138999** itself. When this function is called the *pFlags variable should contain
139000** the default flags to open the database handle with. The value stored in
139001** *pFlags may be updated before returning if the URI filename contains
139002** "cache=xxx" or "mode=xxx" query parameters.
139003**
139004** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
139005** the VFS that should be used to open the database file. *pzFile is set to
139006** point to a buffer containing the name of the file to open. It is the
139007** responsibility of the caller to eventually call sqlite3_free() to release
139008** this buffer.
139009**
139010** If an error occurs, then an SQLite error code is returned and *pzErrMsg
139011** may be set to point to a buffer containing an English language error
139012** message. It is the responsibility of the caller to eventually release
139013** this buffer by calling sqlite3_free().
139014*/
139015SQLITE_PRIVATE int sqlite3ParseUri(
139016  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
139017  const char *zUri,               /* Nul-terminated URI to parse */
139018  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
139019  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
139020  char **pzFile,                  /* OUT: Filename component of URI */
139021  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
139022){
139023  int rc = SQLITE_OK;
139024  unsigned int flags = *pFlags;
139025  const char *zVfs = zDefaultVfs;
139026  char *zFile;
139027  char c;
139028  int nUri = sqlite3Strlen30(zUri);
139029
139030  assert( *pzErrMsg==0 );
139031
139032  if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
139033            || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
139034   && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
139035  ){
139036    char *zOpt;
139037    int eState;                   /* Parser state when parsing URI */
139038    int iIn;                      /* Input character index */
139039    int iOut = 0;                 /* Output character index */
139040    u64 nByte = nUri+2;           /* Bytes of space to allocate */
139041
139042    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
139043    ** method that there may be extra parameters following the file-name.  */
139044    flags |= SQLITE_OPEN_URI;
139045
139046    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
139047    zFile = sqlite3_malloc64(nByte);
139048    if( !zFile ) return SQLITE_NOMEM_BKPT;
139049
139050    iIn = 5;
139051#ifdef SQLITE_ALLOW_URI_AUTHORITY
139052    if( strncmp(zUri+5, "///", 3)==0 ){
139053      iIn = 7;
139054      /* The following condition causes URIs with five leading / characters
139055      ** like file://///host/path to be converted into UNCs like //host/path.
139056      ** The correct URI for that UNC has only two or four leading / characters
139057      ** file://host/path or file:////host/path.  But 5 leading slashes is a
139058      ** common error, we are told, so we handle it as a special case. */
139059      if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
139060    }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
139061      iIn = 16;
139062    }
139063#else
139064    /* Discard the scheme and authority segments of the URI. */
139065    if( zUri[5]=='/' && zUri[6]=='/' ){
139066      iIn = 7;
139067      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
139068      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
139069        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
139070            iIn-7, &zUri[7]);
139071        rc = SQLITE_ERROR;
139072        goto parse_uri_out;
139073      }
139074    }
139075#endif
139076
139077    /* Copy the filename and any query parameters into the zFile buffer.
139078    ** Decode %HH escape codes along the way.
139079    **
139080    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
139081    ** on the parsing context. As follows:
139082    **
139083    **   0: Parsing file-name.
139084    **   1: Parsing name section of a name=value query parameter.
139085    **   2: Parsing value section of a name=value query parameter.
139086    */
139087    eState = 0;
139088    while( (c = zUri[iIn])!=0 && c!='#' ){
139089      iIn++;
139090      if( c=='%'
139091       && sqlite3Isxdigit(zUri[iIn])
139092       && sqlite3Isxdigit(zUri[iIn+1])
139093      ){
139094        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
139095        octet += sqlite3HexToInt(zUri[iIn++]);
139096
139097        assert( octet>=0 && octet<256 );
139098        if( octet==0 ){
139099          /* This branch is taken when "%00" appears within the URI. In this
139100          ** case we ignore all text in the remainder of the path, name or
139101          ** value currently being parsed. So ignore the current character
139102          ** and skip to the next "?", "=" or "&", as appropriate. */
139103          while( (c = zUri[iIn])!=0 && c!='#'
139104              && (eState!=0 || c!='?')
139105              && (eState!=1 || (c!='=' && c!='&'))
139106              && (eState!=2 || c!='&')
139107          ){
139108            iIn++;
139109          }
139110          continue;
139111        }
139112        c = octet;
139113      }else if( eState==1 && (c=='&' || c=='=') ){
139114        if( zFile[iOut-1]==0 ){
139115          /* An empty option name. Ignore this option altogether. */
139116          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
139117          continue;
139118        }
139119        if( c=='&' ){
139120          zFile[iOut++] = '\0';
139121        }else{
139122          eState = 2;
139123        }
139124        c = 0;
139125      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
139126        c = 0;
139127        eState = 1;
139128      }
139129      zFile[iOut++] = c;
139130    }
139131    if( eState==1 ) zFile[iOut++] = '\0';
139132    zFile[iOut++] = '\0';
139133    zFile[iOut++] = '\0';
139134
139135    /* Check if there were any options specified that should be interpreted
139136    ** here. Options that are interpreted here include "vfs" and those that
139137    ** correspond to flags that may be passed to the sqlite3_open_v2()
139138    ** method. */
139139    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
139140    while( zOpt[0] ){
139141      int nOpt = sqlite3Strlen30(zOpt);
139142      char *zVal = &zOpt[nOpt+1];
139143      int nVal = sqlite3Strlen30(zVal);
139144
139145      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
139146        zVfs = zVal;
139147      }else{
139148        struct OpenMode {
139149          const char *z;
139150          int mode;
139151        } *aMode = 0;
139152        char *zModeType = 0;
139153        int mask = 0;
139154        int limit = 0;
139155
139156        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
139157          static struct OpenMode aCacheMode[] = {
139158            { "shared",  SQLITE_OPEN_SHAREDCACHE },
139159            { "private", SQLITE_OPEN_PRIVATECACHE },
139160            { 0, 0 }
139161          };
139162
139163          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
139164          aMode = aCacheMode;
139165          limit = mask;
139166          zModeType = "cache";
139167        }
139168        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
139169          static struct OpenMode aOpenMode[] = {
139170            { "ro",  SQLITE_OPEN_READONLY },
139171            { "rw",  SQLITE_OPEN_READWRITE },
139172            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
139173            { "memory", SQLITE_OPEN_MEMORY },
139174            { 0, 0 }
139175          };
139176
139177          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
139178                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
139179          aMode = aOpenMode;
139180          limit = mask & flags;
139181          zModeType = "access";
139182        }
139183
139184        if( aMode ){
139185          int i;
139186          int mode = 0;
139187          for(i=0; aMode[i].z; i++){
139188            const char *z = aMode[i].z;
139189            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
139190              mode = aMode[i].mode;
139191              break;
139192            }
139193          }
139194          if( mode==0 ){
139195            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
139196            rc = SQLITE_ERROR;
139197            goto parse_uri_out;
139198          }
139199          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
139200            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
139201                                        zModeType, zVal);
139202            rc = SQLITE_PERM;
139203            goto parse_uri_out;
139204          }
139205          flags = (flags & ~mask) | mode;
139206        }
139207      }
139208
139209      zOpt = &zVal[nVal+1];
139210    }
139211
139212  }else{
139213    zFile = sqlite3_malloc64(nUri+2);
139214    if( !zFile ) return SQLITE_NOMEM_BKPT;
139215    memcpy(zFile, zUri, nUri);
139216    zFile[nUri] = '\0';
139217    zFile[nUri+1] = '\0';
139218    flags &= ~SQLITE_OPEN_URI;
139219  }
139220
139221  *ppVfs = sqlite3_vfs_find(zVfs);
139222  if( *ppVfs==0 ){
139223    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
139224    rc = SQLITE_ERROR;
139225  }
139226 parse_uri_out:
139227  if( rc!=SQLITE_OK ){
139228    sqlite3_free(zFile);
139229    zFile = 0;
139230  }
139231  *pFlags = flags;
139232  *pzFile = zFile;
139233  return rc;
139234}
139235
139236
139237/*
139238** This routine does the work of opening a database on behalf of
139239** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
139240** is UTF-8 encoded.
139241*/
139242static int openDatabase(
139243  const char *zFilename, /* Database filename UTF-8 encoded */
139244  sqlite3 **ppDb,        /* OUT: Returned database handle */
139245  unsigned int flags,    /* Operational flags */
139246  const char *zVfs       /* Name of the VFS to use */
139247){
139248  sqlite3 *db;                    /* Store allocated handle here */
139249  int rc;                         /* Return code */
139250  int isThreadsafe;               /* True for threadsafe connections */
139251  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
139252  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
139253
139254#ifdef SQLITE_ENABLE_API_ARMOR
139255  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
139256#endif
139257  *ppDb = 0;
139258#ifndef SQLITE_OMIT_AUTOINIT
139259  rc = sqlite3_initialize();
139260  if( rc ) return rc;
139261#endif
139262
139263  /* Only allow sensible combinations of bits in the flags argument.
139264  ** Throw an error if any non-sense combination is used.  If we
139265  ** do not block illegal combinations here, it could trigger
139266  ** assert() statements in deeper layers.  Sensible combinations
139267  ** are:
139268  **
139269  **  1:  SQLITE_OPEN_READONLY
139270  **  2:  SQLITE_OPEN_READWRITE
139271  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
139272  */
139273  assert( SQLITE_OPEN_READONLY  == 0x01 );
139274  assert( SQLITE_OPEN_READWRITE == 0x02 );
139275  assert( SQLITE_OPEN_CREATE    == 0x04 );
139276  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
139277  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
139278  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
139279  if( ((1<<(flags&7)) & 0x46)==0 ){
139280    return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
139281  }
139282
139283  if( sqlite3GlobalConfig.bCoreMutex==0 ){
139284    isThreadsafe = 0;
139285  }else if( flags & SQLITE_OPEN_NOMUTEX ){
139286    isThreadsafe = 0;
139287  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
139288    isThreadsafe = 1;
139289  }else{
139290    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
139291  }
139292  if( flags & SQLITE_OPEN_PRIVATECACHE ){
139293    flags &= ~SQLITE_OPEN_SHAREDCACHE;
139294  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
139295    flags |= SQLITE_OPEN_SHAREDCACHE;
139296  }
139297
139298  /* Remove harmful bits from the flags parameter
139299  **
139300  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
139301  ** dealt with in the previous code block.  Besides these, the only
139302  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
139303  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
139304  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
139305  ** off all other flags.
139306  */
139307  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
139308               SQLITE_OPEN_EXCLUSIVE |
139309               SQLITE_OPEN_MAIN_DB |
139310               SQLITE_OPEN_TEMP_DB |
139311               SQLITE_OPEN_TRANSIENT_DB |
139312               SQLITE_OPEN_MAIN_JOURNAL |
139313               SQLITE_OPEN_TEMP_JOURNAL |
139314               SQLITE_OPEN_SUBJOURNAL |
139315               SQLITE_OPEN_MASTER_JOURNAL |
139316               SQLITE_OPEN_NOMUTEX |
139317               SQLITE_OPEN_FULLMUTEX |
139318               SQLITE_OPEN_WAL
139319             );
139320
139321  /* Allocate the sqlite data structure */
139322  db = sqlite3MallocZero( sizeof(sqlite3) );
139323  if( db==0 ) goto opendb_out;
139324  if( isThreadsafe ){
139325    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
139326    if( db->mutex==0 ){
139327      sqlite3_free(db);
139328      db = 0;
139329      goto opendb_out;
139330    }
139331  }
139332  sqlite3_mutex_enter(db->mutex);
139333  db->errMask = 0xff;
139334  db->nDb = 2;
139335  db->magic = SQLITE_MAGIC_BUSY;
139336  db->aDb = db->aDbStatic;
139337
139338  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
139339  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
139340  db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
139341  db->autoCommit = 1;
139342  db->nextAutovac = -1;
139343  db->szMmap = sqlite3GlobalConfig.szMmap;
139344  db->nextPagesize = 0;
139345  db->nMaxSorterMmap = 0x7FFFFFFF;
139346  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
139347#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
139348                 | SQLITE_AutoIndex
139349#endif
139350#if SQLITE_DEFAULT_CKPTFULLFSYNC
139351                 | SQLITE_CkptFullFSync
139352#endif
139353#if SQLITE_DEFAULT_FILE_FORMAT<4
139354                 | SQLITE_LegacyFileFmt
139355#endif
139356#ifdef SQLITE_ENABLE_LOAD_EXTENSION
139357                 | SQLITE_LoadExtension
139358#endif
139359#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
139360                 | SQLITE_RecTriggers
139361#endif
139362#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
139363                 | SQLITE_ForeignKeys
139364#endif
139365#if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
139366                 | SQLITE_ReverseOrder
139367#endif
139368#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
139369                 | SQLITE_CellSizeCk
139370#endif
139371#if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
139372                 | SQLITE_Fts3Tokenizer
139373#endif
139374      ;
139375  sqlite3HashInit(&db->aCollSeq);
139376#ifndef SQLITE_OMIT_VIRTUALTABLE
139377  sqlite3HashInit(&db->aModule);
139378#endif
139379
139380  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
139381  ** and UTF-16, so add a version for each to avoid any unnecessary
139382  ** conversions. The only error that can occur here is a malloc() failure.
139383  **
139384  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
139385  ** functions:
139386  */
139387  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
139388  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
139389  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
139390  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
139391  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
139392  if( db->mallocFailed ){
139393    goto opendb_out;
139394  }
139395  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
139396  ** strings is BINARY.
139397  */
139398  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
139399  assert( db->pDfltColl!=0 );
139400
139401  /* Parse the filename/URI argument. */
139402  db->openFlags = flags;
139403  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
139404  if( rc!=SQLITE_OK ){
139405    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
139406    sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
139407    sqlite3_free(zErrMsg);
139408    goto opendb_out;
139409  }
139410
139411  /* Open the backend database driver */
139412  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
139413                        flags | SQLITE_OPEN_MAIN_DB);
139414  if( rc!=SQLITE_OK ){
139415    if( rc==SQLITE_IOERR_NOMEM ){
139416      rc = SQLITE_NOMEM_BKPT;
139417    }
139418    sqlite3Error(db, rc);
139419    goto opendb_out;
139420  }
139421  sqlite3BtreeEnter(db->aDb[0].pBt);
139422  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
139423  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
139424  sqlite3BtreeLeave(db->aDb[0].pBt);
139425  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
139426
139427  /* The default safety_level for the main database is FULL; for the temp
139428  ** database it is OFF. This matches the pager layer defaults.
139429  */
139430  db->aDb[0].zName = "main";
139431  db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
139432  db->aDb[1].zName = "temp";
139433  db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
139434
139435  db->magic = SQLITE_MAGIC_OPEN;
139436  if( db->mallocFailed ){
139437    goto opendb_out;
139438  }
139439
139440  /* Register all built-in functions, but do not attempt to read the
139441  ** database schema yet. This is delayed until the first time the database
139442  ** is accessed.
139443  */
139444  sqlite3Error(db, SQLITE_OK);
139445  sqlite3RegisterPerConnectionBuiltinFunctions(db);
139446
139447  /* Load automatic extensions - extensions that have been registered
139448  ** using the sqlite3_automatic_extension() API.
139449  */
139450  rc = sqlite3_errcode(db);
139451  if( rc==SQLITE_OK ){
139452    sqlite3AutoLoadExtensions(db);
139453    rc = sqlite3_errcode(db);
139454    if( rc!=SQLITE_OK ){
139455      goto opendb_out;
139456    }
139457  }
139458
139459#ifdef SQLITE_ENABLE_FTS1
139460  if( !db->mallocFailed ){
139461    extern int sqlite3Fts1Init(sqlite3*);
139462    rc = sqlite3Fts1Init(db);
139463  }
139464#endif
139465
139466#ifdef SQLITE_ENABLE_FTS2
139467  if( !db->mallocFailed && rc==SQLITE_OK ){
139468    extern int sqlite3Fts2Init(sqlite3*);
139469    rc = sqlite3Fts2Init(db);
139470  }
139471#endif
139472
139473#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
139474  if( !db->mallocFailed && rc==SQLITE_OK ){
139475    rc = sqlite3Fts3Init(db);
139476  }
139477#endif
139478
139479#ifdef SQLITE_ENABLE_FTS5
139480  if( !db->mallocFailed && rc==SQLITE_OK ){
139481    rc = sqlite3Fts5Init(db);
139482  }
139483#endif
139484
139485#ifdef SQLITE_ENABLE_ICU
139486  if( !db->mallocFailed && rc==SQLITE_OK ){
139487    rc = sqlite3IcuInit(db);
139488  }
139489#endif
139490
139491#ifdef SQLITE_ENABLE_RTREE
139492  if( !db->mallocFailed && rc==SQLITE_OK){
139493    rc = sqlite3RtreeInit(db);
139494  }
139495#endif
139496
139497#ifdef SQLITE_ENABLE_DBSTAT_VTAB
139498  if( !db->mallocFailed && rc==SQLITE_OK){
139499    rc = sqlite3DbstatRegister(db);
139500  }
139501#endif
139502
139503#ifdef SQLITE_ENABLE_JSON1
139504  if( !db->mallocFailed && rc==SQLITE_OK){
139505    rc = sqlite3Json1Init(db);
139506  }
139507#endif
139508
139509  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
139510  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
139511  ** mode.  Doing nothing at all also makes NORMAL the default.
139512  */
139513#ifdef SQLITE_DEFAULT_LOCKING_MODE
139514  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
139515  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
139516                          SQLITE_DEFAULT_LOCKING_MODE);
139517#endif
139518
139519  if( rc ) sqlite3Error(db, rc);
139520
139521  /* Enable the lookaside-malloc subsystem */
139522  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
139523                        sqlite3GlobalConfig.nLookaside);
139524
139525  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
139526
139527opendb_out:
139528  if( db ){
139529    assert( db->mutex!=0 || isThreadsafe==0
139530           || sqlite3GlobalConfig.bFullMutex==0 );
139531    sqlite3_mutex_leave(db->mutex);
139532  }
139533  rc = sqlite3_errcode(db);
139534  assert( db!=0 || rc==SQLITE_NOMEM );
139535  if( rc==SQLITE_NOMEM ){
139536    sqlite3_close(db);
139537    db = 0;
139538  }else if( rc!=SQLITE_OK ){
139539    db->magic = SQLITE_MAGIC_SICK;
139540  }
139541  *ppDb = db;
139542#ifdef SQLITE_ENABLE_SQLLOG
139543  if( sqlite3GlobalConfig.xSqllog ){
139544    /* Opening a db handle. Fourth parameter is passed 0. */
139545    void *pArg = sqlite3GlobalConfig.pSqllogArg;
139546    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
139547  }
139548#endif
139549#if defined(SQLITE_HAS_CODEC)
139550  if( rc==SQLITE_OK ){
139551    const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
139552    if( zHexKey && zHexKey[0] ){
139553      u8 iByte;
139554      int i;
139555      char zKey[40];
139556      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
139557        iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
139558        if( (i&1)!=0 ) zKey[i/2] = iByte;
139559      }
139560      sqlite3_key_v2(db, 0, zKey, i/2);
139561    }
139562  }
139563#endif
139564  sqlite3_free(zOpen);
139565  return rc & 0xff;
139566}
139567
139568/*
139569** Open a new database handle.
139570*/
139571SQLITE_API int SQLITE_STDCALL sqlite3_open(
139572  const char *zFilename,
139573  sqlite3 **ppDb
139574){
139575  return openDatabase(zFilename, ppDb,
139576                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
139577}
139578SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
139579  const char *filename,   /* Database filename (UTF-8) */
139580  sqlite3 **ppDb,         /* OUT: SQLite db handle */
139581  int flags,              /* Flags */
139582  const char *zVfs        /* Name of VFS module to use */
139583){
139584  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
139585}
139586
139587#ifndef SQLITE_OMIT_UTF16
139588/*
139589** Open a new database handle.
139590*/
139591SQLITE_API int SQLITE_STDCALL sqlite3_open16(
139592  const void *zFilename,
139593  sqlite3 **ppDb
139594){
139595  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
139596  sqlite3_value *pVal;
139597  int rc;
139598
139599#ifdef SQLITE_ENABLE_API_ARMOR
139600  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
139601#endif
139602  *ppDb = 0;
139603#ifndef SQLITE_OMIT_AUTOINIT
139604  rc = sqlite3_initialize();
139605  if( rc ) return rc;
139606#endif
139607  if( zFilename==0 ) zFilename = "\000\000";
139608  pVal = sqlite3ValueNew(0);
139609  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
139610  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
139611  if( zFilename8 ){
139612    rc = openDatabase(zFilename8, ppDb,
139613                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
139614    assert( *ppDb || rc==SQLITE_NOMEM );
139615    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
139616      SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
139617    }
139618  }else{
139619    rc = SQLITE_NOMEM_BKPT;
139620  }
139621  sqlite3ValueFree(pVal);
139622
139623  return rc & 0xff;
139624}
139625#endif /* SQLITE_OMIT_UTF16 */
139626
139627/*
139628** Register a new collation sequence with the database handle db.
139629*/
139630SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
139631  sqlite3* db,
139632  const char *zName,
139633  int enc,
139634  void* pCtx,
139635  int(*xCompare)(void*,int,const void*,int,const void*)
139636){
139637  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
139638}
139639
139640/*
139641** Register a new collation sequence with the database handle db.
139642*/
139643SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
139644  sqlite3* db,
139645  const char *zName,
139646  int enc,
139647  void* pCtx,
139648  int(*xCompare)(void*,int,const void*,int,const void*),
139649  void(*xDel)(void*)
139650){
139651  int rc;
139652
139653#ifdef SQLITE_ENABLE_API_ARMOR
139654  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139655#endif
139656  sqlite3_mutex_enter(db->mutex);
139657  assert( !db->mallocFailed );
139658  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
139659  rc = sqlite3ApiExit(db, rc);
139660  sqlite3_mutex_leave(db->mutex);
139661  return rc;
139662}
139663
139664#ifndef SQLITE_OMIT_UTF16
139665/*
139666** Register a new collation sequence with the database handle db.
139667*/
139668SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
139669  sqlite3* db,
139670  const void *zName,
139671  int enc,
139672  void* pCtx,
139673  int(*xCompare)(void*,int,const void*,int,const void*)
139674){
139675  int rc = SQLITE_OK;
139676  char *zName8;
139677
139678#ifdef SQLITE_ENABLE_API_ARMOR
139679  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139680#endif
139681  sqlite3_mutex_enter(db->mutex);
139682  assert( !db->mallocFailed );
139683  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
139684  if( zName8 ){
139685    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
139686    sqlite3DbFree(db, zName8);
139687  }
139688  rc = sqlite3ApiExit(db, rc);
139689  sqlite3_mutex_leave(db->mutex);
139690  return rc;
139691}
139692#endif /* SQLITE_OMIT_UTF16 */
139693
139694/*
139695** Register a collation sequence factory callback with the database handle
139696** db. Replace any previously installed collation sequence factory.
139697*/
139698SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
139699  sqlite3 *db,
139700  void *pCollNeededArg,
139701  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
139702){
139703#ifdef SQLITE_ENABLE_API_ARMOR
139704  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139705#endif
139706  sqlite3_mutex_enter(db->mutex);
139707  db->xCollNeeded = xCollNeeded;
139708  db->xCollNeeded16 = 0;
139709  db->pCollNeededArg = pCollNeededArg;
139710  sqlite3_mutex_leave(db->mutex);
139711  return SQLITE_OK;
139712}
139713
139714#ifndef SQLITE_OMIT_UTF16
139715/*
139716** Register a collation sequence factory callback with the database handle
139717** db. Replace any previously installed collation sequence factory.
139718*/
139719SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
139720  sqlite3 *db,
139721  void *pCollNeededArg,
139722  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
139723){
139724#ifdef SQLITE_ENABLE_API_ARMOR
139725  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139726#endif
139727  sqlite3_mutex_enter(db->mutex);
139728  db->xCollNeeded = 0;
139729  db->xCollNeeded16 = xCollNeeded16;
139730  db->pCollNeededArg = pCollNeededArg;
139731  sqlite3_mutex_leave(db->mutex);
139732  return SQLITE_OK;
139733}
139734#endif /* SQLITE_OMIT_UTF16 */
139735
139736#ifndef SQLITE_OMIT_DEPRECATED
139737/*
139738** This function is now an anachronism. It used to be used to recover from a
139739** malloc() failure, but SQLite now does this automatically.
139740*/
139741SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
139742  return SQLITE_OK;
139743}
139744#endif
139745
139746/*
139747** Test to see whether or not the database connection is in autocommit
139748** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
139749** by default.  Autocommit is disabled by a BEGIN statement and reenabled
139750** by the next COMMIT or ROLLBACK.
139751*/
139752SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
139753#ifdef SQLITE_ENABLE_API_ARMOR
139754  if( !sqlite3SafetyCheckOk(db) ){
139755    (void)SQLITE_MISUSE_BKPT;
139756    return 0;
139757  }
139758#endif
139759  return db->autoCommit;
139760}
139761
139762/*
139763** The following routines are substitutes for constants SQLITE_CORRUPT,
139764** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
139765** constants.  They serve two purposes:
139766**
139767**   1.  Serve as a convenient place to set a breakpoint in a debugger
139768**       to detect when version error conditions occurs.
139769**
139770**   2.  Invoke sqlite3_log() to provide the source code location where
139771**       a low-level error is first detected.
139772*/
139773static int reportError(int iErr, int lineno, const char *zType){
139774  sqlite3_log(iErr, "%s at line %d of [%.10s]",
139775              zType, lineno, 20+sqlite3_sourceid());
139776  return iErr;
139777}
139778SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
139779  testcase( sqlite3GlobalConfig.xLog!=0 );
139780  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
139781}
139782SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
139783  testcase( sqlite3GlobalConfig.xLog!=0 );
139784  return reportError(SQLITE_MISUSE, lineno, "misuse");
139785}
139786SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
139787  testcase( sqlite3GlobalConfig.xLog!=0 );
139788  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
139789}
139790#ifdef SQLITE_DEBUG
139791SQLITE_PRIVATE int sqlite3NomemError(int lineno){
139792  testcase( sqlite3GlobalConfig.xLog!=0 );
139793  return reportError(SQLITE_NOMEM, lineno, "OOM");
139794}
139795SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
139796  testcase( sqlite3GlobalConfig.xLog!=0 );
139797  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
139798}
139799#endif
139800
139801#ifndef SQLITE_OMIT_DEPRECATED
139802/*
139803** This is a convenience routine that makes sure that all thread-specific
139804** data for this thread has been deallocated.
139805**
139806** SQLite no longer uses thread-specific data so this routine is now a
139807** no-op.  It is retained for historical compatibility.
139808*/
139809SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
139810}
139811#endif
139812
139813/*
139814** Return meta information about a specific column of a database table.
139815** See comment in sqlite3.h (sqlite.h.in) for details.
139816*/
139817SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
139818  sqlite3 *db,                /* Connection handle */
139819  const char *zDbName,        /* Database name or NULL */
139820  const char *zTableName,     /* Table name */
139821  const char *zColumnName,    /* Column name */
139822  char const **pzDataType,    /* OUTPUT: Declared data type */
139823  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
139824  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
139825  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
139826  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
139827){
139828  int rc;
139829  char *zErrMsg = 0;
139830  Table *pTab = 0;
139831  Column *pCol = 0;
139832  int iCol = 0;
139833  char const *zDataType = 0;
139834  char const *zCollSeq = 0;
139835  int notnull = 0;
139836  int primarykey = 0;
139837  int autoinc = 0;
139838
139839
139840#ifdef SQLITE_ENABLE_API_ARMOR
139841  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
139842    return SQLITE_MISUSE_BKPT;
139843  }
139844#endif
139845
139846  /* Ensure the database schema has been loaded */
139847  sqlite3_mutex_enter(db->mutex);
139848  sqlite3BtreeEnterAll(db);
139849  rc = sqlite3Init(db, &zErrMsg);
139850  if( SQLITE_OK!=rc ){
139851    goto error_out;
139852  }
139853
139854  /* Locate the table in question */
139855  pTab = sqlite3FindTable(db, zTableName, zDbName);
139856  if( !pTab || pTab->pSelect ){
139857    pTab = 0;
139858    goto error_out;
139859  }
139860
139861  /* Find the column for which info is requested */
139862  if( zColumnName==0 ){
139863    /* Query for existance of table only */
139864  }else{
139865    for(iCol=0; iCol<pTab->nCol; iCol++){
139866      pCol = &pTab->aCol[iCol];
139867      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
139868        break;
139869      }
139870    }
139871    if( iCol==pTab->nCol ){
139872      if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
139873        iCol = pTab->iPKey;
139874        pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
139875      }else{
139876        pTab = 0;
139877        goto error_out;
139878      }
139879    }
139880  }
139881
139882  /* The following block stores the meta information that will be returned
139883  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
139884  ** and autoinc. At this point there are two possibilities:
139885  **
139886  **     1. The specified column name was rowid", "oid" or "_rowid_"
139887  **        and there is no explicitly declared IPK column.
139888  **
139889  **     2. The table is not a view and the column name identified an
139890  **        explicitly declared column. Copy meta information from *pCol.
139891  */
139892  if( pCol ){
139893    zDataType = sqlite3ColumnType(pCol,0);
139894    zCollSeq = pCol->zColl;
139895    notnull = pCol->notNull!=0;
139896    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
139897    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
139898  }else{
139899    zDataType = "INTEGER";
139900    primarykey = 1;
139901  }
139902  if( !zCollSeq ){
139903    zCollSeq = sqlite3StrBINARY;
139904  }
139905
139906error_out:
139907  sqlite3BtreeLeaveAll(db);
139908
139909  /* Whether the function call succeeded or failed, set the output parameters
139910  ** to whatever their local counterparts contain. If an error did occur,
139911  ** this has the effect of zeroing all output parameters.
139912  */
139913  if( pzDataType ) *pzDataType = zDataType;
139914  if( pzCollSeq ) *pzCollSeq = zCollSeq;
139915  if( pNotNull ) *pNotNull = notnull;
139916  if( pPrimaryKey ) *pPrimaryKey = primarykey;
139917  if( pAutoinc ) *pAutoinc = autoinc;
139918
139919  if( SQLITE_OK==rc && !pTab ){
139920    sqlite3DbFree(db, zErrMsg);
139921    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
139922        zColumnName);
139923    rc = SQLITE_ERROR;
139924  }
139925  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
139926  sqlite3DbFree(db, zErrMsg);
139927  rc = sqlite3ApiExit(db, rc);
139928  sqlite3_mutex_leave(db->mutex);
139929  return rc;
139930}
139931
139932/*
139933** Sleep for a little while.  Return the amount of time slept.
139934*/
139935SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
139936  sqlite3_vfs *pVfs;
139937  int rc;
139938  pVfs = sqlite3_vfs_find(0);
139939  if( pVfs==0 ) return 0;
139940
139941  /* This function works in milliseconds, but the underlying OsSleep()
139942  ** API uses microseconds. Hence the 1000's.
139943  */
139944  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
139945  return rc;
139946}
139947
139948/*
139949** Enable or disable the extended result codes.
139950*/
139951SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
139952#ifdef SQLITE_ENABLE_API_ARMOR
139953  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139954#endif
139955  sqlite3_mutex_enter(db->mutex);
139956  db->errMask = onoff ? 0xffffffff : 0xff;
139957  sqlite3_mutex_leave(db->mutex);
139958  return SQLITE_OK;
139959}
139960
139961/*
139962** Invoke the xFileControl method on a particular database.
139963*/
139964SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
139965  int rc = SQLITE_ERROR;
139966  Btree *pBtree;
139967
139968#ifdef SQLITE_ENABLE_API_ARMOR
139969  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139970#endif
139971  sqlite3_mutex_enter(db->mutex);
139972  pBtree = sqlite3DbNameToBtree(db, zDbName);
139973  if( pBtree ){
139974    Pager *pPager;
139975    sqlite3_file *fd;
139976    sqlite3BtreeEnter(pBtree);
139977    pPager = sqlite3BtreePager(pBtree);
139978    assert( pPager!=0 );
139979    fd = sqlite3PagerFile(pPager);
139980    assert( fd!=0 );
139981    if( op==SQLITE_FCNTL_FILE_POINTER ){
139982      *(sqlite3_file**)pArg = fd;
139983      rc = SQLITE_OK;
139984    }else if( op==SQLITE_FCNTL_VFS_POINTER ){
139985      *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
139986      rc = SQLITE_OK;
139987    }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
139988      *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
139989      rc = SQLITE_OK;
139990    }else if( fd->pMethods ){
139991      rc = sqlite3OsFileControl(fd, op, pArg);
139992    }else{
139993      rc = SQLITE_NOTFOUND;
139994    }
139995    sqlite3BtreeLeave(pBtree);
139996  }
139997  sqlite3_mutex_leave(db->mutex);
139998  return rc;
139999}
140000
140001/*
140002** Interface to the testing logic.
140003*/
140004SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
140005  int rc = 0;
140006#ifdef SQLITE_OMIT_BUILTIN_TEST
140007  UNUSED_PARAMETER(op);
140008#else
140009  va_list ap;
140010  va_start(ap, op);
140011  switch( op ){
140012
140013    /*
140014    ** Save the current state of the PRNG.
140015    */
140016    case SQLITE_TESTCTRL_PRNG_SAVE: {
140017      sqlite3PrngSaveState();
140018      break;
140019    }
140020
140021    /*
140022    ** Restore the state of the PRNG to the last state saved using
140023    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
140024    ** this verb acts like PRNG_RESET.
140025    */
140026    case SQLITE_TESTCTRL_PRNG_RESTORE: {
140027      sqlite3PrngRestoreState();
140028      break;
140029    }
140030
140031    /*
140032    ** Reset the PRNG back to its uninitialized state.  The next call
140033    ** to sqlite3_randomness() will reseed the PRNG using a single call
140034    ** to the xRandomness method of the default VFS.
140035    */
140036    case SQLITE_TESTCTRL_PRNG_RESET: {
140037      sqlite3_randomness(0,0);
140038      break;
140039    }
140040
140041    /*
140042    **  sqlite3_test_control(BITVEC_TEST, size, program)
140043    **
140044    ** Run a test against a Bitvec object of size.  The program argument
140045    ** is an array of integers that defines the test.  Return -1 on a
140046    ** memory allocation error, 0 on success, or non-zero for an error.
140047    ** See the sqlite3BitvecBuiltinTest() for additional information.
140048    */
140049    case SQLITE_TESTCTRL_BITVEC_TEST: {
140050      int sz = va_arg(ap, int);
140051      int *aProg = va_arg(ap, int*);
140052      rc = sqlite3BitvecBuiltinTest(sz, aProg);
140053      break;
140054    }
140055
140056    /*
140057    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
140058    **
140059    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
140060    ** if xCallback is not NULL.
140061    **
140062    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
140063    ** is called immediately after installing the new callback and the return
140064    ** value from sqlite3FaultSim(0) becomes the return from
140065    ** sqlite3_test_control().
140066    */
140067    case SQLITE_TESTCTRL_FAULT_INSTALL: {
140068      /* MSVC is picky about pulling func ptrs from va lists.
140069      ** http://support.microsoft.com/kb/47961
140070      ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
140071      */
140072      typedef int(*TESTCALLBACKFUNC_t)(int);
140073      sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
140074      rc = sqlite3FaultSim(0);
140075      break;
140076    }
140077
140078    /*
140079    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
140080    **
140081    ** Register hooks to call to indicate which malloc() failures
140082    ** are benign.
140083    */
140084    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
140085      typedef void (*void_function)(void);
140086      void_function xBenignBegin;
140087      void_function xBenignEnd;
140088      xBenignBegin = va_arg(ap, void_function);
140089      xBenignEnd = va_arg(ap, void_function);
140090      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
140091      break;
140092    }
140093
140094    /*
140095    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
140096    **
140097    ** Set the PENDING byte to the value in the argument, if X>0.
140098    ** Make no changes if X==0.  Return the value of the pending byte
140099    ** as it existing before this routine was called.
140100    **
140101    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
140102    ** an incompatible database file format.  Changing the PENDING byte
140103    ** while any database connection is open results in undefined and
140104    ** deleterious behavior.
140105    */
140106    case SQLITE_TESTCTRL_PENDING_BYTE: {
140107      rc = PENDING_BYTE;
140108#ifndef SQLITE_OMIT_WSD
140109      {
140110        unsigned int newVal = va_arg(ap, unsigned int);
140111        if( newVal ) sqlite3PendingByte = newVal;
140112      }
140113#endif
140114      break;
140115    }
140116
140117    /*
140118    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
140119    **
140120    ** This action provides a run-time test to see whether or not
140121    ** assert() was enabled at compile-time.  If X is true and assert()
140122    ** is enabled, then the return value is true.  If X is true and
140123    ** assert() is disabled, then the return value is zero.  If X is
140124    ** false and assert() is enabled, then the assertion fires and the
140125    ** process aborts.  If X is false and assert() is disabled, then the
140126    ** return value is zero.
140127    */
140128    case SQLITE_TESTCTRL_ASSERT: {
140129      volatile int x = 0;
140130      assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
140131      rc = x;
140132      break;
140133    }
140134
140135
140136    /*
140137    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
140138    **
140139    ** This action provides a run-time test to see how the ALWAYS and
140140    ** NEVER macros were defined at compile-time.
140141    **
140142    ** The return value is ALWAYS(X).
140143    **
140144    ** The recommended test is X==2.  If the return value is 2, that means
140145    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
140146    ** default setting.  If the return value is 1, then ALWAYS() is either
140147    ** hard-coded to true or else it asserts if its argument is false.
140148    ** The first behavior (hard-coded to true) is the case if
140149    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
140150    ** behavior (assert if the argument to ALWAYS() is false) is the case if
140151    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
140152    **
140153    ** The run-time test procedure might look something like this:
140154    **
140155    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
140156    **      // ALWAYS() and NEVER() are no-op pass-through macros
140157    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
140158    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
140159    **    }else{
140160    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
140161    **    }
140162    */
140163    case SQLITE_TESTCTRL_ALWAYS: {
140164      int x = va_arg(ap,int);
140165      rc = ALWAYS(x);
140166      break;
140167    }
140168
140169    /*
140170    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
140171    **
140172    ** The integer returned reveals the byte-order of the computer on which
140173    ** SQLite is running:
140174    **
140175    **       1     big-endian,    determined at run-time
140176    **      10     little-endian, determined at run-time
140177    **  432101     big-endian,    determined at compile-time
140178    **  123410     little-endian, determined at compile-time
140179    */
140180    case SQLITE_TESTCTRL_BYTEORDER: {
140181      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
140182      break;
140183    }
140184
140185    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
140186    **
140187    ** Set the nReserve size to N for the main database on the database
140188    ** connection db.
140189    */
140190    case SQLITE_TESTCTRL_RESERVE: {
140191      sqlite3 *db = va_arg(ap, sqlite3*);
140192      int x = va_arg(ap,int);
140193      sqlite3_mutex_enter(db->mutex);
140194      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
140195      sqlite3_mutex_leave(db->mutex);
140196      break;
140197    }
140198
140199    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
140200    **
140201    ** Enable or disable various optimizations for testing purposes.  The
140202    ** argument N is a bitmask of optimizations to be disabled.  For normal
140203    ** operation N should be 0.  The idea is that a test program (like the
140204    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
140205    ** with various optimizations disabled to verify that the same answer
140206    ** is obtained in every case.
140207    */
140208    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
140209      sqlite3 *db = va_arg(ap, sqlite3*);
140210      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
140211      break;
140212    }
140213
140214#ifdef SQLITE_N_KEYWORD
140215    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
140216    **
140217    ** If zWord is a keyword recognized by the parser, then return the
140218    ** number of keywords.  Or if zWord is not a keyword, return 0.
140219    **
140220    ** This test feature is only available in the amalgamation since
140221    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
140222    ** is built using separate source files.
140223    */
140224    case SQLITE_TESTCTRL_ISKEYWORD: {
140225      const char *zWord = va_arg(ap, const char*);
140226      int n = sqlite3Strlen30(zWord);
140227      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
140228      break;
140229    }
140230#endif
140231
140232    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
140233    **
140234    ** Pass pFree into sqlite3ScratchFree().
140235    ** If sz>0 then allocate a scratch buffer into pNew.
140236    */
140237    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
140238      void *pFree, **ppNew;
140239      int sz;
140240      sz = va_arg(ap, int);
140241      ppNew = va_arg(ap, void**);
140242      pFree = va_arg(ap, void*);
140243      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
140244      sqlite3ScratchFree(pFree);
140245      break;
140246    }
140247
140248    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
140249    **
140250    ** If parameter onoff is non-zero, configure the wrappers so that all
140251    ** subsequent calls to localtime() and variants fail. If onoff is zero,
140252    ** undo this setting.
140253    */
140254    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
140255      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
140256      break;
140257    }
140258
140259    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
140260    **
140261    ** Set or clear a flag that indicates that the database file is always well-
140262    ** formed and never corrupt.  This flag is clear by default, indicating that
140263    ** database files might have arbitrary corruption.  Setting the flag during
140264    ** testing causes certain assert() statements in the code to be activated
140265    ** that demonstrat invariants on well-formed database files.
140266    */
140267    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
140268      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
140269      break;
140270    }
140271
140272
140273    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
140274    **
140275    ** Set the VDBE coverage callback function to xCallback with context
140276    ** pointer ptr.
140277    */
140278    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
140279#ifdef SQLITE_VDBE_COVERAGE
140280      typedef void (*branch_callback)(void*,int,u8,u8);
140281      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
140282      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
140283#endif
140284      break;
140285    }
140286
140287    /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
140288    case SQLITE_TESTCTRL_SORTER_MMAP: {
140289      sqlite3 *db = va_arg(ap, sqlite3*);
140290      db->nMaxSorterMmap = va_arg(ap, int);
140291      break;
140292    }
140293
140294    /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
140295    **
140296    ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
140297    ** not.
140298    */
140299    case SQLITE_TESTCTRL_ISINIT: {
140300      if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
140301      break;
140302    }
140303
140304    /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
140305    **
140306    ** This test control is used to create imposter tables.  "db" is a pointer
140307    ** to the database connection.  dbName is the database name (ex: "main" or
140308    ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
140309    ** or off.  "tnum" is the root page of the b-tree to which the imposter
140310    ** table should connect.
140311    **
140312    ** Enable imposter mode only when the schema has already been parsed.  Then
140313    ** run a single CREATE TABLE statement to construct the imposter table in
140314    ** the parsed schema.  Then turn imposter mode back off again.
140315    **
140316    ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
140317    ** the schema to be reparsed the next time it is needed.  This has the
140318    ** effect of erasing all imposter tables.
140319    */
140320    case SQLITE_TESTCTRL_IMPOSTER: {
140321      sqlite3 *db = va_arg(ap, sqlite3*);
140322      sqlite3_mutex_enter(db->mutex);
140323      db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
140324      db->init.busy = db->init.imposterTable = va_arg(ap,int);
140325      db->init.newTnum = va_arg(ap,int);
140326      if( db->init.busy==0 && db->init.newTnum>0 ){
140327        sqlite3ResetAllSchemasOfConnection(db);
140328      }
140329      sqlite3_mutex_leave(db->mutex);
140330      break;
140331    }
140332  }
140333  va_end(ap);
140334#endif /* SQLITE_OMIT_BUILTIN_TEST */
140335  return rc;
140336}
140337
140338/*
140339** This is a utility routine, useful to VFS implementations, that checks
140340** to see if a database file was a URI that contained a specific query
140341** parameter, and if so obtains the value of the query parameter.
140342**
140343** The zFilename argument is the filename pointer passed into the xOpen()
140344** method of a VFS implementation.  The zParam argument is the name of the
140345** query parameter we seek.  This routine returns the value of the zParam
140346** parameter if it exists.  If the parameter does not exist, this routine
140347** returns a NULL pointer.
140348*/
140349SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
140350  if( zFilename==0 || zParam==0 ) return 0;
140351  zFilename += sqlite3Strlen30(zFilename) + 1;
140352  while( zFilename[0] ){
140353    int x = strcmp(zFilename, zParam);
140354    zFilename += sqlite3Strlen30(zFilename) + 1;
140355    if( x==0 ) return zFilename;
140356    zFilename += sqlite3Strlen30(zFilename) + 1;
140357  }
140358  return 0;
140359}
140360
140361/*
140362** Return a boolean value for a query parameter.
140363*/
140364SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
140365  const char *z = sqlite3_uri_parameter(zFilename, zParam);
140366  bDflt = bDflt!=0;
140367  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
140368}
140369
140370/*
140371** Return a 64-bit integer value for a query parameter.
140372*/
140373SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
140374  const char *zFilename,    /* Filename as passed to xOpen */
140375  const char *zParam,       /* URI parameter sought */
140376  sqlite3_int64 bDflt       /* return if parameter is missing */
140377){
140378  const char *z = sqlite3_uri_parameter(zFilename, zParam);
140379  sqlite3_int64 v;
140380  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
140381    bDflt = v;
140382  }
140383  return bDflt;
140384}
140385
140386/*
140387** Return the Btree pointer identified by zDbName.  Return NULL if not found.
140388*/
140389SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
140390  int i;
140391  for(i=0; i<db->nDb; i++){
140392    if( db->aDb[i].pBt
140393     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
140394    ){
140395      return db->aDb[i].pBt;
140396    }
140397  }
140398  return 0;
140399}
140400
140401/*
140402** Return the filename of the database associated with a database
140403** connection.
140404*/
140405SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
140406  Btree *pBt;
140407#ifdef SQLITE_ENABLE_API_ARMOR
140408  if( !sqlite3SafetyCheckOk(db) ){
140409    (void)SQLITE_MISUSE_BKPT;
140410    return 0;
140411  }
140412#endif
140413  pBt = sqlite3DbNameToBtree(db, zDbName);
140414  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
140415}
140416
140417/*
140418** Return 1 if database is read-only or 0 if read/write.  Return -1 if
140419** no such database exists.
140420*/
140421SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
140422  Btree *pBt;
140423#ifdef SQLITE_ENABLE_API_ARMOR
140424  if( !sqlite3SafetyCheckOk(db) ){
140425    (void)SQLITE_MISUSE_BKPT;
140426    return -1;
140427  }
140428#endif
140429  pBt = sqlite3DbNameToBtree(db, zDbName);
140430  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
140431}
140432
140433#ifdef SQLITE_ENABLE_SNAPSHOT
140434/*
140435** Obtain a snapshot handle for the snapshot of database zDb currently
140436** being read by handle db.
140437*/
140438SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_get(
140439  sqlite3 *db,
140440  const char *zDb,
140441  sqlite3_snapshot **ppSnapshot
140442){
140443  int rc = SQLITE_ERROR;
140444#ifndef SQLITE_OMIT_WAL
140445  int iDb;
140446
140447#ifdef SQLITE_ENABLE_API_ARMOR
140448  if( !sqlite3SafetyCheckOk(db) ){
140449    return SQLITE_MISUSE_BKPT;
140450  }
140451#endif
140452  sqlite3_mutex_enter(db->mutex);
140453
140454  iDb = sqlite3FindDbName(db, zDb);
140455  if( iDb==0 || iDb>1 ){
140456    Btree *pBt = db->aDb[iDb].pBt;
140457    if( 0==sqlite3BtreeIsInTrans(pBt) ){
140458      rc = sqlite3BtreeBeginTrans(pBt, 0);
140459      if( rc==SQLITE_OK ){
140460        rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
140461      }
140462    }
140463  }
140464
140465  sqlite3_mutex_leave(db->mutex);
140466#endif   /* SQLITE_OMIT_WAL */
140467  return rc;
140468}
140469
140470/*
140471** Open a read-transaction on the snapshot idendified by pSnapshot.
140472*/
140473SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_open(
140474  sqlite3 *db,
140475  const char *zDb,
140476  sqlite3_snapshot *pSnapshot
140477){
140478  int rc = SQLITE_ERROR;
140479#ifndef SQLITE_OMIT_WAL
140480
140481#ifdef SQLITE_ENABLE_API_ARMOR
140482  if( !sqlite3SafetyCheckOk(db) ){
140483    return SQLITE_MISUSE_BKPT;
140484  }
140485#endif
140486  sqlite3_mutex_enter(db->mutex);
140487  if( db->autoCommit==0 ){
140488    int iDb;
140489    iDb = sqlite3FindDbName(db, zDb);
140490    if( iDb==0 || iDb>1 ){
140491      Btree *pBt = db->aDb[iDb].pBt;
140492      if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
140493        rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
140494        if( rc==SQLITE_OK ){
140495          rc = sqlite3BtreeBeginTrans(pBt, 0);
140496          sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
140497        }
140498      }
140499    }
140500  }
140501
140502  sqlite3_mutex_leave(db->mutex);
140503#endif   /* SQLITE_OMIT_WAL */
140504  return rc;
140505}
140506
140507/*
140508** Free a snapshot handle obtained from sqlite3_snapshot_get().
140509*/
140510SQLITE_API void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
140511  sqlite3_free(pSnapshot);
140512}
140513#endif /* SQLITE_ENABLE_SNAPSHOT */
140514
140515/************** End of main.c ************************************************/
140516/************** Begin file notify.c ******************************************/
140517/*
140518** 2009 March 3
140519**
140520** The author disclaims copyright to this source code.  In place of
140521** a legal notice, here is a blessing:
140522**
140523**    May you do good and not evil.
140524**    May you find forgiveness for yourself and forgive others.
140525**    May you share freely, never taking more than you give.
140526**
140527*************************************************************************
140528**
140529** This file contains the implementation of the sqlite3_unlock_notify()
140530** API method and its associated functionality.
140531*/
140532/* #include "sqliteInt.h" */
140533/* #include "btreeInt.h" */
140534
140535/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
140536#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
140537
140538/*
140539** Public interfaces:
140540**
140541**   sqlite3ConnectionBlocked()
140542**   sqlite3ConnectionUnlocked()
140543**   sqlite3ConnectionClosed()
140544**   sqlite3_unlock_notify()
140545*/
140546
140547#define assertMutexHeld() \
140548  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
140549
140550/*
140551** Head of a linked list of all sqlite3 objects created by this process
140552** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
140553** is not NULL. This variable may only accessed while the STATIC_MASTER
140554** mutex is held.
140555*/
140556static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
140557
140558#ifndef NDEBUG
140559/*
140560** This function is a complex assert() that verifies the following
140561** properties of the blocked connections list:
140562**
140563**   1) Each entry in the list has a non-NULL value for either
140564**      pUnlockConnection or pBlockingConnection, or both.
140565**
140566**   2) All entries in the list that share a common value for
140567**      xUnlockNotify are grouped together.
140568**
140569**   3) If the argument db is not NULL, then none of the entries in the
140570**      blocked connections list have pUnlockConnection or pBlockingConnection
140571**      set to db. This is used when closing connection db.
140572*/
140573static void checkListProperties(sqlite3 *db){
140574  sqlite3 *p;
140575  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
140576    int seen = 0;
140577    sqlite3 *p2;
140578
140579    /* Verify property (1) */
140580    assert( p->pUnlockConnection || p->pBlockingConnection );
140581
140582    /* Verify property (2) */
140583    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
140584      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
140585      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
140586      assert( db==0 || p->pUnlockConnection!=db );
140587      assert( db==0 || p->pBlockingConnection!=db );
140588    }
140589  }
140590}
140591#else
140592# define checkListProperties(x)
140593#endif
140594
140595/*
140596** Remove connection db from the blocked connections list. If connection
140597** db is not currently a part of the list, this function is a no-op.
140598*/
140599static void removeFromBlockedList(sqlite3 *db){
140600  sqlite3 **pp;
140601  assertMutexHeld();
140602  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
140603    if( *pp==db ){
140604      *pp = (*pp)->pNextBlocked;
140605      break;
140606    }
140607  }
140608}
140609
140610/*
140611** Add connection db to the blocked connections list. It is assumed
140612** that it is not already a part of the list.
140613*/
140614static void addToBlockedList(sqlite3 *db){
140615  sqlite3 **pp;
140616  assertMutexHeld();
140617  for(
140618    pp=&sqlite3BlockedList;
140619    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
140620    pp=&(*pp)->pNextBlocked
140621  );
140622  db->pNextBlocked = *pp;
140623  *pp = db;
140624}
140625
140626/*
140627** Obtain the STATIC_MASTER mutex.
140628*/
140629static void enterMutex(void){
140630  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
140631  checkListProperties(0);
140632}
140633
140634/*
140635** Release the STATIC_MASTER mutex.
140636*/
140637static void leaveMutex(void){
140638  assertMutexHeld();
140639  checkListProperties(0);
140640  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
140641}
140642
140643/*
140644** Register an unlock-notify callback.
140645**
140646** This is called after connection "db" has attempted some operation
140647** but has received an SQLITE_LOCKED error because another connection
140648** (call it pOther) in the same process was busy using the same shared
140649** cache.  pOther is found by looking at db->pBlockingConnection.
140650**
140651** If there is no blocking connection, the callback is invoked immediately,
140652** before this routine returns.
140653**
140654** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
140655** a deadlock.
140656**
140657** Otherwise, make arrangements to invoke xNotify when pOther drops
140658** its locks.
140659**
140660** Each call to this routine overrides any prior callbacks registered
140661** on the same "db".  If xNotify==0 then any prior callbacks are immediately
140662** cancelled.
140663*/
140664SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
140665  sqlite3 *db,
140666  void (*xNotify)(void **, int),
140667  void *pArg
140668){
140669  int rc = SQLITE_OK;
140670
140671  sqlite3_mutex_enter(db->mutex);
140672  enterMutex();
140673
140674  if( xNotify==0 ){
140675    removeFromBlockedList(db);
140676    db->pBlockingConnection = 0;
140677    db->pUnlockConnection = 0;
140678    db->xUnlockNotify = 0;
140679    db->pUnlockArg = 0;
140680  }else if( 0==db->pBlockingConnection ){
140681    /* The blocking transaction has been concluded. Or there never was a
140682    ** blocking transaction. In either case, invoke the notify callback
140683    ** immediately.
140684    */
140685    xNotify(&pArg, 1);
140686  }else{
140687    sqlite3 *p;
140688
140689    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
140690    if( p ){
140691      rc = SQLITE_LOCKED;              /* Deadlock detected. */
140692    }else{
140693      db->pUnlockConnection = db->pBlockingConnection;
140694      db->xUnlockNotify = xNotify;
140695      db->pUnlockArg = pArg;
140696      removeFromBlockedList(db);
140697      addToBlockedList(db);
140698    }
140699  }
140700
140701  leaveMutex();
140702  assert( !db->mallocFailed );
140703  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
140704  sqlite3_mutex_leave(db->mutex);
140705  return rc;
140706}
140707
140708/*
140709** This function is called while stepping or preparing a statement
140710** associated with connection db. The operation will return SQLITE_LOCKED
140711** to the user because it requires a lock that will not be available
140712** until connection pBlocker concludes its current transaction.
140713*/
140714SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
140715  enterMutex();
140716  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
140717    addToBlockedList(db);
140718  }
140719  db->pBlockingConnection = pBlocker;
140720  leaveMutex();
140721}
140722
140723/*
140724** This function is called when
140725** the transaction opened by database db has just finished. Locks held
140726** by database connection db have been released.
140727**
140728** This function loops through each entry in the blocked connections
140729** list and does the following:
140730**
140731**   1) If the sqlite3.pBlockingConnection member of a list entry is
140732**      set to db, then set pBlockingConnection=0.
140733**
140734**   2) If the sqlite3.pUnlockConnection member of a list entry is
140735**      set to db, then invoke the configured unlock-notify callback and
140736**      set pUnlockConnection=0.
140737**
140738**   3) If the two steps above mean that pBlockingConnection==0 and
140739**      pUnlockConnection==0, remove the entry from the blocked connections
140740**      list.
140741*/
140742SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
140743  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
140744  int nArg = 0;                            /* Number of entries in aArg[] */
140745  sqlite3 **pp;                            /* Iterator variable */
140746  void **aArg;               /* Arguments to the unlock callback */
140747  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
140748  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
140749
140750  aArg = aStatic;
140751  enterMutex();         /* Enter STATIC_MASTER mutex */
140752
140753  /* This loop runs once for each entry in the blocked-connections list. */
140754  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
140755    sqlite3 *p = *pp;
140756
140757    /* Step 1. */
140758    if( p->pBlockingConnection==db ){
140759      p->pBlockingConnection = 0;
140760    }
140761
140762    /* Step 2. */
140763    if( p->pUnlockConnection==db ){
140764      assert( p->xUnlockNotify );
140765      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
140766        xUnlockNotify(aArg, nArg);
140767        nArg = 0;
140768      }
140769
140770      sqlite3BeginBenignMalloc();
140771      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
140772      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
140773      if( (!aDyn && nArg==(int)ArraySize(aStatic))
140774       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
140775      ){
140776        /* The aArg[] array needs to grow. */
140777        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
140778        if( pNew ){
140779          memcpy(pNew, aArg, nArg*sizeof(void *));
140780          sqlite3_free(aDyn);
140781          aDyn = aArg = pNew;
140782        }else{
140783          /* This occurs when the array of context pointers that need to
140784          ** be passed to the unlock-notify callback is larger than the
140785          ** aStatic[] array allocated on the stack and the attempt to
140786          ** allocate a larger array from the heap has failed.
140787          **
140788          ** This is a difficult situation to handle. Returning an error
140789          ** code to the caller is insufficient, as even if an error code
140790          ** is returned the transaction on connection db will still be
140791          ** closed and the unlock-notify callbacks on blocked connections
140792          ** will go unissued. This might cause the application to wait
140793          ** indefinitely for an unlock-notify callback that will never
140794          ** arrive.
140795          **
140796          ** Instead, invoke the unlock-notify callback with the context
140797          ** array already accumulated. We can then clear the array and
140798          ** begin accumulating any further context pointers without
140799          ** requiring any dynamic allocation. This is sub-optimal because
140800          ** it means that instead of one callback with a large array of
140801          ** context pointers the application will receive two or more
140802          ** callbacks with smaller arrays of context pointers, which will
140803          ** reduce the applications ability to prioritize multiple
140804          ** connections. But it is the best that can be done under the
140805          ** circumstances.
140806          */
140807          xUnlockNotify(aArg, nArg);
140808          nArg = 0;
140809        }
140810      }
140811      sqlite3EndBenignMalloc();
140812
140813      aArg[nArg++] = p->pUnlockArg;
140814      xUnlockNotify = p->xUnlockNotify;
140815      p->pUnlockConnection = 0;
140816      p->xUnlockNotify = 0;
140817      p->pUnlockArg = 0;
140818    }
140819
140820    /* Step 3. */
140821    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
140822      /* Remove connection p from the blocked connections list. */
140823      *pp = p->pNextBlocked;
140824      p->pNextBlocked = 0;
140825    }else{
140826      pp = &p->pNextBlocked;
140827    }
140828  }
140829
140830  if( nArg!=0 ){
140831    xUnlockNotify(aArg, nArg);
140832  }
140833  sqlite3_free(aDyn);
140834  leaveMutex();         /* Leave STATIC_MASTER mutex */
140835}
140836
140837/*
140838** This is called when the database connection passed as an argument is
140839** being closed. The connection is removed from the blocked list.
140840*/
140841SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
140842  sqlite3ConnectionUnlocked(db);
140843  enterMutex();
140844  removeFromBlockedList(db);
140845  checkListProperties(db);
140846  leaveMutex();
140847}
140848#endif
140849
140850/************** End of notify.c **********************************************/
140851/************** Begin file fts3.c ********************************************/
140852/*
140853** 2006 Oct 10
140854**
140855** The author disclaims copyright to this source code.  In place of
140856** a legal notice, here is a blessing:
140857**
140858**    May you do good and not evil.
140859**    May you find forgiveness for yourself and forgive others.
140860**    May you share freely, never taking more than you give.
140861**
140862******************************************************************************
140863**
140864** This is an SQLite module implementing full-text search.
140865*/
140866
140867/*
140868** The code in this file is only compiled if:
140869**
140870**     * The FTS3 module is being built as an extension
140871**       (in which case SQLITE_CORE is not defined), or
140872**
140873**     * The FTS3 module is being built into the core of
140874**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140875*/
140876
140877/* The full-text index is stored in a series of b+tree (-like)
140878** structures called segments which map terms to doclists.  The
140879** structures are like b+trees in layout, but are constructed from the
140880** bottom up in optimal fashion and are not updatable.  Since trees
140881** are built from the bottom up, things will be described from the
140882** bottom up.
140883**
140884**
140885**** Varints ****
140886** The basic unit of encoding is a variable-length integer called a
140887** varint.  We encode variable-length integers in little-endian order
140888** using seven bits * per byte as follows:
140889**
140890** KEY:
140891**         A = 0xxxxxxx    7 bits of data and one flag bit
140892**         B = 1xxxxxxx    7 bits of data and one flag bit
140893**
140894**  7 bits - A
140895** 14 bits - BA
140896** 21 bits - BBA
140897** and so on.
140898**
140899** This is similar in concept to how sqlite encodes "varints" but
140900** the encoding is not the same.  SQLite varints are big-endian
140901** are are limited to 9 bytes in length whereas FTS3 varints are
140902** little-endian and can be up to 10 bytes in length (in theory).
140903**
140904** Example encodings:
140905**
140906**     1:    0x01
140907**   127:    0x7f
140908**   128:    0x81 0x00
140909**
140910**
140911**** Document lists ****
140912** A doclist (document list) holds a docid-sorted list of hits for a
140913** given term.  Doclists hold docids and associated token positions.
140914** A docid is the unique integer identifier for a single document.
140915** A position is the index of a word within the document.  The first
140916** word of the document has a position of 0.
140917**
140918** FTS3 used to optionally store character offsets using a compile-time
140919** option.  But that functionality is no longer supported.
140920**
140921** A doclist is stored like this:
140922**
140923** array {
140924**   varint docid;          (delta from previous doclist)
140925**   array {                (position list for column 0)
140926**     varint position;     (2 more than the delta from previous position)
140927**   }
140928**   array {
140929**     varint POS_COLUMN;   (marks start of position list for new column)
140930**     varint column;       (index of new column)
140931**     array {
140932**       varint position;   (2 more than the delta from previous position)
140933**     }
140934**   }
140935**   varint POS_END;        (marks end of positions for this document.
140936** }
140937**
140938** Here, array { X } means zero or more occurrences of X, adjacent in
140939** memory.  A "position" is an index of a token in the token stream
140940** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
140941** in the same logical place as the position element, and act as sentinals
140942** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
140943** The positions numbers are not stored literally but rather as two more
140944** than the difference from the prior position, or the just the position plus
140945** 2 for the first position.  Example:
140946**
140947**   label:       A B C D E  F  G H   I  J K
140948**   value:     123 5 9 1 1 14 35 0 234 72 0
140949**
140950** The 123 value is the first docid.  For column zero in this document
140951** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
140952** at D signals the start of a new column; the 1 at E indicates that the
140953** new column is column number 1.  There are two positions at 12 and 45
140954** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
140955** 234 at I is the delta to next docid (357).  It has one position 70
140956** (72-2) and then terminates with the 0 at K.
140957**
140958** A "position-list" is the list of positions for multiple columns for
140959** a single docid.  A "column-list" is the set of positions for a single
140960** column.  Hence, a position-list consists of one or more column-lists,
140961** a document record consists of a docid followed by a position-list and
140962** a doclist consists of one or more document records.
140963**
140964** A bare doclist omits the position information, becoming an
140965** array of varint-encoded docids.
140966**
140967**** Segment leaf nodes ****
140968** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
140969** nodes are written using LeafWriter, and read using LeafReader (to
140970** iterate through a single leaf node's data) and LeavesReader (to
140971** iterate through a segment's entire leaf layer).  Leaf nodes have
140972** the format:
140973**
140974** varint iHeight;             (height from leaf level, always 0)
140975** varint nTerm;               (length of first term)
140976** char pTerm[nTerm];          (content of first term)
140977** varint nDoclist;            (length of term's associated doclist)
140978** char pDoclist[nDoclist];    (content of doclist)
140979** array {
140980**                             (further terms are delta-encoded)
140981**   varint nPrefix;           (length of prefix shared with previous term)
140982**   varint nSuffix;           (length of unshared suffix)
140983**   char pTermSuffix[nSuffix];(unshared suffix of next term)
140984**   varint nDoclist;          (length of term's associated doclist)
140985**   char pDoclist[nDoclist];  (content of doclist)
140986** }
140987**
140988** Here, array { X } means zero or more occurrences of X, adjacent in
140989** memory.
140990**
140991** Leaf nodes are broken into blocks which are stored contiguously in
140992** the %_segments table in sorted order.  This means that when the end
140993** of a node is reached, the next term is in the node with the next
140994** greater node id.
140995**
140996** New data is spilled to a new leaf node when the current node
140997** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
140998** larger than STANDALONE_MIN (default 1024) is placed in a standalone
140999** node (a leaf node with a single term and doclist).  The goal of
141000** these settings is to pack together groups of small doclists while
141001** making it efficient to directly access large doclists.  The
141002** assumption is that large doclists represent terms which are more
141003** likely to be query targets.
141004**
141005** TODO(shess) It may be useful for blocking decisions to be more
141006** dynamic.  For instance, it may make more sense to have a 2.5k leaf
141007** node rather than splitting into 2k and .5k nodes.  My intuition is
141008** that this might extend through 2x or 4x the pagesize.
141009**
141010**
141011**** Segment interior nodes ****
141012** Segment interior nodes store blockids for subtree nodes and terms
141013** to describe what data is stored by the each subtree.  Interior
141014** nodes are written using InteriorWriter, and read using
141015** InteriorReader.  InteriorWriters are created as needed when
141016** SegmentWriter creates new leaf nodes, or when an interior node
141017** itself grows too big and must be split.  The format of interior
141018** nodes:
141019**
141020** varint iHeight;           (height from leaf level, always >0)
141021** varint iBlockid;          (block id of node's leftmost subtree)
141022** optional {
141023**   varint nTerm;           (length of first term)
141024**   char pTerm[nTerm];      (content of first term)
141025**   array {
141026**                                (further terms are delta-encoded)
141027**     varint nPrefix;            (length of shared prefix with previous term)
141028**     varint nSuffix;            (length of unshared suffix)
141029**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
141030**   }
141031** }
141032**
141033** Here, optional { X } means an optional element, while array { X }
141034** means zero or more occurrences of X, adjacent in memory.
141035**
141036** An interior node encodes n terms separating n+1 subtrees.  The
141037** subtree blocks are contiguous, so only the first subtree's blockid
141038** is encoded.  The subtree at iBlockid will contain all terms less
141039** than the first term encoded (or all terms if no term is encoded).
141040** Otherwise, for terms greater than or equal to pTerm[i] but less
141041** than pTerm[i+1], the subtree for that term will be rooted at
141042** iBlockid+i.  Interior nodes only store enough term data to
141043** distinguish adjacent children (if the rightmost term of the left
141044** child is "something", and the leftmost term of the right child is
141045** "wicked", only "w" is stored).
141046**
141047** New data is spilled to a new interior node at the same height when
141048** the current node exceeds INTERIOR_MAX bytes (default 2048).
141049** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
141050** interior nodes and making the tree too skinny.  The interior nodes
141051** at a given height are naturally tracked by interior nodes at
141052** height+1, and so on.
141053**
141054**
141055**** Segment directory ****
141056** The segment directory in table %_segdir stores meta-information for
141057** merging and deleting segments, and also the root node of the
141058** segment's tree.
141059**
141060** The root node is the top node of the segment's tree after encoding
141061** the entire segment, restricted to ROOT_MAX bytes (default 1024).
141062** This could be either a leaf node or an interior node.  If the top
141063** node requires more than ROOT_MAX bytes, it is flushed to %_segments
141064** and a new root interior node is generated (which should always fit
141065** within ROOT_MAX because it only needs space for 2 varints, the
141066** height and the blockid of the previous root).
141067**
141068** The meta-information in the segment directory is:
141069**   level               - segment level (see below)
141070**   idx                 - index within level
141071**                       - (level,idx uniquely identify a segment)
141072**   start_block         - first leaf node
141073**   leaves_end_block    - last leaf node
141074**   end_block           - last block (including interior nodes)
141075**   root                - contents of root node
141076**
141077** If the root node is a leaf node, then start_block,
141078** leaves_end_block, and end_block are all 0.
141079**
141080**
141081**** Segment merging ****
141082** To amortize update costs, segments are grouped into levels and
141083** merged in batches.  Each increase in level represents exponentially
141084** more documents.
141085**
141086** New documents (actually, document updates) are tokenized and
141087** written individually (using LeafWriter) to a level 0 segment, with
141088** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
141089** level 0 segments are merged into a single level 1 segment.  Level 1
141090** is populated like level 0, and eventually MERGE_COUNT level 1
141091** segments are merged to a single level 2 segment (representing
141092** MERGE_COUNT^2 updates), and so on.
141093**
141094** A segment merge traverses all segments at a given level in
141095** parallel, performing a straightforward sorted merge.  Since segment
141096** leaf nodes are written in to the %_segments table in order, this
141097** merge traverses the underlying sqlite disk structures efficiently.
141098** After the merge, all segment blocks from the merged level are
141099** deleted.
141100**
141101** MERGE_COUNT controls how often we merge segments.  16 seems to be
141102** somewhat of a sweet spot for insertion performance.  32 and 64 show
141103** very similar performance numbers to 16 on insertion, though they're
141104** a tiny bit slower (perhaps due to more overhead in merge-time
141105** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
141106** 16, 2 about 66% slower than 16.
141107**
141108** At query time, high MERGE_COUNT increases the number of segments
141109** which need to be scanned and merged.  For instance, with 100k docs
141110** inserted:
141111**
141112**    MERGE_COUNT   segments
141113**       16           25
141114**        8           12
141115**        4           10
141116**        2            6
141117**
141118** This appears to have only a moderate impact on queries for very
141119** frequent terms (which are somewhat dominated by segment merge
141120** costs), and infrequent and non-existent terms still seem to be fast
141121** even with many segments.
141122**
141123** TODO(shess) That said, it would be nice to have a better query-side
141124** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
141125** optimizations to things like doclist merging will swing the sweet
141126** spot around.
141127**
141128**
141129**
141130**** Handling of deletions and updates ****
141131** Since we're using a segmented structure, with no docid-oriented
141132** index into the term index, we clearly cannot simply update the term
141133** index when a document is deleted or updated.  For deletions, we
141134** write an empty doclist (varint(docid) varint(POS_END)), for updates
141135** we simply write the new doclist.  Segment merges overwrite older
141136** data for a particular docid with newer data, so deletes or updates
141137** will eventually overtake the earlier data and knock it out.  The
141138** query logic likewise merges doclists so that newer data knocks out
141139** older data.
141140*/
141141
141142/************** Include fts3Int.h in the middle of fts3.c ********************/
141143/************** Begin file fts3Int.h *****************************************/
141144/*
141145** 2009 Nov 12
141146**
141147** The author disclaims copyright to this source code.  In place of
141148** a legal notice, here is a blessing:
141149**
141150**    May you do good and not evil.
141151**    May you find forgiveness for yourself and forgive others.
141152**    May you share freely, never taking more than you give.
141153**
141154******************************************************************************
141155**
141156*/
141157#ifndef _FTSINT_H
141158#define _FTSINT_H
141159
141160#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
141161# define NDEBUG 1
141162#endif
141163
141164/* FTS3/FTS4 require virtual tables */
141165#ifdef SQLITE_OMIT_VIRTUALTABLE
141166# undef SQLITE_ENABLE_FTS3
141167# undef SQLITE_ENABLE_FTS4
141168#endif
141169
141170/*
141171** FTS4 is really an extension for FTS3.  It is enabled using the
141172** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
141173** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
141174*/
141175#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
141176# define SQLITE_ENABLE_FTS3
141177#endif
141178
141179#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141180
141181/* If not building as part of the core, include sqlite3ext.h. */
141182#ifndef SQLITE_CORE
141183/* # include "sqlite3ext.h"  */
141184SQLITE_EXTENSION_INIT3
141185#endif
141186
141187/* #include "sqlite3.h" */
141188/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
141189/************** Begin file fts3_tokenizer.h **********************************/
141190/*
141191** 2006 July 10
141192**
141193** The author disclaims copyright to this source code.
141194**
141195*************************************************************************
141196** Defines the interface to tokenizers used by fulltext-search.  There
141197** are three basic components:
141198**
141199** sqlite3_tokenizer_module is a singleton defining the tokenizer
141200** interface functions.  This is essentially the class structure for
141201** tokenizers.
141202**
141203** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
141204** including customization information defined at creation time.
141205**
141206** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
141207** tokens from a particular input.
141208*/
141209#ifndef _FTS3_TOKENIZER_H_
141210#define _FTS3_TOKENIZER_H_
141211
141212/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
141213** If tokenizers are to be allowed to call sqlite3_*() functions, then
141214** we will need a way to register the API consistently.
141215*/
141216/* #include "sqlite3.h" */
141217
141218/*
141219** Structures used by the tokenizer interface. When a new tokenizer
141220** implementation is registered, the caller provides a pointer to
141221** an sqlite3_tokenizer_module containing pointers to the callback
141222** functions that make up an implementation.
141223**
141224** When an fts3 table is created, it passes any arguments passed to
141225** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
141226** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
141227** implementation. The xCreate() function in turn returns an
141228** sqlite3_tokenizer structure representing the specific tokenizer to
141229** be used for the fts3 table (customized by the tokenizer clause arguments).
141230**
141231** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
141232** method is called. It returns an sqlite3_tokenizer_cursor object
141233** that may be used to tokenize a specific input buffer based on
141234** the tokenization rules supplied by a specific sqlite3_tokenizer
141235** object.
141236*/
141237typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
141238typedef struct sqlite3_tokenizer sqlite3_tokenizer;
141239typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
141240
141241struct sqlite3_tokenizer_module {
141242
141243  /*
141244  ** Structure version. Should always be set to 0 or 1.
141245  */
141246  int iVersion;
141247
141248  /*
141249  ** Create a new tokenizer. The values in the argv[] array are the
141250  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
141251  ** TABLE statement that created the fts3 table. For example, if
141252  ** the following SQL is executed:
141253  **
141254  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
141255  **
141256  ** then argc is set to 2, and the argv[] array contains pointers
141257  ** to the strings "arg1" and "arg2".
141258  **
141259  ** This method should return either SQLITE_OK (0), or an SQLite error
141260  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
141261  ** to point at the newly created tokenizer structure. The generic
141262  ** sqlite3_tokenizer.pModule variable should not be initialized by
141263  ** this callback. The caller will do so.
141264  */
141265  int (*xCreate)(
141266    int argc,                           /* Size of argv array */
141267    const char *const*argv,             /* Tokenizer argument strings */
141268    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
141269  );
141270
141271  /*
141272  ** Destroy an existing tokenizer. The fts3 module calls this method
141273  ** exactly once for each successful call to xCreate().
141274  */
141275  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
141276
141277  /*
141278  ** Create a tokenizer cursor to tokenize an input buffer. The caller
141279  ** is responsible for ensuring that the input buffer remains valid
141280  ** until the cursor is closed (using the xClose() method).
141281  */
141282  int (*xOpen)(
141283    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
141284    const char *pInput, int nBytes,      /* Input buffer */
141285    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
141286  );
141287
141288  /*
141289  ** Destroy an existing tokenizer cursor. The fts3 module calls this
141290  ** method exactly once for each successful call to xOpen().
141291  */
141292  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
141293
141294  /*
141295  ** Retrieve the next token from the tokenizer cursor pCursor. This
141296  ** method should either return SQLITE_OK and set the values of the
141297  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
141298  ** the end of the buffer has been reached, or an SQLite error code.
141299  **
141300  ** *ppToken should be set to point at a buffer containing the
141301  ** normalized version of the token (i.e. after any case-folding and/or
141302  ** stemming has been performed). *pnBytes should be set to the length
141303  ** of this buffer in bytes. The input text that generated the token is
141304  ** identified by the byte offsets returned in *piStartOffset and
141305  ** *piEndOffset. *piStartOffset should be set to the index of the first
141306  ** byte of the token in the input buffer. *piEndOffset should be set
141307  ** to the index of the first byte just past the end of the token in
141308  ** the input buffer.
141309  **
141310  ** The buffer *ppToken is set to point at is managed by the tokenizer
141311  ** implementation. It is only required to be valid until the next call
141312  ** to xNext() or xClose().
141313  */
141314  /* TODO(shess) current implementation requires pInput to be
141315  ** nul-terminated.  This should either be fixed, or pInput/nBytes
141316  ** should be converted to zInput.
141317  */
141318  int (*xNext)(
141319    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
141320    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
141321    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
141322    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
141323    int *piPosition      /* OUT: Number of tokens returned before this one */
141324  );
141325
141326  /***********************************************************************
141327  ** Methods below this point are only available if iVersion>=1.
141328  */
141329
141330  /*
141331  ** Configure the language id of a tokenizer cursor.
141332  */
141333  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
141334};
141335
141336struct sqlite3_tokenizer {
141337  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
141338  /* Tokenizer implementations will typically add additional fields */
141339};
141340
141341struct sqlite3_tokenizer_cursor {
141342  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
141343  /* Tokenizer implementations will typically add additional fields */
141344};
141345
141346int fts3_global_term_cnt(int iTerm, int iCol);
141347int fts3_term_cnt(int iTerm, int iCol);
141348
141349
141350#endif /* _FTS3_TOKENIZER_H_ */
141351
141352/************** End of fts3_tokenizer.h **************************************/
141353/************** Continuing where we left off in fts3Int.h ********************/
141354/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
141355/************** Begin file fts3_hash.h ***************************************/
141356/*
141357** 2001 September 22
141358**
141359** The author disclaims copyright to this source code.  In place of
141360** a legal notice, here is a blessing:
141361**
141362**    May you do good and not evil.
141363**    May you find forgiveness for yourself and forgive others.
141364**    May you share freely, never taking more than you give.
141365**
141366*************************************************************************
141367** This is the header file for the generic hash-table implementation
141368** used in SQLite.  We've modified it slightly to serve as a standalone
141369** hash table implementation for the full-text indexing module.
141370**
141371*/
141372#ifndef _FTS3_HASH_H_
141373#define _FTS3_HASH_H_
141374
141375/* Forward declarations of structures. */
141376typedef struct Fts3Hash Fts3Hash;
141377typedef struct Fts3HashElem Fts3HashElem;
141378
141379/* A complete hash table is an instance of the following structure.
141380** The internals of this structure are intended to be opaque -- client
141381** code should not attempt to access or modify the fields of this structure
141382** directly.  Change this structure only by using the routines below.
141383** However, many of the "procedures" and "functions" for modifying and
141384** accessing this structure are really macros, so we can't really make
141385** this structure opaque.
141386*/
141387struct Fts3Hash {
141388  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
141389  char copyKey;           /* True if copy of key made on insert */
141390  int count;              /* Number of entries in this table */
141391  Fts3HashElem *first;    /* The first element of the array */
141392  int htsize;             /* Number of buckets in the hash table */
141393  struct _fts3ht {        /* the hash table */
141394    int count;               /* Number of entries with this hash */
141395    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
141396  } *ht;
141397};
141398
141399/* Each element in the hash table is an instance of the following
141400** structure.  All elements are stored on a single doubly-linked list.
141401**
141402** Again, this structure is intended to be opaque, but it can't really
141403** be opaque because it is used by macros.
141404*/
141405struct Fts3HashElem {
141406  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
141407  void *data;                /* Data associated with this element */
141408  void *pKey; int nKey;      /* Key associated with this element */
141409};
141410
141411/*
141412** There are 2 different modes of operation for a hash table:
141413**
141414**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
141415**                           (including the null-terminator, if any).  Case
141416**                           is respected in comparisons.
141417**
141418**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
141419**                           memcmp() is used to compare keys.
141420**
141421** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
141422*/
141423#define FTS3_HASH_STRING    1
141424#define FTS3_HASH_BINARY    2
141425
141426/*
141427** Access routines.  To delete, insert a NULL pointer.
141428*/
141429SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
141430SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
141431SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
141432SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
141433SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
141434
141435/*
141436** Shorthand for the functions above
141437*/
141438#define fts3HashInit     sqlite3Fts3HashInit
141439#define fts3HashInsert   sqlite3Fts3HashInsert
141440#define fts3HashFind     sqlite3Fts3HashFind
141441#define fts3HashClear    sqlite3Fts3HashClear
141442#define fts3HashFindElem sqlite3Fts3HashFindElem
141443
141444/*
141445** Macros for looping over all elements of a hash table.  The idiom is
141446** like this:
141447**
141448**   Fts3Hash h;
141449**   Fts3HashElem *p;
141450**   ...
141451**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
141452**     SomeStructure *pData = fts3HashData(p);
141453**     // do something with pData
141454**   }
141455*/
141456#define fts3HashFirst(H)  ((H)->first)
141457#define fts3HashNext(E)   ((E)->next)
141458#define fts3HashData(E)   ((E)->data)
141459#define fts3HashKey(E)    ((E)->pKey)
141460#define fts3HashKeysize(E) ((E)->nKey)
141461
141462/*
141463** Number of entries in a hash table
141464*/
141465#define fts3HashCount(H)  ((H)->count)
141466
141467#endif /* _FTS3_HASH_H_ */
141468
141469/************** End of fts3_hash.h *******************************************/
141470/************** Continuing where we left off in fts3Int.h ********************/
141471
141472/*
141473** This constant determines the maximum depth of an FTS expression tree
141474** that the library will create and use. FTS uses recursion to perform
141475** various operations on the query tree, so the disadvantage of a large
141476** limit is that it may allow very large queries to use large amounts
141477** of stack space (perhaps causing a stack overflow).
141478*/
141479#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
141480# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
141481#endif
141482
141483
141484/*
141485** This constant controls how often segments are merged. Once there are
141486** FTS3_MERGE_COUNT segments of level N, they are merged into a single
141487** segment of level N+1.
141488*/
141489#define FTS3_MERGE_COUNT 16
141490
141491/*
141492** This is the maximum amount of data (in bytes) to store in the
141493** Fts3Table.pendingTerms hash table. Normally, the hash table is
141494** populated as documents are inserted/updated/deleted in a transaction
141495** and used to create a new segment when the transaction is committed.
141496** However if this limit is reached midway through a transaction, a new
141497** segment is created and the hash table cleared immediately.
141498*/
141499#define FTS3_MAX_PENDING_DATA (1*1024*1024)
141500
141501/*
141502** Macro to return the number of elements in an array. SQLite has a
141503** similar macro called ArraySize(). Use a different name to avoid
141504** a collision when building an amalgamation with built-in FTS3.
141505*/
141506#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
141507
141508
141509#ifndef MIN
141510# define MIN(x,y) ((x)<(y)?(x):(y))
141511#endif
141512#ifndef MAX
141513# define MAX(x,y) ((x)>(y)?(x):(y))
141514#endif
141515
141516/*
141517** Maximum length of a varint encoded integer. The varint format is different
141518** from that used by SQLite, so the maximum length is 10, not 9.
141519*/
141520#define FTS3_VARINT_MAX 10
141521
141522/*
141523** FTS4 virtual tables may maintain multiple indexes - one index of all terms
141524** in the document set and zero or more prefix indexes. All indexes are stored
141525** as one or more b+-trees in the %_segments and %_segdir tables.
141526**
141527** It is possible to determine which index a b+-tree belongs to based on the
141528** value stored in the "%_segdir.level" column. Given this value L, the index
141529** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
141530** level values between 0 and 1023 (inclusive) belong to index 0, all levels
141531** between 1024 and 2047 to index 1, and so on.
141532**
141533** It is considered impossible for an index to use more than 1024 levels. In
141534** theory though this may happen, but only after at least
141535** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
141536*/
141537#define FTS3_SEGDIR_MAXLEVEL      1024
141538#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
141539
141540/*
141541** The testcase() macro is only used by the amalgamation.  If undefined,
141542** make it a no-op.
141543*/
141544#ifndef testcase
141545# define testcase(X)
141546#endif
141547
141548/*
141549** Terminator values for position-lists and column-lists.
141550*/
141551#define POS_COLUMN  (1)     /* Column-list terminator */
141552#define POS_END     (0)     /* Position-list terminator */
141553
141554/*
141555** This section provides definitions to allow the
141556** FTS3 extension to be compiled outside of the
141557** amalgamation.
141558*/
141559#ifndef SQLITE_AMALGAMATION
141560/*
141561** Macros indicating that conditional expressions are always true or
141562** false.
141563*/
141564#ifdef SQLITE_COVERAGE_TEST
141565# define ALWAYS(x) (1)
141566# define NEVER(X)  (0)
141567#elif defined(SQLITE_DEBUG)
141568# define ALWAYS(x) sqlite3Fts3Always((x)!=0)
141569# define NEVER(x) sqlite3Fts3Never((x)!=0)
141570SQLITE_PRIVATE int sqlite3Fts3Always(int b);
141571SQLITE_PRIVATE int sqlite3Fts3Never(int b);
141572#else
141573# define ALWAYS(x) (x)
141574# define NEVER(x)  (x)
141575#endif
141576
141577/*
141578** Internal types used by SQLite.
141579*/
141580typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
141581typedef short int i16;            /* 2-byte (or larger) signed integer */
141582typedef unsigned int u32;         /* 4-byte unsigned integer */
141583typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
141584typedef sqlite3_int64 i64;        /* 8-byte signed integer */
141585
141586/*
141587** Macro used to suppress compiler warnings for unused parameters.
141588*/
141589#define UNUSED_PARAMETER(x) (void)(x)
141590
141591/*
141592** Activate assert() only if SQLITE_TEST is enabled.
141593*/
141594#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
141595# define NDEBUG 1
141596#endif
141597
141598/*
141599** The TESTONLY macro is used to enclose variable declarations or
141600** other bits of code that are needed to support the arguments
141601** within testcase() and assert() macros.
141602*/
141603#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
141604# define TESTONLY(X)  X
141605#else
141606# define TESTONLY(X)
141607#endif
141608
141609#endif /* SQLITE_AMALGAMATION */
141610
141611#ifdef SQLITE_DEBUG
141612SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
141613# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
141614#else
141615# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
141616#endif
141617
141618typedef struct Fts3Table Fts3Table;
141619typedef struct Fts3Cursor Fts3Cursor;
141620typedef struct Fts3Expr Fts3Expr;
141621typedef struct Fts3Phrase Fts3Phrase;
141622typedef struct Fts3PhraseToken Fts3PhraseToken;
141623
141624typedef struct Fts3Doclist Fts3Doclist;
141625typedef struct Fts3SegFilter Fts3SegFilter;
141626typedef struct Fts3DeferredToken Fts3DeferredToken;
141627typedef struct Fts3SegReader Fts3SegReader;
141628typedef struct Fts3MultiSegReader Fts3MultiSegReader;
141629
141630typedef struct MatchinfoBuffer MatchinfoBuffer;
141631
141632/*
141633** A connection to a fulltext index is an instance of the following
141634** structure. The xCreate and xConnect methods create an instance
141635** of this structure and xDestroy and xDisconnect free that instance.
141636** All other methods receive a pointer to the structure as one of their
141637** arguments.
141638*/
141639struct Fts3Table {
141640  sqlite3_vtab base;              /* Base class used by SQLite core */
141641  sqlite3 *db;                    /* The database connection */
141642  const char *zDb;                /* logical database name */
141643  const char *zName;              /* virtual table name */
141644  int nColumn;                    /* number of named columns in virtual table */
141645  char **azColumn;                /* column names.  malloced */
141646  u8 *abNotindexed;               /* True for 'notindexed' columns */
141647  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
141648  char *zContentTbl;              /* content=xxx option, or NULL */
141649  char *zLanguageid;              /* languageid=xxx option, or NULL */
141650  int nAutoincrmerge;             /* Value configured by 'automerge' */
141651  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
141652
141653  /* Precompiled statements used by the implementation. Each of these
141654  ** statements is run and reset within a single virtual table API call.
141655  */
141656  sqlite3_stmt *aStmt[40];
141657
141658  char *zReadExprlist;
141659  char *zWriteExprlist;
141660
141661  int nNodeSize;                  /* Soft limit for node size */
141662  u8 bFts4;                       /* True for FTS4, false for FTS3 */
141663  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
141664  u8 bHasDocsize;                 /* True if %_docsize table exists */
141665  u8 bDescIdx;                    /* True if doclists are in reverse order */
141666  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
141667  int nPgsz;                      /* Page size for host database */
141668  char *zSegmentsTbl;             /* Name of %_segments table */
141669  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
141670
141671  /*
141672  ** The following array of hash tables is used to buffer pending index
141673  ** updates during transactions. All pending updates buffered at any one
141674  ** time must share a common language-id (see the FTS4 langid= feature).
141675  ** The current language id is stored in variable iPrevLangid.
141676  **
141677  ** A single FTS4 table may have multiple full-text indexes. For each index
141678  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
141679  ** terms that appear in the document set. Each subsequent index in aIndex[]
141680  ** is an index of prefixes of a specific length.
141681  **
141682  ** Variable nPendingData contains an estimate the memory consumed by the
141683  ** pending data structures, including hash table overhead, but not including
141684  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
141685  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
141686  ** recently inserted record.
141687  */
141688  int nIndex;                     /* Size of aIndex[] */
141689  struct Fts3Index {
141690    int nPrefix;                  /* Prefix length (0 for main terms index) */
141691    Fts3Hash hPending;            /* Pending terms table for this index */
141692  } *aIndex;
141693  int nMaxPendingData;            /* Max pending data before flush to disk */
141694  int nPendingData;               /* Current bytes of pending data */
141695  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
141696  int iPrevLangid;                /* Langid of recently inserted document */
141697  int bPrevDelete;                /* True if last operation was a delete */
141698
141699#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
141700  /* State variables used for validating that the transaction control
141701  ** methods of the virtual table are called at appropriate times.  These
141702  ** values do not contribute to FTS functionality; they are used for
141703  ** verifying the operation of the SQLite core.
141704  */
141705  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
141706  int mxSavepoint;       /* Largest valid xSavepoint integer */
141707#endif
141708
141709#ifdef SQLITE_TEST
141710  /* True to disable the incremental doclist optimization. This is controled
141711  ** by special insert command 'test-no-incr-doclist'.  */
141712  int bNoIncrDoclist;
141713#endif
141714};
141715
141716/*
141717** When the core wants to read from the virtual table, it creates a
141718** virtual table cursor (an instance of the following structure) using
141719** the xOpen method. Cursors are destroyed using the xClose method.
141720*/
141721struct Fts3Cursor {
141722  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
141723  i16 eSearch;                    /* Search strategy (see below) */
141724  u8 isEof;                       /* True if at End Of Results */
141725  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
141726  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
141727  Fts3Expr *pExpr;                /* Parsed MATCH query string */
141728  int iLangid;                    /* Language being queried for */
141729  int nPhrase;                    /* Number of matchable phrases in query */
141730  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
141731  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
141732  char *pNextId;                  /* Pointer into the body of aDoclist */
141733  char *aDoclist;                 /* List of docids for full-text queries */
141734  int nDoclist;                   /* Size of buffer at aDoclist */
141735  u8 bDesc;                       /* True to sort in descending order */
141736  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
141737  int nRowAvg;                    /* Average size of database rows, in pages */
141738  sqlite3_int64 nDoc;             /* Documents in table */
141739  i64 iMinDocid;                  /* Minimum docid to return */
141740  i64 iMaxDocid;                  /* Maximum docid to return */
141741  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
141742  MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
141743};
141744
141745#define FTS3_EVAL_FILTER    0
141746#define FTS3_EVAL_NEXT      1
141747#define FTS3_EVAL_MATCHINFO 2
141748
141749/*
141750** The Fts3Cursor.eSearch member is always set to one of the following.
141751** Actualy, Fts3Cursor.eSearch can be greater than or equal to
141752** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
141753** of the column to be searched.  For example, in
141754**
141755**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
141756**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
141757**
141758** Because the LHS of the MATCH operator is 2nd column "b",
141759** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
141760** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
141761** indicating that all columns should be searched,
141762** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
141763*/
141764#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
141765#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
141766#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
141767
141768/*
141769** The lower 16-bits of the sqlite3_index_info.idxNum value set by
141770** the xBestIndex() method contains the Fts3Cursor.eSearch value described
141771** above. The upper 16-bits contain a combination of the following
141772** bits, used to describe extra constraints on full-text searches.
141773*/
141774#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
141775#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
141776#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
141777
141778struct Fts3Doclist {
141779  char *aAll;                    /* Array containing doclist (or NULL) */
141780  int nAll;                      /* Size of a[] in bytes */
141781  char *pNextDocid;              /* Pointer to next docid */
141782
141783  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
141784  int bFreeList;                 /* True if pList should be sqlite3_free()d */
141785  char *pList;                   /* Pointer to position list following iDocid */
141786  int nList;                     /* Length of position list */
141787};
141788
141789/*
141790** A "phrase" is a sequence of one or more tokens that must match in
141791** sequence.  A single token is the base case and the most common case.
141792** For a sequence of tokens contained in double-quotes (i.e. "one two three")
141793** nToken will be the number of tokens in the string.
141794*/
141795struct Fts3PhraseToken {
141796  char *z;                        /* Text of the token */
141797  int n;                          /* Number of bytes in buffer z */
141798  int isPrefix;                   /* True if token ends with a "*" character */
141799  int bFirst;                     /* True if token must appear at position 0 */
141800
141801  /* Variables above this point are populated when the expression is
141802  ** parsed (by code in fts3_expr.c). Below this point the variables are
141803  ** used when evaluating the expression. */
141804  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
141805  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
141806};
141807
141808struct Fts3Phrase {
141809  /* Cache of doclist for this phrase. */
141810  Fts3Doclist doclist;
141811  int bIncr;                 /* True if doclist is loaded incrementally */
141812  int iDoclistToken;
141813
141814  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
141815  ** OR condition.  */
141816  char *pOrPoslist;
141817  i64 iOrDocid;
141818
141819  /* Variables below this point are populated by fts3_expr.c when parsing
141820  ** a MATCH expression. Everything above is part of the evaluation phase.
141821  */
141822  int nToken;                /* Number of tokens in the phrase */
141823  int iColumn;               /* Index of column this phrase must match */
141824  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
141825};
141826
141827/*
141828** A tree of these objects forms the RHS of a MATCH operator.
141829**
141830** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
141831** points to a malloced buffer, size nDoclist bytes, containing the results
141832** of this phrase query in FTS3 doclist format. As usual, the initial
141833** "Length" field found in doclists stored on disk is omitted from this
141834** buffer.
141835**
141836** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
141837** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
141838** where nCol is the number of columns in the queried FTS table. The array
141839** is populated as follows:
141840**
141841**   aMI[iCol*3 + 0] = Undefined
141842**   aMI[iCol*3 + 1] = Number of occurrences
141843**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
141844**
141845** The aMI array is allocated using sqlite3_malloc(). It should be freed
141846** when the expression node is.
141847*/
141848struct Fts3Expr {
141849  int eType;                 /* One of the FTSQUERY_XXX values defined below */
141850  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
141851  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
141852  Fts3Expr *pLeft;           /* Left operand */
141853  Fts3Expr *pRight;          /* Right operand */
141854  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
141855
141856  /* The following are used by the fts3_eval.c module. */
141857  sqlite3_int64 iDocid;      /* Current docid */
141858  u8 bEof;                   /* True this expression is at EOF already */
141859  u8 bStart;                 /* True if iDocid is valid */
141860  u8 bDeferred;              /* True if this expression is entirely deferred */
141861
141862  /* The following are used by the fts3_snippet.c module. */
141863  int iPhrase;               /* Index of this phrase in matchinfo() results */
141864  u32 *aMI;                  /* See above */
141865};
141866
141867/*
141868** Candidate values for Fts3Query.eType. Note that the order of the first
141869** four values is in order of precedence when parsing expressions. For
141870** example, the following:
141871**
141872**   "a OR b AND c NOT d NEAR e"
141873**
141874** is equivalent to:
141875**
141876**   "a OR (b AND (c NOT (d NEAR e)))"
141877*/
141878#define FTSQUERY_NEAR   1
141879#define FTSQUERY_NOT    2
141880#define FTSQUERY_AND    3
141881#define FTSQUERY_OR     4
141882#define FTSQUERY_PHRASE 5
141883
141884
141885/* fts3_write.c */
141886SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
141887SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
141888SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
141889SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
141890SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
141891  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
141892SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
141893  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
141894SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
141895SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
141896SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
141897
141898SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
141899SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
141900
141901#ifndef SQLITE_DISABLE_FTS4_DEFERRED
141902SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
141903SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
141904SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
141905SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
141906SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
141907#else
141908# define sqlite3Fts3FreeDeferredTokens(x)
141909# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
141910# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
141911# define sqlite3Fts3FreeDeferredDoclists(x)
141912# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
141913#endif
141914
141915SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
141916SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
141917
141918/* Special values interpreted by sqlite3SegReaderCursor() */
141919#define FTS3_SEGCURSOR_PENDING        -1
141920#define FTS3_SEGCURSOR_ALL            -2
141921
141922SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
141923SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
141924SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
141925
141926SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
141927    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
141928
141929/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
141930#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
141931#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
141932#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
141933#define FTS3_SEGMENT_PREFIX        0x00000008
141934#define FTS3_SEGMENT_SCAN          0x00000010
141935#define FTS3_SEGMENT_FIRST         0x00000020
141936
141937/* Type passed as 4th argument to SegmentReaderIterate() */
141938struct Fts3SegFilter {
141939  const char *zTerm;
141940  int nTerm;
141941  int iCol;
141942  int flags;
141943};
141944
141945struct Fts3MultiSegReader {
141946  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
141947  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
141948  int nSegment;                   /* Size of apSegment array */
141949  int nAdvance;                   /* How many seg-readers to advance */
141950  Fts3SegFilter *pFilter;         /* Pointer to filter object */
141951  char *aBuffer;                  /* Buffer to merge doclists in */
141952  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
141953
141954  int iColFilter;                 /* If >=0, filter for this column */
141955  int bRestart;
141956
141957  /* Used by fts3.c only. */
141958  int nCost;                      /* Cost of running iterator */
141959  int bLookup;                    /* True if a lookup of a single entry. */
141960
141961  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
141962  char *zTerm;                    /* Pointer to term buffer */
141963  int nTerm;                      /* Size of zTerm in bytes */
141964  char *aDoclist;                 /* Pointer to doclist buffer */
141965  int nDoclist;                   /* Size of aDoclist[] in bytes */
141966};
141967
141968SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
141969
141970#define fts3GetVarint32(p, piVal) (                                           \
141971  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
141972)
141973
141974/* fts3.c */
141975SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
141976SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
141977SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
141978SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
141979SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
141980SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
141981SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
141982SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
141983SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
141984SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
141985SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
141986
141987/* fts3_tokenizer.c */
141988SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
141989SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
141990SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
141991    sqlite3_tokenizer **, char **
141992);
141993SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
141994
141995/* fts3_snippet.c */
141996SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
141997SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
141998  const char *, const char *, int, int
141999);
142000SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
142001SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
142002
142003/* fts3_expr.c */
142004SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
142005  char **, int, int, int, const char *, int, Fts3Expr **, char **
142006);
142007SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
142008#ifdef SQLITE_TEST
142009SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
142010SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
142011#endif
142012
142013SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
142014  sqlite3_tokenizer_cursor **
142015);
142016
142017/* fts3_aux.c */
142018SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
142019
142020SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
142021
142022SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
142023    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
142024SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
142025    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
142026SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
142027SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
142028SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
142029
142030/* fts3_tokenize_vtab.c */
142031SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
142032
142033/* fts3_unicode2.c (functions generated by parsing unicode text files) */
142034#ifndef SQLITE_DISABLE_FTS3_UNICODE
142035SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
142036SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
142037SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
142038#endif
142039
142040#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
142041#endif /* _FTSINT_H */
142042
142043/************** End of fts3Int.h *********************************************/
142044/************** Continuing where we left off in fts3.c ***********************/
142045#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142046
142047#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
142048# define SQLITE_CORE 1
142049#endif
142050
142051/* #include <assert.h> */
142052/* #include <stdlib.h> */
142053/* #include <stddef.h> */
142054/* #include <stdio.h> */
142055/* #include <string.h> */
142056/* #include <stdarg.h> */
142057
142058/* #include "fts3.h" */
142059#ifndef SQLITE_CORE
142060/* # include "sqlite3ext.h" */
142061  SQLITE_EXTENSION_INIT1
142062#endif
142063
142064static int fts3EvalNext(Fts3Cursor *pCsr);
142065static int fts3EvalStart(Fts3Cursor *pCsr);
142066static int fts3TermSegReaderCursor(
142067    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
142068
142069#ifndef SQLITE_AMALGAMATION
142070# if defined(SQLITE_DEBUG)
142071SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
142072SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
142073# endif
142074#endif
142075
142076/*
142077** Write a 64-bit variable-length integer to memory starting at p[0].
142078** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
142079** The number of bytes written is returned.
142080*/
142081SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
142082  unsigned char *q = (unsigned char *) p;
142083  sqlite_uint64 vu = v;
142084  do{
142085    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
142086    vu >>= 7;
142087  }while( vu!=0 );
142088  q[-1] &= 0x7f;  /* turn off high bit in final byte */
142089  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
142090  return (int) (q - (unsigned char *)p);
142091}
142092
142093#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
142094  v = (v & mask1) | ( (*ptr++) << shift );                    \
142095  if( (v & mask2)==0 ){ var = v; return ret; }
142096#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
142097  v = (*ptr++);                                               \
142098  if( (v & mask2)==0 ){ var = v; return ret; }
142099
142100/*
142101** Read a 64-bit variable-length integer from memory starting at p[0].
142102** Return the number of bytes read, or 0 on error.
142103** The value is stored in *v.
142104*/
142105SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
142106  const char *pStart = p;
142107  u32 a;
142108  u64 b;
142109  int shift;
142110
142111  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
142112  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
142113  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
142114  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
142115  b = (a & 0x0FFFFFFF );
142116
142117  for(shift=28; shift<=63; shift+=7){
142118    u64 c = *p++;
142119    b += (c&0x7F) << shift;
142120    if( (c & 0x80)==0 ) break;
142121  }
142122  *v = b;
142123  return (int)(p - pStart);
142124}
142125
142126/*
142127** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
142128** 32-bit integer before it is returned.
142129*/
142130SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
142131  u32 a;
142132
142133#ifndef fts3GetVarint32
142134  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
142135#else
142136  a = (*p++);
142137  assert( a & 0x80 );
142138#endif
142139
142140  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
142141  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
142142  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
142143  a = (a & 0x0FFFFFFF );
142144  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
142145  return 5;
142146}
142147
142148/*
142149** Return the number of bytes required to encode v as a varint
142150*/
142151SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
142152  int i = 0;
142153  do{
142154    i++;
142155    v >>= 7;
142156  }while( v!=0 );
142157  return i;
142158}
142159
142160/*
142161** Convert an SQL-style quoted string into a normal string by removing
142162** the quote characters.  The conversion is done in-place.  If the
142163** input does not begin with a quote character, then this routine
142164** is a no-op.
142165**
142166** Examples:
142167**
142168**     "abc"   becomes   abc
142169**     'xyz'   becomes   xyz
142170**     [pqr]   becomes   pqr
142171**     `mno`   becomes   mno
142172**
142173*/
142174SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
142175  char quote;                     /* Quote character (if any ) */
142176
142177  quote = z[0];
142178  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
142179    int iIn = 1;                  /* Index of next byte to read from input */
142180    int iOut = 0;                 /* Index of next byte to write to output */
142181
142182    /* If the first byte was a '[', then the close-quote character is a ']' */
142183    if( quote=='[' ) quote = ']';
142184
142185    while( z[iIn] ){
142186      if( z[iIn]==quote ){
142187        if( z[iIn+1]!=quote ) break;
142188        z[iOut++] = quote;
142189        iIn += 2;
142190      }else{
142191        z[iOut++] = z[iIn++];
142192      }
142193    }
142194    z[iOut] = '\0';
142195  }
142196}
142197
142198/*
142199** Read a single varint from the doclist at *pp and advance *pp to point
142200** to the first byte past the end of the varint.  Add the value of the varint
142201** to *pVal.
142202*/
142203static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
142204  sqlite3_int64 iVal;
142205  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
142206  *pVal += iVal;
142207}
142208
142209/*
142210** When this function is called, *pp points to the first byte following a
142211** varint that is part of a doclist (or position-list, or any other list
142212** of varints). This function moves *pp to point to the start of that varint,
142213** and sets *pVal by the varint value.
142214**
142215** Argument pStart points to the first byte of the doclist that the
142216** varint is part of.
142217*/
142218static void fts3GetReverseVarint(
142219  char **pp,
142220  char *pStart,
142221  sqlite3_int64 *pVal
142222){
142223  sqlite3_int64 iVal;
142224  char *p;
142225
142226  /* Pointer p now points at the first byte past the varint we are
142227  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
142228  ** clear on character p[-1]. */
142229  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
142230  p++;
142231  *pp = p;
142232
142233  sqlite3Fts3GetVarint(p, &iVal);
142234  *pVal = iVal;
142235}
142236
142237/*
142238** The xDisconnect() virtual table method.
142239*/
142240static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
142241  Fts3Table *p = (Fts3Table *)pVtab;
142242  int i;
142243
142244  assert( p->nPendingData==0 );
142245  assert( p->pSegments==0 );
142246
142247  /* Free any prepared statements held */
142248  for(i=0; i<SizeofArray(p->aStmt); i++){
142249    sqlite3_finalize(p->aStmt[i]);
142250  }
142251  sqlite3_free(p->zSegmentsTbl);
142252  sqlite3_free(p->zReadExprlist);
142253  sqlite3_free(p->zWriteExprlist);
142254  sqlite3_free(p->zContentTbl);
142255  sqlite3_free(p->zLanguageid);
142256
142257  /* Invoke the tokenizer destructor to free the tokenizer. */
142258  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
142259
142260  sqlite3_free(p);
142261  return SQLITE_OK;
142262}
142263
142264/*
142265** Write an error message into *pzErr
142266*/
142267SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
142268  va_list ap;
142269  sqlite3_free(*pzErr);
142270  va_start(ap, zFormat);
142271  *pzErr = sqlite3_vmprintf(zFormat, ap);
142272  va_end(ap);
142273}
142274
142275/*
142276** Construct one or more SQL statements from the format string given
142277** and then evaluate those statements. The success code is written
142278** into *pRc.
142279**
142280** If *pRc is initially non-zero then this routine is a no-op.
142281*/
142282static void fts3DbExec(
142283  int *pRc,              /* Success code */
142284  sqlite3 *db,           /* Database in which to run SQL */
142285  const char *zFormat,   /* Format string for SQL */
142286  ...                    /* Arguments to the format string */
142287){
142288  va_list ap;
142289  char *zSql;
142290  if( *pRc ) return;
142291  va_start(ap, zFormat);
142292  zSql = sqlite3_vmprintf(zFormat, ap);
142293  va_end(ap);
142294  if( zSql==0 ){
142295    *pRc = SQLITE_NOMEM;
142296  }else{
142297    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
142298    sqlite3_free(zSql);
142299  }
142300}
142301
142302/*
142303** The xDestroy() virtual table method.
142304*/
142305static int fts3DestroyMethod(sqlite3_vtab *pVtab){
142306  Fts3Table *p = (Fts3Table *)pVtab;
142307  int rc = SQLITE_OK;              /* Return code */
142308  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
142309  sqlite3 *db = p->db;             /* Database handle */
142310
142311  /* Drop the shadow tables */
142312  if( p->zContentTbl==0 ){
142313    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
142314  }
142315  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
142316  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
142317  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
142318  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
142319
142320  /* If everything has worked, invoke fts3DisconnectMethod() to free the
142321  ** memory associated with the Fts3Table structure and return SQLITE_OK.
142322  ** Otherwise, return an SQLite error code.
142323  */
142324  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
142325}
142326
142327
142328/*
142329** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
142330** passed as the first argument. This is done as part of the xConnect()
142331** and xCreate() methods.
142332**
142333** If *pRc is non-zero when this function is called, it is a no-op.
142334** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
142335** before returning.
142336*/
142337static void fts3DeclareVtab(int *pRc, Fts3Table *p){
142338  if( *pRc==SQLITE_OK ){
142339    int i;                        /* Iterator variable */
142340    int rc;                       /* Return code */
142341    char *zSql;                   /* SQL statement passed to declare_vtab() */
142342    char *zCols;                  /* List of user defined columns */
142343    const char *zLanguageid;
142344
142345    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
142346    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
142347
142348    /* Create a list of user columns for the virtual table */
142349    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
142350    for(i=1; zCols && i<p->nColumn; i++){
142351      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
142352    }
142353
142354    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
142355    zSql = sqlite3_mprintf(
142356        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
142357        zCols, p->zName, zLanguageid
142358    );
142359    if( !zCols || !zSql ){
142360      rc = SQLITE_NOMEM;
142361    }else{
142362      rc = sqlite3_declare_vtab(p->db, zSql);
142363    }
142364
142365    sqlite3_free(zSql);
142366    sqlite3_free(zCols);
142367    *pRc = rc;
142368  }
142369}
142370
142371/*
142372** Create the %_stat table if it does not already exist.
142373*/
142374SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
142375  fts3DbExec(pRc, p->db,
142376      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
142377          "(id INTEGER PRIMARY KEY, value BLOB);",
142378      p->zDb, p->zName
142379  );
142380  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
142381}
142382
142383/*
142384** Create the backing store tables (%_content, %_segments and %_segdir)
142385** required by the FTS3 table passed as the only argument. This is done
142386** as part of the vtab xCreate() method.
142387**
142388** If the p->bHasDocsize boolean is true (indicating that this is an
142389** FTS4 table, not an FTS3 table) then also create the %_docsize and
142390** %_stat tables required by FTS4.
142391*/
142392static int fts3CreateTables(Fts3Table *p){
142393  int rc = SQLITE_OK;             /* Return code */
142394  int i;                          /* Iterator variable */
142395  sqlite3 *db = p->db;            /* The database connection */
142396
142397  if( p->zContentTbl==0 ){
142398    const char *zLanguageid = p->zLanguageid;
142399    char *zContentCols;           /* Columns of %_content table */
142400
142401    /* Create a list of user columns for the content table */
142402    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
142403    for(i=0; zContentCols && i<p->nColumn; i++){
142404      char *z = p->azColumn[i];
142405      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
142406    }
142407    if( zLanguageid && zContentCols ){
142408      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
142409    }
142410    if( zContentCols==0 ) rc = SQLITE_NOMEM;
142411
142412    /* Create the content table */
142413    fts3DbExec(&rc, db,
142414       "CREATE TABLE %Q.'%q_content'(%s)",
142415       p->zDb, p->zName, zContentCols
142416    );
142417    sqlite3_free(zContentCols);
142418  }
142419
142420  /* Create other tables */
142421  fts3DbExec(&rc, db,
142422      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
142423      p->zDb, p->zName
142424  );
142425  fts3DbExec(&rc, db,
142426      "CREATE TABLE %Q.'%q_segdir'("
142427        "level INTEGER,"
142428        "idx INTEGER,"
142429        "start_block INTEGER,"
142430        "leaves_end_block INTEGER,"
142431        "end_block INTEGER,"
142432        "root BLOB,"
142433        "PRIMARY KEY(level, idx)"
142434      ");",
142435      p->zDb, p->zName
142436  );
142437  if( p->bHasDocsize ){
142438    fts3DbExec(&rc, db,
142439        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
142440        p->zDb, p->zName
142441    );
142442  }
142443  assert( p->bHasStat==p->bFts4 );
142444  if( p->bHasStat ){
142445    sqlite3Fts3CreateStatTable(&rc, p);
142446  }
142447  return rc;
142448}
142449
142450/*
142451** Store the current database page-size in bytes in p->nPgsz.
142452**
142453** If *pRc is non-zero when this function is called, it is a no-op.
142454** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
142455** before returning.
142456*/
142457static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
142458  if( *pRc==SQLITE_OK ){
142459    int rc;                       /* Return code */
142460    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
142461    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
142462
142463    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
142464    if( !zSql ){
142465      rc = SQLITE_NOMEM;
142466    }else{
142467      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
142468      if( rc==SQLITE_OK ){
142469        sqlite3_step(pStmt);
142470        p->nPgsz = sqlite3_column_int(pStmt, 0);
142471        rc = sqlite3_finalize(pStmt);
142472      }else if( rc==SQLITE_AUTH ){
142473        p->nPgsz = 1024;
142474        rc = SQLITE_OK;
142475      }
142476    }
142477    assert( p->nPgsz>0 || rc!=SQLITE_OK );
142478    sqlite3_free(zSql);
142479    *pRc = rc;
142480  }
142481}
142482
142483/*
142484** "Special" FTS4 arguments are column specifications of the following form:
142485**
142486**   <key> = <value>
142487**
142488** There may not be whitespace surrounding the "=" character. The <value>
142489** term may be quoted, but the <key> may not.
142490*/
142491static int fts3IsSpecialColumn(
142492  const char *z,
142493  int *pnKey,
142494  char **pzValue
142495){
142496  char *zValue;
142497  const char *zCsr = z;
142498
142499  while( *zCsr!='=' ){
142500    if( *zCsr=='\0' ) return 0;
142501    zCsr++;
142502  }
142503
142504  *pnKey = (int)(zCsr-z);
142505  zValue = sqlite3_mprintf("%s", &zCsr[1]);
142506  if( zValue ){
142507    sqlite3Fts3Dequote(zValue);
142508  }
142509  *pzValue = zValue;
142510  return 1;
142511}
142512
142513/*
142514** Append the output of a printf() style formatting to an existing string.
142515*/
142516static void fts3Appendf(
142517  int *pRc,                       /* IN/OUT: Error code */
142518  char **pz,                      /* IN/OUT: Pointer to string buffer */
142519  const char *zFormat,            /* Printf format string to append */
142520  ...                             /* Arguments for printf format string */
142521){
142522  if( *pRc==SQLITE_OK ){
142523    va_list ap;
142524    char *z;
142525    va_start(ap, zFormat);
142526    z = sqlite3_vmprintf(zFormat, ap);
142527    va_end(ap);
142528    if( z && *pz ){
142529      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
142530      sqlite3_free(z);
142531      z = z2;
142532    }
142533    if( z==0 ) *pRc = SQLITE_NOMEM;
142534    sqlite3_free(*pz);
142535    *pz = z;
142536  }
142537}
142538
142539/*
142540** Return a copy of input string zInput enclosed in double-quotes (") and
142541** with all double quote characters escaped. For example:
142542**
142543**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
142544**
142545** The pointer returned points to memory obtained from sqlite3_malloc(). It
142546** is the callers responsibility to call sqlite3_free() to release this
142547** memory.
142548*/
142549static char *fts3QuoteId(char const *zInput){
142550  int nRet;
142551  char *zRet;
142552  nRet = 2 + (int)strlen(zInput)*2 + 1;
142553  zRet = sqlite3_malloc(nRet);
142554  if( zRet ){
142555    int i;
142556    char *z = zRet;
142557    *(z++) = '"';
142558    for(i=0; zInput[i]; i++){
142559      if( zInput[i]=='"' ) *(z++) = '"';
142560      *(z++) = zInput[i];
142561    }
142562    *(z++) = '"';
142563    *(z++) = '\0';
142564  }
142565  return zRet;
142566}
142567
142568/*
142569** Return a list of comma separated SQL expressions and a FROM clause that
142570** could be used in a SELECT statement such as the following:
142571**
142572**     SELECT <list of expressions> FROM %_content AS x ...
142573**
142574** to return the docid, followed by each column of text data in order
142575** from left to write. If parameter zFunc is not NULL, then instead of
142576** being returned directly each column of text data is passed to an SQL
142577** function named zFunc first. For example, if zFunc is "unzip" and the
142578** table has the three user-defined columns "a", "b", and "c", the following
142579** string is returned:
142580**
142581**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
142582**
142583** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
142584** is the responsibility of the caller to eventually free it.
142585**
142586** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
142587** a NULL pointer is returned). Otherwise, if an OOM error is encountered
142588** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
142589** no error occurs, *pRc is left unmodified.
142590*/
142591static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
142592  char *zRet = 0;
142593  char *zFree = 0;
142594  char *zFunction;
142595  int i;
142596
142597  if( p->zContentTbl==0 ){
142598    if( !zFunc ){
142599      zFunction = "";
142600    }else{
142601      zFree = zFunction = fts3QuoteId(zFunc);
142602    }
142603    fts3Appendf(pRc, &zRet, "docid");
142604    for(i=0; i<p->nColumn; i++){
142605      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
142606    }
142607    if( p->zLanguageid ){
142608      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
142609    }
142610    sqlite3_free(zFree);
142611  }else{
142612    fts3Appendf(pRc, &zRet, "rowid");
142613    for(i=0; i<p->nColumn; i++){
142614      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
142615    }
142616    if( p->zLanguageid ){
142617      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
142618    }
142619  }
142620  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
142621      p->zDb,
142622      (p->zContentTbl ? p->zContentTbl : p->zName),
142623      (p->zContentTbl ? "" : "_content")
142624  );
142625  return zRet;
142626}
142627
142628/*
142629** Return a list of N comma separated question marks, where N is the number
142630** of columns in the %_content table (one for the docid plus one for each
142631** user-defined text column).
142632**
142633** If argument zFunc is not NULL, then all but the first question mark
142634** is preceded by zFunc and an open bracket, and followed by a closed
142635** bracket. For example, if zFunc is "zip" and the FTS3 table has three
142636** user-defined text columns, the following string is returned:
142637**
142638**     "?, zip(?), zip(?), zip(?)"
142639**
142640** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
142641** is the responsibility of the caller to eventually free it.
142642**
142643** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
142644** a NULL pointer is returned). Otherwise, if an OOM error is encountered
142645** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
142646** no error occurs, *pRc is left unmodified.
142647*/
142648static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
142649  char *zRet = 0;
142650  char *zFree = 0;
142651  char *zFunction;
142652  int i;
142653
142654  if( !zFunc ){
142655    zFunction = "";
142656  }else{
142657    zFree = zFunction = fts3QuoteId(zFunc);
142658  }
142659  fts3Appendf(pRc, &zRet, "?");
142660  for(i=0; i<p->nColumn; i++){
142661    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
142662  }
142663  if( p->zLanguageid ){
142664    fts3Appendf(pRc, &zRet, ", ?");
142665  }
142666  sqlite3_free(zFree);
142667  return zRet;
142668}
142669
142670/*
142671** This function interprets the string at (*pp) as a non-negative integer
142672** value. It reads the integer and sets *pnOut to the value read, then
142673** sets *pp to point to the byte immediately following the last byte of
142674** the integer value.
142675**
142676** Only decimal digits ('0'..'9') may be part of an integer value.
142677**
142678** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
142679** the output value undefined. Otherwise SQLITE_OK is returned.
142680**
142681** This function is used when parsing the "prefix=" FTS4 parameter.
142682*/
142683static int fts3GobbleInt(const char **pp, int *pnOut){
142684  const int MAX_NPREFIX = 10000000;
142685  const char *p;                  /* Iterator pointer */
142686  int nInt = 0;                   /* Output value */
142687
142688  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
142689    nInt = nInt * 10 + (p[0] - '0');
142690    if( nInt>MAX_NPREFIX ){
142691      nInt = 0;
142692      break;
142693    }
142694  }
142695  if( p==*pp ) return SQLITE_ERROR;
142696  *pnOut = nInt;
142697  *pp = p;
142698  return SQLITE_OK;
142699}
142700
142701/*
142702** This function is called to allocate an array of Fts3Index structures
142703** representing the indexes maintained by the current FTS table. FTS tables
142704** always maintain the main "terms" index, but may also maintain one or
142705** more "prefix" indexes, depending on the value of the "prefix=" parameter
142706** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
142707**
142708** Argument zParam is passed the value of the "prefix=" option if one was
142709** specified, or NULL otherwise.
142710**
142711** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
142712** the allocated array. *pnIndex is set to the number of elements in the
142713** array. If an error does occur, an SQLite error code is returned.
142714**
142715** Regardless of whether or not an error is returned, it is the responsibility
142716** of the caller to call sqlite3_free() on the output array to free it.
142717*/
142718static int fts3PrefixParameter(
142719  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
142720  int *pnIndex,                   /* OUT: size of *apIndex[] array */
142721  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
142722){
142723  struct Fts3Index *aIndex;       /* Allocated array */
142724  int nIndex = 1;                 /* Number of entries in array */
142725
142726  if( zParam && zParam[0] ){
142727    const char *p;
142728    nIndex++;
142729    for(p=zParam; *p; p++){
142730      if( *p==',' ) nIndex++;
142731    }
142732  }
142733
142734  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
142735  *apIndex = aIndex;
142736  if( !aIndex ){
142737    return SQLITE_NOMEM;
142738  }
142739
142740  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
142741  if( zParam ){
142742    const char *p = zParam;
142743    int i;
142744    for(i=1; i<nIndex; i++){
142745      int nPrefix = 0;
142746      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
142747      assert( nPrefix>=0 );
142748      if( nPrefix==0 ){
142749        nIndex--;
142750        i--;
142751      }else{
142752        aIndex[i].nPrefix = nPrefix;
142753      }
142754      p++;
142755    }
142756  }
142757
142758  *pnIndex = nIndex;
142759  return SQLITE_OK;
142760}
142761
142762/*
142763** This function is called when initializing an FTS4 table that uses the
142764** content=xxx option. It determines the number of and names of the columns
142765** of the new FTS4 table.
142766**
142767** The third argument passed to this function is the value passed to the
142768** config=xxx option (i.e. "xxx"). This function queries the database for
142769** a table of that name. If found, the output variables are populated
142770** as follows:
142771**
142772**   *pnCol:   Set to the number of columns table xxx has,
142773**
142774**   *pnStr:   Set to the total amount of space required to store a copy
142775**             of each columns name, including the nul-terminator.
142776**
142777**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
142778**             the name of the corresponding column in table xxx. The array
142779**             and its contents are allocated using a single allocation. It
142780**             is the responsibility of the caller to free this allocation
142781**             by eventually passing the *pazCol value to sqlite3_free().
142782**
142783** If the table cannot be found, an error code is returned and the output
142784** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
142785** returned (and the output variables are undefined).
142786*/
142787static int fts3ContentColumns(
142788  sqlite3 *db,                    /* Database handle */
142789  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
142790  const char *zTbl,               /* Name of content table */
142791  const char ***pazCol,           /* OUT: Malloc'd array of column names */
142792  int *pnCol,                     /* OUT: Size of array *pazCol */
142793  int *pnStr,                     /* OUT: Bytes of string content */
142794  char **pzErr                    /* OUT: error message */
142795){
142796  int rc = SQLITE_OK;             /* Return code */
142797  char *zSql;                     /* "SELECT *" statement on zTbl */
142798  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
142799
142800  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
142801  if( !zSql ){
142802    rc = SQLITE_NOMEM;
142803  }else{
142804    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
142805    if( rc!=SQLITE_OK ){
142806      sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
142807    }
142808  }
142809  sqlite3_free(zSql);
142810
142811  if( rc==SQLITE_OK ){
142812    const char **azCol;           /* Output array */
142813    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
142814    int nCol;                     /* Number of table columns */
142815    int i;                        /* Used to iterate through columns */
142816
142817    /* Loop through the returned columns. Set nStr to the number of bytes of
142818    ** space required to store a copy of each column name, including the
142819    ** nul-terminator byte.  */
142820    nCol = sqlite3_column_count(pStmt);
142821    for(i=0; i<nCol; i++){
142822      const char *zCol = sqlite3_column_name(pStmt, i);
142823      nStr += (int)strlen(zCol) + 1;
142824    }
142825
142826    /* Allocate and populate the array to return. */
142827    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
142828    if( azCol==0 ){
142829      rc = SQLITE_NOMEM;
142830    }else{
142831      char *p = (char *)&azCol[nCol];
142832      for(i=0; i<nCol; i++){
142833        const char *zCol = sqlite3_column_name(pStmt, i);
142834        int n = (int)strlen(zCol)+1;
142835        memcpy(p, zCol, n);
142836        azCol[i] = p;
142837        p += n;
142838      }
142839    }
142840    sqlite3_finalize(pStmt);
142841
142842    /* Set the output variables. */
142843    *pnCol = nCol;
142844    *pnStr = nStr;
142845    *pazCol = azCol;
142846  }
142847
142848  return rc;
142849}
142850
142851/*
142852** This function is the implementation of both the xConnect and xCreate
142853** methods of the FTS3 virtual table.
142854**
142855** The argv[] array contains the following:
142856**
142857**   argv[0]   -> module name  ("fts3" or "fts4")
142858**   argv[1]   -> database name
142859**   argv[2]   -> table name
142860**   argv[...] -> "column name" and other module argument fields.
142861*/
142862static int fts3InitVtab(
142863  int isCreate,                   /* True for xCreate, false for xConnect */
142864  sqlite3 *db,                    /* The SQLite database connection */
142865  void *pAux,                     /* Hash table containing tokenizers */
142866  int argc,                       /* Number of elements in argv array */
142867  const char * const *argv,       /* xCreate/xConnect argument array */
142868  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
142869  char **pzErr                    /* Write any error message here */
142870){
142871  Fts3Hash *pHash = (Fts3Hash *)pAux;
142872  Fts3Table *p = 0;               /* Pointer to allocated vtab */
142873  int rc = SQLITE_OK;             /* Return code */
142874  int i;                          /* Iterator variable */
142875  int nByte;                      /* Size of allocation used for *p */
142876  int iCol;                       /* Column index */
142877  int nString = 0;                /* Bytes required to hold all column names */
142878  int nCol = 0;                   /* Number of columns in the FTS table */
142879  char *zCsr;                     /* Space for holding column names */
142880  int nDb;                        /* Bytes required to hold database name */
142881  int nName;                      /* Bytes required to hold table name */
142882  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
142883  const char **aCol;              /* Array of column names */
142884  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
142885
142886  int nIndex = 0;                 /* Size of aIndex[] array */
142887  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
142888
142889  /* The results of parsing supported FTS4 key=value options: */
142890  int bNoDocsize = 0;             /* True to omit %_docsize table */
142891  int bDescIdx = 0;               /* True to store descending indexes */
142892  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
142893  char *zCompress = 0;            /* compress=? parameter (or NULL) */
142894  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
142895  char *zContent = 0;             /* content=? parameter (or NULL) */
142896  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
142897  char **azNotindexed = 0;        /* The set of notindexed= columns */
142898  int nNotindexed = 0;            /* Size of azNotindexed[] array */
142899
142900  assert( strlen(argv[0])==4 );
142901  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
142902       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
142903  );
142904
142905  nDb = (int)strlen(argv[1]) + 1;
142906  nName = (int)strlen(argv[2]) + 1;
142907
142908  nByte = sizeof(const char *) * (argc-2);
142909  aCol = (const char **)sqlite3_malloc(nByte);
142910  if( aCol ){
142911    memset((void*)aCol, 0, nByte);
142912    azNotindexed = (char **)sqlite3_malloc(nByte);
142913  }
142914  if( azNotindexed ){
142915    memset(azNotindexed, 0, nByte);
142916  }
142917  if( !aCol || !azNotindexed ){
142918    rc = SQLITE_NOMEM;
142919    goto fts3_init_out;
142920  }
142921
142922  /* Loop through all of the arguments passed by the user to the FTS3/4
142923  ** module (i.e. all the column names and special arguments). This loop
142924  ** does the following:
142925  **
142926  **   + Figures out the number of columns the FTSX table will have, and
142927  **     the number of bytes of space that must be allocated to store copies
142928  **     of the column names.
142929  **
142930  **   + If there is a tokenizer specification included in the arguments,
142931  **     initializes the tokenizer pTokenizer.
142932  */
142933  for(i=3; rc==SQLITE_OK && i<argc; i++){
142934    char const *z = argv[i];
142935    int nKey;
142936    char *zVal;
142937
142938    /* Check if this is a tokenizer specification */
142939    if( !pTokenizer
142940     && strlen(z)>8
142941     && 0==sqlite3_strnicmp(z, "tokenize", 8)
142942     && 0==sqlite3Fts3IsIdChar(z[8])
142943    ){
142944      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
142945    }
142946
142947    /* Check if it is an FTS4 special argument. */
142948    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
142949      struct Fts4Option {
142950        const char *zOpt;
142951        int nOpt;
142952      } aFts4Opt[] = {
142953        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
142954        { "prefix",      6 },     /* 1 -> PREFIX */
142955        { "compress",    8 },     /* 2 -> COMPRESS */
142956        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
142957        { "order",       5 },     /* 4 -> ORDER */
142958        { "content",     7 },     /* 5 -> CONTENT */
142959        { "languageid", 10 },     /* 6 -> LANGUAGEID */
142960        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
142961      };
142962
142963      int iOpt;
142964      if( !zVal ){
142965        rc = SQLITE_NOMEM;
142966      }else{
142967        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
142968          struct Fts4Option *pOp = &aFts4Opt[iOpt];
142969          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
142970            break;
142971          }
142972        }
142973        if( iOpt==SizeofArray(aFts4Opt) ){
142974          sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
142975          rc = SQLITE_ERROR;
142976        }else{
142977          switch( iOpt ){
142978            case 0:               /* MATCHINFO */
142979              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
142980                sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
142981                rc = SQLITE_ERROR;
142982              }
142983              bNoDocsize = 1;
142984              break;
142985
142986            case 1:               /* PREFIX */
142987              sqlite3_free(zPrefix);
142988              zPrefix = zVal;
142989              zVal = 0;
142990              break;
142991
142992            case 2:               /* COMPRESS */
142993              sqlite3_free(zCompress);
142994              zCompress = zVal;
142995              zVal = 0;
142996              break;
142997
142998            case 3:               /* UNCOMPRESS */
142999              sqlite3_free(zUncompress);
143000              zUncompress = zVal;
143001              zVal = 0;
143002              break;
143003
143004            case 4:               /* ORDER */
143005              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
143006               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
143007              ){
143008                sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
143009                rc = SQLITE_ERROR;
143010              }
143011              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
143012              break;
143013
143014            case 5:              /* CONTENT */
143015              sqlite3_free(zContent);
143016              zContent = zVal;
143017              zVal = 0;
143018              break;
143019
143020            case 6:              /* LANGUAGEID */
143021              assert( iOpt==6 );
143022              sqlite3_free(zLanguageid);
143023              zLanguageid = zVal;
143024              zVal = 0;
143025              break;
143026
143027            case 7:              /* NOTINDEXED */
143028              azNotindexed[nNotindexed++] = zVal;
143029              zVal = 0;
143030              break;
143031          }
143032        }
143033        sqlite3_free(zVal);
143034      }
143035    }
143036
143037    /* Otherwise, the argument is a column name. */
143038    else {
143039      nString += (int)(strlen(z) + 1);
143040      aCol[nCol++] = z;
143041    }
143042  }
143043
143044  /* If a content=xxx option was specified, the following:
143045  **
143046  **   1. Ignore any compress= and uncompress= options.
143047  **
143048  **   2. If no column names were specified as part of the CREATE VIRTUAL
143049  **      TABLE statement, use all columns from the content table.
143050  */
143051  if( rc==SQLITE_OK && zContent ){
143052    sqlite3_free(zCompress);
143053    sqlite3_free(zUncompress);
143054    zCompress = 0;
143055    zUncompress = 0;
143056    if( nCol==0 ){
143057      sqlite3_free((void*)aCol);
143058      aCol = 0;
143059      rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
143060
143061      /* If a languageid= option was specified, remove the language id
143062      ** column from the aCol[] array. */
143063      if( rc==SQLITE_OK && zLanguageid ){
143064        int j;
143065        for(j=0; j<nCol; j++){
143066          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
143067            int k;
143068            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
143069            nCol--;
143070            break;
143071          }
143072        }
143073      }
143074    }
143075  }
143076  if( rc!=SQLITE_OK ) goto fts3_init_out;
143077
143078  if( nCol==0 ){
143079    assert( nString==0 );
143080    aCol[0] = "content";
143081    nString = 8;
143082    nCol = 1;
143083  }
143084
143085  if( pTokenizer==0 ){
143086    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
143087    if( rc!=SQLITE_OK ) goto fts3_init_out;
143088  }
143089  assert( pTokenizer );
143090
143091  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
143092  if( rc==SQLITE_ERROR ){
143093    assert( zPrefix );
143094    sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
143095  }
143096  if( rc!=SQLITE_OK ) goto fts3_init_out;
143097
143098  /* Allocate and populate the Fts3Table structure. */
143099  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
143100          nCol * sizeof(char *) +              /* azColumn */
143101          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
143102          nCol * sizeof(u8) +                  /* abNotindexed */
143103          nName +                              /* zName */
143104          nDb +                                /* zDb */
143105          nString;                             /* Space for azColumn strings */
143106  p = (Fts3Table*)sqlite3_malloc(nByte);
143107  if( p==0 ){
143108    rc = SQLITE_NOMEM;
143109    goto fts3_init_out;
143110  }
143111  memset(p, 0, nByte);
143112  p->db = db;
143113  p->nColumn = nCol;
143114  p->nPendingData = 0;
143115  p->azColumn = (char **)&p[1];
143116  p->pTokenizer = pTokenizer;
143117  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
143118  p->bHasDocsize = (isFts4 && bNoDocsize==0);
143119  p->bHasStat = isFts4;
143120  p->bFts4 = isFts4;
143121  p->bDescIdx = bDescIdx;
143122  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
143123  p->zContentTbl = zContent;
143124  p->zLanguageid = zLanguageid;
143125  zContent = 0;
143126  zLanguageid = 0;
143127  TESTONLY( p->inTransaction = -1 );
143128  TESTONLY( p->mxSavepoint = -1 );
143129
143130  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
143131  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
143132  p->nIndex = nIndex;
143133  for(i=0; i<nIndex; i++){
143134    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
143135  }
143136  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
143137
143138  /* Fill in the zName and zDb fields of the vtab structure. */
143139  zCsr = (char *)&p->abNotindexed[nCol];
143140  p->zName = zCsr;
143141  memcpy(zCsr, argv[2], nName);
143142  zCsr += nName;
143143  p->zDb = zCsr;
143144  memcpy(zCsr, argv[1], nDb);
143145  zCsr += nDb;
143146
143147  /* Fill in the azColumn array */
143148  for(iCol=0; iCol<nCol; iCol++){
143149    char *z;
143150    int n = 0;
143151    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
143152    memcpy(zCsr, z, n);
143153    zCsr[n] = '\0';
143154    sqlite3Fts3Dequote(zCsr);
143155    p->azColumn[iCol] = zCsr;
143156    zCsr += n+1;
143157    assert( zCsr <= &((char *)p)[nByte] );
143158  }
143159
143160  /* Fill in the abNotindexed array */
143161  for(iCol=0; iCol<nCol; iCol++){
143162    int n = (int)strlen(p->azColumn[iCol]);
143163    for(i=0; i<nNotindexed; i++){
143164      char *zNot = azNotindexed[i];
143165      if( zNot && n==(int)strlen(zNot)
143166       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
143167      ){
143168        p->abNotindexed[iCol] = 1;
143169        sqlite3_free(zNot);
143170        azNotindexed[i] = 0;
143171      }
143172    }
143173  }
143174  for(i=0; i<nNotindexed; i++){
143175    if( azNotindexed[i] ){
143176      sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
143177      rc = SQLITE_ERROR;
143178    }
143179  }
143180
143181  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
143182    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
143183    rc = SQLITE_ERROR;
143184    sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
143185  }
143186  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
143187  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
143188  if( rc!=SQLITE_OK ) goto fts3_init_out;
143189
143190  /* If this is an xCreate call, create the underlying tables in the
143191  ** database. TODO: For xConnect(), it could verify that said tables exist.
143192  */
143193  if( isCreate ){
143194    rc = fts3CreateTables(p);
143195  }
143196
143197  /* Check to see if a legacy fts3 table has been "upgraded" by the
143198  ** addition of a %_stat table so that it can use incremental merge.
143199  */
143200  if( !isFts4 && !isCreate ){
143201    p->bHasStat = 2;
143202  }
143203
143204  /* Figure out the page-size for the database. This is required in order to
143205  ** estimate the cost of loading large doclists from the database.  */
143206  fts3DatabasePageSize(&rc, p);
143207  p->nNodeSize = p->nPgsz-35;
143208
143209  /* Declare the table schema to SQLite. */
143210  fts3DeclareVtab(&rc, p);
143211
143212fts3_init_out:
143213  sqlite3_free(zPrefix);
143214  sqlite3_free(aIndex);
143215  sqlite3_free(zCompress);
143216  sqlite3_free(zUncompress);
143217  sqlite3_free(zContent);
143218  sqlite3_free(zLanguageid);
143219  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
143220  sqlite3_free((void *)aCol);
143221  sqlite3_free((void *)azNotindexed);
143222  if( rc!=SQLITE_OK ){
143223    if( p ){
143224      fts3DisconnectMethod((sqlite3_vtab *)p);
143225    }else if( pTokenizer ){
143226      pTokenizer->pModule->xDestroy(pTokenizer);
143227    }
143228  }else{
143229    assert( p->pSegments==0 );
143230    *ppVTab = &p->base;
143231  }
143232  return rc;
143233}
143234
143235/*
143236** The xConnect() and xCreate() methods for the virtual table. All the
143237** work is done in function fts3InitVtab().
143238*/
143239static int fts3ConnectMethod(
143240  sqlite3 *db,                    /* Database connection */
143241  void *pAux,                     /* Pointer to tokenizer hash table */
143242  int argc,                       /* Number of elements in argv array */
143243  const char * const *argv,       /* xCreate/xConnect argument array */
143244  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
143245  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
143246){
143247  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
143248}
143249static int fts3CreateMethod(
143250  sqlite3 *db,                    /* Database connection */
143251  void *pAux,                     /* Pointer to tokenizer hash table */
143252  int argc,                       /* Number of elements in argv array */
143253  const char * const *argv,       /* xCreate/xConnect argument array */
143254  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
143255  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
143256){
143257  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
143258}
143259
143260/*
143261** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
143262** extension is currently being used by a version of SQLite too old to
143263** support estimatedRows. In that case this function is a no-op.
143264*/
143265static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
143266#if SQLITE_VERSION_NUMBER>=3008002
143267  if( sqlite3_libversion_number()>=3008002 ){
143268    pIdxInfo->estimatedRows = nRow;
143269  }
143270#endif
143271}
143272
143273/*
143274** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
143275** extension is currently being used by a version of SQLite too old to
143276** support index-info flags. In that case this function is a no-op.
143277*/
143278static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
143279#if SQLITE_VERSION_NUMBER>=3008012
143280  if( sqlite3_libversion_number()>=3008012 ){
143281    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
143282  }
143283#endif
143284}
143285
143286/*
143287** Implementation of the xBestIndex method for FTS3 tables. There
143288** are three possible strategies, in order of preference:
143289**
143290**   1. Direct lookup by rowid or docid.
143291**   2. Full-text search using a MATCH operator on a non-docid column.
143292**   3. Linear scan of %_content table.
143293*/
143294static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
143295  Fts3Table *p = (Fts3Table *)pVTab;
143296  int i;                          /* Iterator variable */
143297  int iCons = -1;                 /* Index of constraint to use */
143298
143299  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
143300  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
143301  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
143302  int iIdx;
143303
143304  /* By default use a full table scan. This is an expensive option,
143305  ** so search through the constraints to see if a more efficient
143306  ** strategy is possible.
143307  */
143308  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
143309  pInfo->estimatedCost = 5000000;
143310  for(i=0; i<pInfo->nConstraint; i++){
143311    int bDocid;                 /* True if this constraint is on docid */
143312    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
143313    if( pCons->usable==0 ){
143314      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
143315        /* There exists an unusable MATCH constraint. This means that if
143316        ** the planner does elect to use the results of this call as part
143317        ** of the overall query plan the user will see an "unable to use
143318        ** function MATCH in the requested context" error. To discourage
143319        ** this, return a very high cost here.  */
143320        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
143321        pInfo->estimatedCost = 1e50;
143322        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
143323        return SQLITE_OK;
143324      }
143325      continue;
143326    }
143327
143328    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
143329
143330    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
143331    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
143332      pInfo->idxNum = FTS3_DOCID_SEARCH;
143333      pInfo->estimatedCost = 1.0;
143334      iCons = i;
143335    }
143336
143337    /* A MATCH constraint. Use a full-text search.
143338    **
143339    ** If there is more than one MATCH constraint available, use the first
143340    ** one encountered. If there is both a MATCH constraint and a direct
143341    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
143342    ** though the rowid/docid lookup is faster than a MATCH query, selecting
143343    ** it would lead to an "unable to use function MATCH in the requested
143344    ** context" error.
143345    */
143346    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
143347     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
143348    ){
143349      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
143350      pInfo->estimatedCost = 2.0;
143351      iCons = i;
143352    }
143353
143354    /* Equality constraint on the langid column */
143355    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
143356     && pCons->iColumn==p->nColumn + 2
143357    ){
143358      iLangidCons = i;
143359    }
143360
143361    if( bDocid ){
143362      switch( pCons->op ){
143363        case SQLITE_INDEX_CONSTRAINT_GE:
143364        case SQLITE_INDEX_CONSTRAINT_GT:
143365          iDocidGe = i;
143366          break;
143367
143368        case SQLITE_INDEX_CONSTRAINT_LE:
143369        case SQLITE_INDEX_CONSTRAINT_LT:
143370          iDocidLe = i;
143371          break;
143372      }
143373    }
143374  }
143375
143376  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
143377  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
143378
143379  iIdx = 1;
143380  if( iCons>=0 ){
143381    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
143382    pInfo->aConstraintUsage[iCons].omit = 1;
143383  }
143384  if( iLangidCons>=0 ){
143385    pInfo->idxNum |= FTS3_HAVE_LANGID;
143386    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
143387  }
143388  if( iDocidGe>=0 ){
143389    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
143390    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
143391  }
143392  if( iDocidLe>=0 ){
143393    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
143394    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
143395  }
143396
143397  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
143398  ** docid) order. Both ascending and descending are possible.
143399  */
143400  if( pInfo->nOrderBy==1 ){
143401    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
143402    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
143403      if( pOrder->desc ){
143404        pInfo->idxStr = "DESC";
143405      }else{
143406        pInfo->idxStr = "ASC";
143407      }
143408      pInfo->orderByConsumed = 1;
143409    }
143410  }
143411
143412  assert( p->pSegments==0 );
143413  return SQLITE_OK;
143414}
143415
143416/*
143417** Implementation of xOpen method.
143418*/
143419static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
143420  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
143421
143422  UNUSED_PARAMETER(pVTab);
143423
143424  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
143425  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
143426  ** if the allocation fails, return SQLITE_NOMEM.
143427  */
143428  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
143429  if( !pCsr ){
143430    return SQLITE_NOMEM;
143431  }
143432  memset(pCsr, 0, sizeof(Fts3Cursor));
143433  return SQLITE_OK;
143434}
143435
143436/*
143437** Close the cursor.  For additional information see the documentation
143438** on the xClose method of the virtual table interface.
143439*/
143440static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
143441  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
143442  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143443  sqlite3_finalize(pCsr->pStmt);
143444  sqlite3Fts3ExprFree(pCsr->pExpr);
143445  sqlite3Fts3FreeDeferredTokens(pCsr);
143446  sqlite3_free(pCsr->aDoclist);
143447  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
143448  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143449  sqlite3_free(pCsr);
143450  return SQLITE_OK;
143451}
143452
143453/*
143454** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
143455** compose and prepare an SQL statement of the form:
143456**
143457**    "SELECT <columns> FROM %_content WHERE rowid = ?"
143458**
143459** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
143460** it. If an error occurs, return an SQLite error code.
143461**
143462** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
143463*/
143464static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
143465  int rc = SQLITE_OK;
143466  if( pCsr->pStmt==0 ){
143467    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
143468    char *zSql;
143469    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
143470    if( !zSql ) return SQLITE_NOMEM;
143471    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
143472    sqlite3_free(zSql);
143473  }
143474  *ppStmt = pCsr->pStmt;
143475  return rc;
143476}
143477
143478/*
143479** Position the pCsr->pStmt statement so that it is on the row
143480** of the %_content table that contains the last match.  Return
143481** SQLITE_OK on success.
143482*/
143483static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
143484  int rc = SQLITE_OK;
143485  if( pCsr->isRequireSeek ){
143486    sqlite3_stmt *pStmt = 0;
143487
143488    rc = fts3CursorSeekStmt(pCsr, &pStmt);
143489    if( rc==SQLITE_OK ){
143490      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
143491      pCsr->isRequireSeek = 0;
143492      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
143493        return SQLITE_OK;
143494      }else{
143495        rc = sqlite3_reset(pCsr->pStmt);
143496        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
143497          /* If no row was found and no error has occurred, then the %_content
143498          ** table is missing a row that is present in the full-text index.
143499          ** The data structures are corrupt.  */
143500          rc = FTS_CORRUPT_VTAB;
143501          pCsr->isEof = 1;
143502        }
143503      }
143504    }
143505  }
143506
143507  if( rc!=SQLITE_OK && pContext ){
143508    sqlite3_result_error_code(pContext, rc);
143509  }
143510  return rc;
143511}
143512
143513/*
143514** This function is used to process a single interior node when searching
143515** a b-tree for a term or term prefix. The node data is passed to this
143516** function via the zNode/nNode parameters. The term to search for is
143517** passed in zTerm/nTerm.
143518**
143519** If piFirst is not NULL, then this function sets *piFirst to the blockid
143520** of the child node that heads the sub-tree that may contain the term.
143521**
143522** If piLast is not NULL, then *piLast is set to the right-most child node
143523** that heads a sub-tree that may contain a term for which zTerm/nTerm is
143524** a prefix.
143525**
143526** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
143527*/
143528static int fts3ScanInteriorNode(
143529  const char *zTerm,              /* Term to select leaves for */
143530  int nTerm,                      /* Size of term zTerm in bytes */
143531  const char *zNode,              /* Buffer containing segment interior node */
143532  int nNode,                      /* Size of buffer at zNode */
143533  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
143534  sqlite3_int64 *piLast           /* OUT: Selected child node */
143535){
143536  int rc = SQLITE_OK;             /* Return code */
143537  const char *zCsr = zNode;       /* Cursor to iterate through node */
143538  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
143539  char *zBuffer = 0;              /* Buffer to load terms into */
143540  int nAlloc = 0;                 /* Size of allocated buffer */
143541  int isFirstTerm = 1;            /* True when processing first term on page */
143542  sqlite3_int64 iChild;           /* Block id of child node to descend to */
143543
143544  /* Skip over the 'height' varint that occurs at the start of every
143545  ** interior node. Then load the blockid of the left-child of the b-tree
143546  ** node into variable iChild.
143547  **
143548  ** Even if the data structure on disk is corrupted, this (reading two
143549  ** varints from the buffer) does not risk an overread. If zNode is a
143550  ** root node, then the buffer comes from a SELECT statement. SQLite does
143551  ** not make this guarantee explicitly, but in practice there are always
143552  ** either more than 20 bytes of allocated space following the nNode bytes of
143553  ** contents, or two zero bytes. Or, if the node is read from the %_segments
143554  ** table, then there are always 20 bytes of zeroed padding following the
143555  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
143556  */
143557  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
143558  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
143559  if( zCsr>zEnd ){
143560    return FTS_CORRUPT_VTAB;
143561  }
143562
143563  while( zCsr<zEnd && (piFirst || piLast) ){
143564    int cmp;                      /* memcmp() result */
143565    int nSuffix;                  /* Size of term suffix */
143566    int nPrefix = 0;              /* Size of term prefix */
143567    int nBuffer;                  /* Total term size */
143568
143569    /* Load the next term on the node into zBuffer. Use realloc() to expand
143570    ** the size of zBuffer if required.  */
143571    if( !isFirstTerm ){
143572      zCsr += fts3GetVarint32(zCsr, &nPrefix);
143573    }
143574    isFirstTerm = 0;
143575    zCsr += fts3GetVarint32(zCsr, &nSuffix);
143576
143577    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
143578      rc = FTS_CORRUPT_VTAB;
143579      goto finish_scan;
143580    }
143581    if( nPrefix+nSuffix>nAlloc ){
143582      char *zNew;
143583      nAlloc = (nPrefix+nSuffix) * 2;
143584      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
143585      if( !zNew ){
143586        rc = SQLITE_NOMEM;
143587        goto finish_scan;
143588      }
143589      zBuffer = zNew;
143590    }
143591    assert( zBuffer );
143592    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
143593    nBuffer = nPrefix + nSuffix;
143594    zCsr += nSuffix;
143595
143596    /* Compare the term we are searching for with the term just loaded from
143597    ** the interior node. If the specified term is greater than or equal
143598    ** to the term from the interior node, then all terms on the sub-tree
143599    ** headed by node iChild are smaller than zTerm. No need to search
143600    ** iChild.
143601    **
143602    ** If the interior node term is larger than the specified term, then
143603    ** the tree headed by iChild may contain the specified term.
143604    */
143605    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
143606    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
143607      *piFirst = iChild;
143608      piFirst = 0;
143609    }
143610
143611    if( piLast && cmp<0 ){
143612      *piLast = iChild;
143613      piLast = 0;
143614    }
143615
143616    iChild++;
143617  };
143618
143619  if( piFirst ) *piFirst = iChild;
143620  if( piLast ) *piLast = iChild;
143621
143622 finish_scan:
143623  sqlite3_free(zBuffer);
143624  return rc;
143625}
143626
143627
143628/*
143629** The buffer pointed to by argument zNode (size nNode bytes) contains an
143630** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
143631** contains a term. This function searches the sub-tree headed by the zNode
143632** node for the range of leaf nodes that may contain the specified term
143633** or terms for which the specified term is a prefix.
143634**
143635** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
143636** left-most leaf node in the tree that may contain the specified term.
143637** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
143638** right-most leaf node that may contain a term for which the specified
143639** term is a prefix.
143640**
143641** It is possible that the range of returned leaf nodes does not contain
143642** the specified term or any terms for which it is a prefix. However, if the
143643** segment does contain any such terms, they are stored within the identified
143644** range. Because this function only inspects interior segment nodes (and
143645** never loads leaf nodes into memory), it is not possible to be sure.
143646**
143647** If an error occurs, an error code other than SQLITE_OK is returned.
143648*/
143649static int fts3SelectLeaf(
143650  Fts3Table *p,                   /* Virtual table handle */
143651  const char *zTerm,              /* Term to select leaves for */
143652  int nTerm,                      /* Size of term zTerm in bytes */
143653  const char *zNode,              /* Buffer containing segment interior node */
143654  int nNode,                      /* Size of buffer at zNode */
143655  sqlite3_int64 *piLeaf,          /* Selected leaf node */
143656  sqlite3_int64 *piLeaf2          /* Selected leaf node */
143657){
143658  int rc = SQLITE_OK;             /* Return code */
143659  int iHeight;                    /* Height of this node in tree */
143660
143661  assert( piLeaf || piLeaf2 );
143662
143663  fts3GetVarint32(zNode, &iHeight);
143664  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
143665  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
143666
143667  if( rc==SQLITE_OK && iHeight>1 ){
143668    char *zBlob = 0;              /* Blob read from %_segments table */
143669    int nBlob = 0;                /* Size of zBlob in bytes */
143670
143671    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
143672      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
143673      if( rc==SQLITE_OK ){
143674        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
143675      }
143676      sqlite3_free(zBlob);
143677      piLeaf = 0;
143678      zBlob = 0;
143679    }
143680
143681    if( rc==SQLITE_OK ){
143682      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
143683    }
143684    if( rc==SQLITE_OK ){
143685      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
143686    }
143687    sqlite3_free(zBlob);
143688  }
143689
143690  return rc;
143691}
143692
143693/*
143694** This function is used to create delta-encoded serialized lists of FTS3
143695** varints. Each call to this function appends a single varint to a list.
143696*/
143697static void fts3PutDeltaVarint(
143698  char **pp,                      /* IN/OUT: Output pointer */
143699  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
143700  sqlite3_int64 iVal              /* Write this value to the list */
143701){
143702  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
143703  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
143704  *piPrev = iVal;
143705}
143706
143707/*
143708** When this function is called, *ppPoslist is assumed to point to the
143709** start of a position-list. After it returns, *ppPoslist points to the
143710** first byte after the position-list.
143711**
143712** A position list is list of positions (delta encoded) and columns for
143713** a single document record of a doclist.  So, in other words, this
143714** routine advances *ppPoslist so that it points to the next docid in
143715** the doclist, or to the first byte past the end of the doclist.
143716**
143717** If pp is not NULL, then the contents of the position list are copied
143718** to *pp. *pp is set to point to the first byte past the last byte copied
143719** before this function returns.
143720*/
143721static void fts3PoslistCopy(char **pp, char **ppPoslist){
143722  char *pEnd = *ppPoslist;
143723  char c = 0;
143724
143725  /* The end of a position list is marked by a zero encoded as an FTS3
143726  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
143727  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
143728  ** of some other, multi-byte, value.
143729  **
143730  ** The following while-loop moves pEnd to point to the first byte that is not
143731  ** immediately preceded by a byte with the 0x80 bit set. Then increments
143732  ** pEnd once more so that it points to the byte immediately following the
143733  ** last byte in the position-list.
143734  */
143735  while( *pEnd | c ){
143736    c = *pEnd++ & 0x80;
143737    testcase( c!=0 && (*pEnd)==0 );
143738  }
143739  pEnd++;  /* Advance past the POS_END terminator byte */
143740
143741  if( pp ){
143742    int n = (int)(pEnd - *ppPoslist);
143743    char *p = *pp;
143744    memcpy(p, *ppPoslist, n);
143745    p += n;
143746    *pp = p;
143747  }
143748  *ppPoslist = pEnd;
143749}
143750
143751/*
143752** When this function is called, *ppPoslist is assumed to point to the
143753** start of a column-list. After it returns, *ppPoslist points to the
143754** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
143755**
143756** A column-list is list of delta-encoded positions for a single column
143757** within a single document within a doclist.
143758**
143759** The column-list is terminated either by a POS_COLUMN varint (1) or
143760** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
143761** the POS_COLUMN or POS_END that terminates the column-list.
143762**
143763** If pp is not NULL, then the contents of the column-list are copied
143764** to *pp. *pp is set to point to the first byte past the last byte copied
143765** before this function returns.  The POS_COLUMN or POS_END terminator
143766** is not copied into *pp.
143767*/
143768static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
143769  char *pEnd = *ppPoslist;
143770  char c = 0;
143771
143772  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
143773  ** not part of a multi-byte varint.
143774  */
143775  while( 0xFE & (*pEnd | c) ){
143776    c = *pEnd++ & 0x80;
143777    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
143778  }
143779  if( pp ){
143780    int n = (int)(pEnd - *ppPoslist);
143781    char *p = *pp;
143782    memcpy(p, *ppPoslist, n);
143783    p += n;
143784    *pp = p;
143785  }
143786  *ppPoslist = pEnd;
143787}
143788
143789/*
143790** Value used to signify the end of an position-list. This is safe because
143791** it is not possible to have a document with 2^31 terms.
143792*/
143793#define POSITION_LIST_END 0x7fffffff
143794
143795/*
143796** This function is used to help parse position-lists. When this function is
143797** called, *pp may point to the start of the next varint in the position-list
143798** being parsed, or it may point to 1 byte past the end of the position-list
143799** (in which case **pp will be a terminator bytes POS_END (0) or
143800** (1)).
143801**
143802** If *pp points past the end of the current position-list, set *pi to
143803** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
143804** increment the current value of *pi by the value read, and set *pp to
143805** point to the next value before returning.
143806**
143807** Before calling this routine *pi must be initialized to the value of
143808** the previous position, or zero if we are reading the first position
143809** in the position-list.  Because positions are delta-encoded, the value
143810** of the previous position is needed in order to compute the value of
143811** the next position.
143812*/
143813static void fts3ReadNextPos(
143814  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
143815  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
143816){
143817  if( (**pp)&0xFE ){
143818    fts3GetDeltaVarint(pp, pi);
143819    *pi -= 2;
143820  }else{
143821    *pi = POSITION_LIST_END;
143822  }
143823}
143824
143825/*
143826** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
143827** the value of iCol encoded as a varint to *pp.   This will start a new
143828** column list.
143829**
143830** Set *pp to point to the byte just after the last byte written before
143831** returning (do not modify it if iCol==0). Return the total number of bytes
143832** written (0 if iCol==0).
143833*/
143834static int fts3PutColNumber(char **pp, int iCol){
143835  int n = 0;                      /* Number of bytes written */
143836  if( iCol ){
143837    char *p = *pp;                /* Output pointer */
143838    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
143839    *p = 0x01;
143840    *pp = &p[n];
143841  }
143842  return n;
143843}
143844
143845/*
143846** Compute the union of two position lists.  The output written
143847** into *pp contains all positions of both *pp1 and *pp2 in sorted
143848** order and with any duplicates removed.  All pointers are
143849** updated appropriately.   The caller is responsible for insuring
143850** that there is enough space in *pp to hold the complete output.
143851*/
143852static void fts3PoslistMerge(
143853  char **pp,                      /* Output buffer */
143854  char **pp1,                     /* Left input list */
143855  char **pp2                      /* Right input list */
143856){
143857  char *p = *pp;
143858  char *p1 = *pp1;
143859  char *p2 = *pp2;
143860
143861  while( *p1 || *p2 ){
143862    int iCol1;         /* The current column index in pp1 */
143863    int iCol2;         /* The current column index in pp2 */
143864
143865    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
143866    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
143867    else iCol1 = 0;
143868
143869    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
143870    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
143871    else iCol2 = 0;
143872
143873    if( iCol1==iCol2 ){
143874      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
143875      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
143876      sqlite3_int64 iPrev = 0;
143877      int n = fts3PutColNumber(&p, iCol1);
143878      p1 += n;
143879      p2 += n;
143880
143881      /* At this point, both p1 and p2 point to the start of column-lists
143882      ** for the same column (the column with index iCol1 and iCol2).
143883      ** A column-list is a list of non-negative delta-encoded varints, each
143884      ** incremented by 2 before being stored. Each list is terminated by a
143885      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
143886      ** and writes the results to buffer p. p is left pointing to the byte
143887      ** after the list written. No terminator (POS_END or POS_COLUMN) is
143888      ** written to the output.
143889      */
143890      fts3GetDeltaVarint(&p1, &i1);
143891      fts3GetDeltaVarint(&p2, &i2);
143892      do {
143893        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
143894        iPrev -= 2;
143895        if( i1==i2 ){
143896          fts3ReadNextPos(&p1, &i1);
143897          fts3ReadNextPos(&p2, &i2);
143898        }else if( i1<i2 ){
143899          fts3ReadNextPos(&p1, &i1);
143900        }else{
143901          fts3ReadNextPos(&p2, &i2);
143902        }
143903      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
143904    }else if( iCol1<iCol2 ){
143905      p1 += fts3PutColNumber(&p, iCol1);
143906      fts3ColumnlistCopy(&p, &p1);
143907    }else{
143908      p2 += fts3PutColNumber(&p, iCol2);
143909      fts3ColumnlistCopy(&p, &p2);
143910    }
143911  }
143912
143913  *p++ = POS_END;
143914  *pp = p;
143915  *pp1 = p1 + 1;
143916  *pp2 = p2 + 1;
143917}
143918
143919/*
143920** This function is used to merge two position lists into one. When it is
143921** called, *pp1 and *pp2 must both point to position lists. A position-list is
143922** the part of a doclist that follows each document id. For example, if a row
143923** contains:
143924**
143925**     'a b c'|'x y z'|'a b b a'
143926**
143927** Then the position list for this row for token 'b' would consist of:
143928**
143929**     0x02 0x01 0x02 0x03 0x03 0x00
143930**
143931** When this function returns, both *pp1 and *pp2 are left pointing to the
143932** byte following the 0x00 terminator of their respective position lists.
143933**
143934** If isSaveLeft is 0, an entry is added to the output position list for
143935** each position in *pp2 for which there exists one or more positions in
143936** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
143937** when the *pp1 token appears before the *pp2 token, but not more than nToken
143938** slots before it.
143939**
143940** e.g. nToken==1 searches for adjacent positions.
143941*/
143942static int fts3PoslistPhraseMerge(
143943  char **pp,                      /* IN/OUT: Preallocated output buffer */
143944  int nToken,                     /* Maximum difference in token positions */
143945  int isSaveLeft,                 /* Save the left position */
143946  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
143947  char **pp1,                     /* IN/OUT: Left input list */
143948  char **pp2                      /* IN/OUT: Right input list */
143949){
143950  char *p = *pp;
143951  char *p1 = *pp1;
143952  char *p2 = *pp2;
143953  int iCol1 = 0;
143954  int iCol2 = 0;
143955
143956  /* Never set both isSaveLeft and isExact for the same invocation. */
143957  assert( isSaveLeft==0 || isExact==0 );
143958
143959  assert( p!=0 && *p1!=0 && *p2!=0 );
143960  if( *p1==POS_COLUMN ){
143961    p1++;
143962    p1 += fts3GetVarint32(p1, &iCol1);
143963  }
143964  if( *p2==POS_COLUMN ){
143965    p2++;
143966    p2 += fts3GetVarint32(p2, &iCol2);
143967  }
143968
143969  while( 1 ){
143970    if( iCol1==iCol2 ){
143971      char *pSave = p;
143972      sqlite3_int64 iPrev = 0;
143973      sqlite3_int64 iPos1 = 0;
143974      sqlite3_int64 iPos2 = 0;
143975
143976      if( iCol1 ){
143977        *p++ = POS_COLUMN;
143978        p += sqlite3Fts3PutVarint(p, iCol1);
143979      }
143980
143981      assert( *p1!=POS_END && *p1!=POS_COLUMN );
143982      assert( *p2!=POS_END && *p2!=POS_COLUMN );
143983      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
143984      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
143985
143986      while( 1 ){
143987        if( iPos2==iPos1+nToken
143988         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
143989        ){
143990          sqlite3_int64 iSave;
143991          iSave = isSaveLeft ? iPos1 : iPos2;
143992          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
143993          pSave = 0;
143994          assert( p );
143995        }
143996        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
143997          if( (*p2&0xFE)==0 ) break;
143998          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
143999        }else{
144000          if( (*p1&0xFE)==0 ) break;
144001          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
144002        }
144003      }
144004
144005      if( pSave ){
144006        assert( pp && p );
144007        p = pSave;
144008      }
144009
144010      fts3ColumnlistCopy(0, &p1);
144011      fts3ColumnlistCopy(0, &p2);
144012      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
144013      if( 0==*p1 || 0==*p2 ) break;
144014
144015      p1++;
144016      p1 += fts3GetVarint32(p1, &iCol1);
144017      p2++;
144018      p2 += fts3GetVarint32(p2, &iCol2);
144019    }
144020
144021    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
144022    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
144023    ** end of the position list, or the 0x01 that precedes the next
144024    ** column-number in the position list.
144025    */
144026    else if( iCol1<iCol2 ){
144027      fts3ColumnlistCopy(0, &p1);
144028      if( 0==*p1 ) break;
144029      p1++;
144030      p1 += fts3GetVarint32(p1, &iCol1);
144031    }else{
144032      fts3ColumnlistCopy(0, &p2);
144033      if( 0==*p2 ) break;
144034      p2++;
144035      p2 += fts3GetVarint32(p2, &iCol2);
144036    }
144037  }
144038
144039  fts3PoslistCopy(0, &p2);
144040  fts3PoslistCopy(0, &p1);
144041  *pp1 = p1;
144042  *pp2 = p2;
144043  if( *pp==p ){
144044    return 0;
144045  }
144046  *p++ = 0x00;
144047  *pp = p;
144048  return 1;
144049}
144050
144051/*
144052** Merge two position-lists as required by the NEAR operator. The argument
144053** position lists correspond to the left and right phrases of an expression
144054** like:
144055**
144056**     "phrase 1" NEAR "phrase number 2"
144057**
144058** Position list *pp1 corresponds to the left-hand side of the NEAR
144059** expression and *pp2 to the right. As usual, the indexes in the position
144060** lists are the offsets of the last token in each phrase (tokens "1" and "2"
144061** in the example above).
144062**
144063** The output position list - written to *pp - is a copy of *pp2 with those
144064** entries that are not sufficiently NEAR entries in *pp1 removed.
144065*/
144066static int fts3PoslistNearMerge(
144067  char **pp,                      /* Output buffer */
144068  char *aTmp,                     /* Temporary buffer space */
144069  int nRight,                     /* Maximum difference in token positions */
144070  int nLeft,                      /* Maximum difference in token positions */
144071  char **pp1,                     /* IN/OUT: Left input list */
144072  char **pp2                      /* IN/OUT: Right input list */
144073){
144074  char *p1 = *pp1;
144075  char *p2 = *pp2;
144076
144077  char *pTmp1 = aTmp;
144078  char *pTmp2;
144079  char *aTmp2;
144080  int res = 1;
144081
144082  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
144083  aTmp2 = pTmp2 = pTmp1;
144084  *pp1 = p1;
144085  *pp2 = p2;
144086  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
144087  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
144088    fts3PoslistMerge(pp, &aTmp, &aTmp2);
144089  }else if( pTmp1!=aTmp ){
144090    fts3PoslistCopy(pp, &aTmp);
144091  }else if( pTmp2!=aTmp2 ){
144092    fts3PoslistCopy(pp, &aTmp2);
144093  }else{
144094    res = 0;
144095  }
144096
144097  return res;
144098}
144099
144100/*
144101** An instance of this function is used to merge together the (potentially
144102** large number of) doclists for each term that matches a prefix query.
144103** See function fts3TermSelectMerge() for details.
144104*/
144105typedef struct TermSelect TermSelect;
144106struct TermSelect {
144107  char *aaOutput[16];             /* Malloc'd output buffers */
144108  int anOutput[16];               /* Size each output buffer in bytes */
144109};
144110
144111/*
144112** This function is used to read a single varint from a buffer. Parameter
144113** pEnd points 1 byte past the end of the buffer. When this function is
144114** called, if *pp points to pEnd or greater, then the end of the buffer
144115** has been reached. In this case *pp is set to 0 and the function returns.
144116**
144117** If *pp does not point to or past pEnd, then a single varint is read
144118** from *pp. *pp is then set to point 1 byte past the end of the read varint.
144119**
144120** If bDescIdx is false, the value read is added to *pVal before returning.
144121** If it is true, the value read is subtracted from *pVal before this
144122** function returns.
144123*/
144124static void fts3GetDeltaVarint3(
144125  char **pp,                      /* IN/OUT: Point to read varint from */
144126  char *pEnd,                     /* End of buffer */
144127  int bDescIdx,                   /* True if docids are descending */
144128  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
144129){
144130  if( *pp>=pEnd ){
144131    *pp = 0;
144132  }else{
144133    sqlite3_int64 iVal;
144134    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
144135    if( bDescIdx ){
144136      *pVal -= iVal;
144137    }else{
144138      *pVal += iVal;
144139    }
144140  }
144141}
144142
144143/*
144144** This function is used to write a single varint to a buffer. The varint
144145** is written to *pp. Before returning, *pp is set to point 1 byte past the
144146** end of the value written.
144147**
144148** If *pbFirst is zero when this function is called, the value written to
144149** the buffer is that of parameter iVal.
144150**
144151** If *pbFirst is non-zero when this function is called, then the value
144152** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
144153** (if bDescIdx is non-zero).
144154**
144155** Before returning, this function always sets *pbFirst to 1 and *piPrev
144156** to the value of parameter iVal.
144157*/
144158static void fts3PutDeltaVarint3(
144159  char **pp,                      /* IN/OUT: Output pointer */
144160  int bDescIdx,                   /* True for descending docids */
144161  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
144162  int *pbFirst,                   /* IN/OUT: True after first int written */
144163  sqlite3_int64 iVal              /* Write this value to the list */
144164){
144165  sqlite3_int64 iWrite;
144166  if( bDescIdx==0 || *pbFirst==0 ){
144167    iWrite = iVal - *piPrev;
144168  }else{
144169    iWrite = *piPrev - iVal;
144170  }
144171  assert( *pbFirst || *piPrev==0 );
144172  assert( *pbFirst==0 || iWrite>0 );
144173  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
144174  *piPrev = iVal;
144175  *pbFirst = 1;
144176}
144177
144178
144179/*
144180** This macro is used by various functions that merge doclists. The two
144181** arguments are 64-bit docid values. If the value of the stack variable
144182** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
144183** Otherwise, (i2-i1).
144184**
144185** Using this makes it easier to write code that can merge doclists that are
144186** sorted in either ascending or descending order.
144187*/
144188#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
144189
144190/*
144191** This function does an "OR" merge of two doclists (output contains all
144192** positions contained in either argument doclist). If the docids in the
144193** input doclists are sorted in ascending order, parameter bDescDoclist
144194** should be false. If they are sorted in ascending order, it should be
144195** passed a non-zero value.
144196**
144197** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
144198** containing the output doclist and SQLITE_OK is returned. In this case
144199** *pnOut is set to the number of bytes in the output doclist.
144200**
144201** If an error occurs, an SQLite error code is returned. The output values
144202** are undefined in this case.
144203*/
144204static int fts3DoclistOrMerge(
144205  int bDescDoclist,               /* True if arguments are desc */
144206  char *a1, int n1,               /* First doclist */
144207  char *a2, int n2,               /* Second doclist */
144208  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
144209){
144210  sqlite3_int64 i1 = 0;
144211  sqlite3_int64 i2 = 0;
144212  sqlite3_int64 iPrev = 0;
144213  char *pEnd1 = &a1[n1];
144214  char *pEnd2 = &a2[n2];
144215  char *p1 = a1;
144216  char *p2 = a2;
144217  char *p;
144218  char *aOut;
144219  int bFirstOut = 0;
144220
144221  *paOut = 0;
144222  *pnOut = 0;
144223
144224  /* Allocate space for the output. Both the input and output doclists
144225  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
144226  ** then the first docid in each list is simply encoded as a varint. For
144227  ** each subsequent docid, the varint stored is the difference between the
144228  ** current and previous docid (a positive number - since the list is in
144229  ** ascending order).
144230  **
144231  ** The first docid written to the output is therefore encoded using the
144232  ** same number of bytes as it is in whichever of the input lists it is
144233  ** read from. And each subsequent docid read from the same input list
144234  ** consumes either the same or less bytes as it did in the input (since
144235  ** the difference between it and the previous value in the output must
144236  ** be a positive value less than or equal to the delta value read from
144237  ** the input list). The same argument applies to all but the first docid
144238  ** read from the 'other' list. And to the contents of all position lists
144239  ** that will be copied and merged from the input to the output.
144240  **
144241  ** However, if the first docid copied to the output is a negative number,
144242  ** then the encoding of the first docid from the 'other' input list may
144243  ** be larger in the output than it was in the input (since the delta value
144244  ** may be a larger positive integer than the actual docid).
144245  **
144246  ** The space required to store the output is therefore the sum of the
144247  ** sizes of the two inputs, plus enough space for exactly one of the input
144248  ** docids to grow.
144249  **
144250  ** A symetric argument may be made if the doclists are in descending
144251  ** order.
144252  */
144253  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
144254  if( !aOut ) return SQLITE_NOMEM;
144255
144256  p = aOut;
144257  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
144258  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
144259  while( p1 || p2 ){
144260    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
144261
144262    if( p2 && p1 && iDiff==0 ){
144263      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144264      fts3PoslistMerge(&p, &p1, &p2);
144265      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144266      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144267    }else if( !p2 || (p1 && iDiff<0) ){
144268      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144269      fts3PoslistCopy(&p, &p1);
144270      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144271    }else{
144272      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
144273      fts3PoslistCopy(&p, &p2);
144274      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144275    }
144276  }
144277
144278  *paOut = aOut;
144279  *pnOut = (int)(p-aOut);
144280  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
144281  return SQLITE_OK;
144282}
144283
144284/*
144285** This function does a "phrase" merge of two doclists. In a phrase merge,
144286** the output contains a copy of each position from the right-hand input
144287** doclist for which there is a position in the left-hand input doclist
144288** exactly nDist tokens before it.
144289**
144290** If the docids in the input doclists are sorted in ascending order,
144291** parameter bDescDoclist should be false. If they are sorted in ascending
144292** order, it should be passed a non-zero value.
144293**
144294** The right-hand input doclist is overwritten by this function.
144295*/
144296static int fts3DoclistPhraseMerge(
144297  int bDescDoclist,               /* True if arguments are desc */
144298  int nDist,                      /* Distance from left to right (1=adjacent) */
144299  char *aLeft, int nLeft,         /* Left doclist */
144300  char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
144301){
144302  sqlite3_int64 i1 = 0;
144303  sqlite3_int64 i2 = 0;
144304  sqlite3_int64 iPrev = 0;
144305  char *aRight = *paRight;
144306  char *pEnd1 = &aLeft[nLeft];
144307  char *pEnd2 = &aRight[*pnRight];
144308  char *p1 = aLeft;
144309  char *p2 = aRight;
144310  char *p;
144311  int bFirstOut = 0;
144312  char *aOut;
144313
144314  assert( nDist>0 );
144315  if( bDescDoclist ){
144316    aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
144317    if( aOut==0 ) return SQLITE_NOMEM;
144318  }else{
144319    aOut = aRight;
144320  }
144321  p = aOut;
144322
144323  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
144324  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
144325
144326  while( p1 && p2 ){
144327    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
144328    if( iDiff==0 ){
144329      char *pSave = p;
144330      sqlite3_int64 iPrevSave = iPrev;
144331      int bFirstOutSave = bFirstOut;
144332
144333      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144334      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
144335        p = pSave;
144336        iPrev = iPrevSave;
144337        bFirstOut = bFirstOutSave;
144338      }
144339      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144340      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144341    }else if( iDiff<0 ){
144342      fts3PoslistCopy(0, &p1);
144343      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144344    }else{
144345      fts3PoslistCopy(0, &p2);
144346      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144347    }
144348  }
144349
144350  *pnRight = (int)(p - aOut);
144351  if( bDescDoclist ){
144352    sqlite3_free(aRight);
144353    *paRight = aOut;
144354  }
144355
144356  return SQLITE_OK;
144357}
144358
144359/*
144360** Argument pList points to a position list nList bytes in size. This
144361** function checks to see if the position list contains any entries for
144362** a token in position 0 (of any column). If so, it writes argument iDelta
144363** to the output buffer pOut, followed by a position list consisting only
144364** of the entries from pList at position 0, and terminated by an 0x00 byte.
144365** The value returned is the number of bytes written to pOut (if any).
144366*/
144367SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
144368  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
144369  char *pList,                    /* Position list (no 0x00 term) */
144370  int nList,                      /* Size of pList in bytes */
144371  char *pOut                      /* Write output here */
144372){
144373  int nOut = 0;
144374  int bWritten = 0;               /* True once iDelta has been written */
144375  char *p = pList;
144376  char *pEnd = &pList[nList];
144377
144378  if( *p!=0x01 ){
144379    if( *p==0x02 ){
144380      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
144381      pOut[nOut++] = 0x02;
144382      bWritten = 1;
144383    }
144384    fts3ColumnlistCopy(0, &p);
144385  }
144386
144387  while( p<pEnd && *p==0x01 ){
144388    sqlite3_int64 iCol;
144389    p++;
144390    p += sqlite3Fts3GetVarint(p, &iCol);
144391    if( *p==0x02 ){
144392      if( bWritten==0 ){
144393        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
144394        bWritten = 1;
144395      }
144396      pOut[nOut++] = 0x01;
144397      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
144398      pOut[nOut++] = 0x02;
144399    }
144400    fts3ColumnlistCopy(0, &p);
144401  }
144402  if( bWritten ){
144403    pOut[nOut++] = 0x00;
144404  }
144405
144406  return nOut;
144407}
144408
144409
144410/*
144411** Merge all doclists in the TermSelect.aaOutput[] array into a single
144412** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
144413** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
144414**
144415** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
144416** the responsibility of the caller to free any doclists left in the
144417** TermSelect.aaOutput[] array.
144418*/
144419static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
144420  char *aOut = 0;
144421  int nOut = 0;
144422  int i;
144423
144424  /* Loop through the doclists in the aaOutput[] array. Merge them all
144425  ** into a single doclist.
144426  */
144427  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
144428    if( pTS->aaOutput[i] ){
144429      if( !aOut ){
144430        aOut = pTS->aaOutput[i];
144431        nOut = pTS->anOutput[i];
144432        pTS->aaOutput[i] = 0;
144433      }else{
144434        int nNew;
144435        char *aNew;
144436
144437        int rc = fts3DoclistOrMerge(p->bDescIdx,
144438            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
144439        );
144440        if( rc!=SQLITE_OK ){
144441          sqlite3_free(aOut);
144442          return rc;
144443        }
144444
144445        sqlite3_free(pTS->aaOutput[i]);
144446        sqlite3_free(aOut);
144447        pTS->aaOutput[i] = 0;
144448        aOut = aNew;
144449        nOut = nNew;
144450      }
144451    }
144452  }
144453
144454  pTS->aaOutput[0] = aOut;
144455  pTS->anOutput[0] = nOut;
144456  return SQLITE_OK;
144457}
144458
144459/*
144460** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
144461** as the first argument. The merge is an "OR" merge (see function
144462** fts3DoclistOrMerge() for details).
144463**
144464** This function is called with the doclist for each term that matches
144465** a queried prefix. It merges all these doclists into one, the doclist
144466** for the specified prefix. Since there can be a very large number of
144467** doclists to merge, the merging is done pair-wise using the TermSelect
144468** object.
144469**
144470** This function returns SQLITE_OK if the merge is successful, or an
144471** SQLite error code (SQLITE_NOMEM) if an error occurs.
144472*/
144473static int fts3TermSelectMerge(
144474  Fts3Table *p,                   /* FTS table handle */
144475  TermSelect *pTS,                /* TermSelect object to merge into */
144476  char *aDoclist,                 /* Pointer to doclist */
144477  int nDoclist                    /* Size of aDoclist in bytes */
144478){
144479  if( pTS->aaOutput[0]==0 ){
144480    /* If this is the first term selected, copy the doclist to the output
144481    ** buffer using memcpy().
144482    **
144483    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
144484    ** allocation. This is so as to ensure that the buffer is big enough
144485    ** to hold the current doclist AND'd with any other doclist. If the
144486    ** doclists are stored in order=ASC order, this padding would not be
144487    ** required (since the size of [doclistA AND doclistB] is always less
144488    ** than or equal to the size of [doclistA] in that case). But this is
144489    ** not true for order=DESC. For example, a doclist containing (1, -1)
144490    ** may be smaller than (-1), as in the first example the -1 may be stored
144491    ** as a single-byte delta, whereas in the second it must be stored as a
144492    ** FTS3_VARINT_MAX byte varint.
144493    **
144494    ** Similar padding is added in the fts3DoclistOrMerge() function.
144495    */
144496    pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
144497    pTS->anOutput[0] = nDoclist;
144498    if( pTS->aaOutput[0] ){
144499      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
144500    }else{
144501      return SQLITE_NOMEM;
144502    }
144503  }else{
144504    char *aMerge = aDoclist;
144505    int nMerge = nDoclist;
144506    int iOut;
144507
144508    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
144509      if( pTS->aaOutput[iOut]==0 ){
144510        assert( iOut>0 );
144511        pTS->aaOutput[iOut] = aMerge;
144512        pTS->anOutput[iOut] = nMerge;
144513        break;
144514      }else{
144515        char *aNew;
144516        int nNew;
144517
144518        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
144519            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
144520        );
144521        if( rc!=SQLITE_OK ){
144522          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
144523          return rc;
144524        }
144525
144526        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
144527        sqlite3_free(pTS->aaOutput[iOut]);
144528        pTS->aaOutput[iOut] = 0;
144529
144530        aMerge = aNew;
144531        nMerge = nNew;
144532        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
144533          pTS->aaOutput[iOut] = aMerge;
144534          pTS->anOutput[iOut] = nMerge;
144535        }
144536      }
144537    }
144538  }
144539  return SQLITE_OK;
144540}
144541
144542/*
144543** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
144544*/
144545static int fts3SegReaderCursorAppend(
144546  Fts3MultiSegReader *pCsr,
144547  Fts3SegReader *pNew
144548){
144549  if( (pCsr->nSegment%16)==0 ){
144550    Fts3SegReader **apNew;
144551    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
144552    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
144553    if( !apNew ){
144554      sqlite3Fts3SegReaderFree(pNew);
144555      return SQLITE_NOMEM;
144556    }
144557    pCsr->apSegment = apNew;
144558  }
144559  pCsr->apSegment[pCsr->nSegment++] = pNew;
144560  return SQLITE_OK;
144561}
144562
144563/*
144564** Add seg-reader objects to the Fts3MultiSegReader object passed as the
144565** 8th argument.
144566**
144567** This function returns SQLITE_OK if successful, or an SQLite error code
144568** otherwise.
144569*/
144570static int fts3SegReaderCursor(
144571  Fts3Table *p,                   /* FTS3 table handle */
144572  int iLangid,                    /* Language id */
144573  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
144574  int iLevel,                     /* Level of segments to scan */
144575  const char *zTerm,              /* Term to query for */
144576  int nTerm,                      /* Size of zTerm in bytes */
144577  int isPrefix,                   /* True for a prefix search */
144578  int isScan,                     /* True to scan from zTerm to EOF */
144579  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
144580){
144581  int rc = SQLITE_OK;             /* Error code */
144582  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
144583  int rc2;                        /* Result of sqlite3_reset() */
144584
144585  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
144586  ** for the pending-terms. If this is a scan, then this call must be being
144587  ** made by an fts4aux module, not an FTS table. In this case calling
144588  ** Fts3SegReaderPending might segfault, as the data structures used by
144589  ** fts4aux are not completely populated. So it's easiest to filter these
144590  ** calls out here.  */
144591  if( iLevel<0 && p->aIndex ){
144592    Fts3SegReader *pSeg = 0;
144593    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
144594    if( rc==SQLITE_OK && pSeg ){
144595      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
144596    }
144597  }
144598
144599  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
144600    if( rc==SQLITE_OK ){
144601      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
144602    }
144603
144604    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
144605      Fts3SegReader *pSeg = 0;
144606
144607      /* Read the values returned by the SELECT into local variables. */
144608      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
144609      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
144610      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
144611      int nRoot = sqlite3_column_bytes(pStmt, 4);
144612      char const *zRoot = sqlite3_column_blob(pStmt, 4);
144613
144614      /* If zTerm is not NULL, and this segment is not stored entirely on its
144615      ** root node, the range of leaves scanned can be reduced. Do this. */
144616      if( iStartBlock && zTerm ){
144617        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
144618        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
144619        if( rc!=SQLITE_OK ) goto finished;
144620        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
144621      }
144622
144623      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
144624          (isPrefix==0 && isScan==0),
144625          iStartBlock, iLeavesEndBlock,
144626          iEndBlock, zRoot, nRoot, &pSeg
144627      );
144628      if( rc!=SQLITE_OK ) goto finished;
144629      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
144630    }
144631  }
144632
144633 finished:
144634  rc2 = sqlite3_reset(pStmt);
144635  if( rc==SQLITE_DONE ) rc = rc2;
144636
144637  return rc;
144638}
144639
144640/*
144641** Set up a cursor object for iterating through a full-text index or a
144642** single level therein.
144643*/
144644SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
144645  Fts3Table *p,                   /* FTS3 table handle */
144646  int iLangid,                    /* Language-id to search */
144647  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
144648  int iLevel,                     /* Level of segments to scan */
144649  const char *zTerm,              /* Term to query for */
144650  int nTerm,                      /* Size of zTerm in bytes */
144651  int isPrefix,                   /* True for a prefix search */
144652  int isScan,                     /* True to scan from zTerm to EOF */
144653  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
144654){
144655  assert( iIndex>=0 && iIndex<p->nIndex );
144656  assert( iLevel==FTS3_SEGCURSOR_ALL
144657      ||  iLevel==FTS3_SEGCURSOR_PENDING
144658      ||  iLevel>=0
144659  );
144660  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
144661  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
144662  assert( isPrefix==0 || isScan==0 );
144663
144664  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
144665  return fts3SegReaderCursor(
144666      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
144667  );
144668}
144669
144670/*
144671** In addition to its current configuration, have the Fts3MultiSegReader
144672** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
144673**
144674** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144675*/
144676static int fts3SegReaderCursorAddZero(
144677  Fts3Table *p,                   /* FTS virtual table handle */
144678  int iLangid,
144679  const char *zTerm,              /* Term to scan doclist of */
144680  int nTerm,                      /* Number of bytes in zTerm */
144681  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
144682){
144683  return fts3SegReaderCursor(p,
144684      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
144685  );
144686}
144687
144688/*
144689** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
144690** if isPrefix is true, to scan the doclist for all terms for which
144691** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
144692** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
144693** an SQLite error code.
144694**
144695** It is the responsibility of the caller to free this object by eventually
144696** passing it to fts3SegReaderCursorFree()
144697**
144698** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144699** Output parameter *ppSegcsr is set to 0 if an error occurs.
144700*/
144701static int fts3TermSegReaderCursor(
144702  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
144703  const char *zTerm,              /* Term to query for */
144704  int nTerm,                      /* Size of zTerm in bytes */
144705  int isPrefix,                   /* True for a prefix search */
144706  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
144707){
144708  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
144709  int rc = SQLITE_NOMEM;          /* Return code */
144710
144711  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
144712  if( pSegcsr ){
144713    int i;
144714    int bFound = 0;               /* True once an index has been found */
144715    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
144716
144717    if( isPrefix ){
144718      for(i=1; bFound==0 && i<p->nIndex; i++){
144719        if( p->aIndex[i].nPrefix==nTerm ){
144720          bFound = 1;
144721          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
144722              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
144723          );
144724          pSegcsr->bLookup = 1;
144725        }
144726      }
144727
144728      for(i=1; bFound==0 && i<p->nIndex; i++){
144729        if( p->aIndex[i].nPrefix==nTerm+1 ){
144730          bFound = 1;
144731          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
144732              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
144733          );
144734          if( rc==SQLITE_OK ){
144735            rc = fts3SegReaderCursorAddZero(
144736                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
144737            );
144738          }
144739        }
144740      }
144741    }
144742
144743    if( bFound==0 ){
144744      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
144745          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
144746      );
144747      pSegcsr->bLookup = !isPrefix;
144748    }
144749  }
144750
144751  *ppSegcsr = pSegcsr;
144752  return rc;
144753}
144754
144755/*
144756** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
144757*/
144758static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
144759  sqlite3Fts3SegReaderFinish(pSegcsr);
144760  sqlite3_free(pSegcsr);
144761}
144762
144763/*
144764** This function retrieves the doclist for the specified term (or term
144765** prefix) from the database.
144766*/
144767static int fts3TermSelect(
144768  Fts3Table *p,                   /* Virtual table handle */
144769  Fts3PhraseToken *pTok,          /* Token to query for */
144770  int iColumn,                    /* Column to query (or -ve for all columns) */
144771  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
144772  char **ppOut                    /* OUT: Malloced result buffer */
144773){
144774  int rc;                         /* Return code */
144775  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
144776  TermSelect tsc;                 /* Object for pair-wise doclist merging */
144777  Fts3SegFilter filter;           /* Segment term filter configuration */
144778
144779  pSegcsr = pTok->pSegcsr;
144780  memset(&tsc, 0, sizeof(TermSelect));
144781
144782  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
144783        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
144784        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
144785        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
144786  filter.iCol = iColumn;
144787  filter.zTerm = pTok->z;
144788  filter.nTerm = pTok->n;
144789
144790  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
144791  while( SQLITE_OK==rc
144792      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
144793  ){
144794    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
144795  }
144796
144797  if( rc==SQLITE_OK ){
144798    rc = fts3TermSelectFinishMerge(p, &tsc);
144799  }
144800  if( rc==SQLITE_OK ){
144801    *ppOut = tsc.aaOutput[0];
144802    *pnOut = tsc.anOutput[0];
144803  }else{
144804    int i;
144805    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
144806      sqlite3_free(tsc.aaOutput[i]);
144807    }
144808  }
144809
144810  fts3SegReaderCursorFree(pSegcsr);
144811  pTok->pSegcsr = 0;
144812  return rc;
144813}
144814
144815/*
144816** This function counts the total number of docids in the doclist stored
144817** in buffer aList[], size nList bytes.
144818**
144819** If the isPoslist argument is true, then it is assumed that the doclist
144820** contains a position-list following each docid. Otherwise, it is assumed
144821** that the doclist is simply a list of docids stored as delta encoded
144822** varints.
144823*/
144824static int fts3DoclistCountDocids(char *aList, int nList){
144825  int nDoc = 0;                   /* Return value */
144826  if( aList ){
144827    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
144828    char *p = aList;              /* Cursor */
144829    while( p<aEnd ){
144830      nDoc++;
144831      while( (*p++)&0x80 );     /* Skip docid varint */
144832      fts3PoslistCopy(0, &p);   /* Skip over position list */
144833    }
144834  }
144835
144836  return nDoc;
144837}
144838
144839/*
144840** Advance the cursor to the next row in the %_content table that
144841** matches the search criteria.  For a MATCH search, this will be
144842** the next row that matches. For a full-table scan, this will be
144843** simply the next row in the %_content table.  For a docid lookup,
144844** this routine simply sets the EOF flag.
144845**
144846** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
144847** even if we reach end-of-file.  The fts3EofMethod() will be called
144848** subsequently to determine whether or not an EOF was hit.
144849*/
144850static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
144851  int rc;
144852  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144853  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
144854    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
144855      pCsr->isEof = 1;
144856      rc = sqlite3_reset(pCsr->pStmt);
144857    }else{
144858      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
144859      rc = SQLITE_OK;
144860    }
144861  }else{
144862    rc = fts3EvalNext((Fts3Cursor *)pCursor);
144863  }
144864  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144865  return rc;
144866}
144867
144868/*
144869** The following are copied from sqliteInt.h.
144870**
144871** Constants for the largest and smallest possible 64-bit signed integers.
144872** These macros are designed to work correctly on both 32-bit and 64-bit
144873** compilers.
144874*/
144875#ifndef SQLITE_AMALGAMATION
144876# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
144877# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
144878#endif
144879
144880/*
144881** If the numeric type of argument pVal is "integer", then return it
144882** converted to a 64-bit signed integer. Otherwise, return a copy of
144883** the second parameter, iDefault.
144884*/
144885static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
144886  if( pVal ){
144887    int eType = sqlite3_value_numeric_type(pVal);
144888    if( eType==SQLITE_INTEGER ){
144889      return sqlite3_value_int64(pVal);
144890    }
144891  }
144892  return iDefault;
144893}
144894
144895/*
144896** This is the xFilter interface for the virtual table.  See
144897** the virtual table xFilter method documentation for additional
144898** information.
144899**
144900** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
144901** the %_content table.
144902**
144903** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
144904** in the %_content table.
144905**
144906** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
144907** column on the left-hand side of the MATCH operator is column
144908** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
144909** side of the MATCH operator.
144910*/
144911static int fts3FilterMethod(
144912  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
144913  int idxNum,                     /* Strategy index */
144914  const char *idxStr,             /* Unused */
144915  int nVal,                       /* Number of elements in apVal */
144916  sqlite3_value **apVal           /* Arguments for the indexing scheme */
144917){
144918  int rc = SQLITE_OK;
144919  char *zSql;                     /* SQL statement used to access %_content */
144920  int eSearch;
144921  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
144922  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144923
144924  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
144925  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
144926  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
144927  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
144928  int iIdx;
144929
144930  UNUSED_PARAMETER(idxStr);
144931  UNUSED_PARAMETER(nVal);
144932
144933  eSearch = (idxNum & 0x0000FFFF);
144934  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
144935  assert( p->pSegments==0 );
144936
144937  /* Collect arguments into local variables */
144938  iIdx = 0;
144939  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
144940  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
144941  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
144942  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
144943  assert( iIdx==nVal );
144944
144945  /* In case the cursor has been used before, clear it now. */
144946  sqlite3_finalize(pCsr->pStmt);
144947  sqlite3_free(pCsr->aDoclist);
144948  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
144949  sqlite3Fts3ExprFree(pCsr->pExpr);
144950  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
144951
144952  /* Set the lower and upper bounds on docids to return */
144953  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
144954  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
144955
144956  if( idxStr ){
144957    pCsr->bDesc = (idxStr[0]=='D');
144958  }else{
144959    pCsr->bDesc = p->bDescIdx;
144960  }
144961  pCsr->eSearch = (i16)eSearch;
144962
144963  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
144964    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
144965    const char *zQuery = (const char *)sqlite3_value_text(pCons);
144966
144967    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
144968      return SQLITE_NOMEM;
144969    }
144970
144971    pCsr->iLangid = 0;
144972    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
144973
144974    assert( p->base.zErrMsg==0 );
144975    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
144976        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
144977        &p->base.zErrMsg
144978    );
144979    if( rc!=SQLITE_OK ){
144980      return rc;
144981    }
144982
144983    rc = fts3EvalStart(pCsr);
144984    sqlite3Fts3SegmentsClose(p);
144985    if( rc!=SQLITE_OK ) return rc;
144986    pCsr->pNextId = pCsr->aDoclist;
144987    pCsr->iPrevId = 0;
144988  }
144989
144990  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
144991  ** statement loops through all rows of the %_content table. For a
144992  ** full-text query or docid lookup, the statement retrieves a single
144993  ** row by docid.
144994  */
144995  if( eSearch==FTS3_FULLSCAN_SEARCH ){
144996    if( pDocidGe || pDocidLe ){
144997      zSql = sqlite3_mprintf(
144998          "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
144999          p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
145000          (pCsr->bDesc ? "DESC" : "ASC")
145001      );
145002    }else{
145003      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
145004          p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
145005      );
145006    }
145007    if( zSql ){
145008      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
145009      sqlite3_free(zSql);
145010    }else{
145011      rc = SQLITE_NOMEM;
145012    }
145013  }else if( eSearch==FTS3_DOCID_SEARCH ){
145014    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
145015    if( rc==SQLITE_OK ){
145016      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
145017    }
145018  }
145019  if( rc!=SQLITE_OK ) return rc;
145020
145021  return fts3NextMethod(pCursor);
145022}
145023
145024/*
145025** This is the xEof method of the virtual table. SQLite calls this
145026** routine to find out if it has reached the end of a result set.
145027*/
145028static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
145029  return ((Fts3Cursor *)pCursor)->isEof;
145030}
145031
145032/*
145033** This is the xRowid method. The SQLite core calls this routine to
145034** retrieve the rowid for the current row of the result set. fts3
145035** exposes %_content.docid as the rowid for the virtual table. The
145036** rowid should be written to *pRowid.
145037*/
145038static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
145039  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
145040  *pRowid = pCsr->iPrevId;
145041  return SQLITE_OK;
145042}
145043
145044/*
145045** This is the xColumn method, called by SQLite to request a value from
145046** the row that the supplied cursor currently points to.
145047**
145048** If:
145049**
145050**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
145051**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
145052**   (iCol == p->nColumn+1) -> Docid column
145053**   (iCol == p->nColumn+2) -> Langid column
145054*/
145055static int fts3ColumnMethod(
145056  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145057  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
145058  int iCol                        /* Index of column to read value from */
145059){
145060  int rc = SQLITE_OK;             /* Return Code */
145061  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
145062  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
145063
145064  /* The column value supplied by SQLite must be in range. */
145065  assert( iCol>=0 && iCol<=p->nColumn+2 );
145066
145067  if( iCol==p->nColumn+1 ){
145068    /* This call is a request for the "docid" column. Since "docid" is an
145069    ** alias for "rowid", use the xRowid() method to obtain the value.
145070    */
145071    sqlite3_result_int64(pCtx, pCsr->iPrevId);
145072  }else if( iCol==p->nColumn ){
145073    /* The extra column whose name is the same as the table.
145074    ** Return a blob which is a pointer to the cursor.  */
145075    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
145076  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
145077    sqlite3_result_int64(pCtx, pCsr->iLangid);
145078  }else{
145079    /* The requested column is either a user column (one that contains
145080    ** indexed data), or the language-id column.  */
145081    rc = fts3CursorSeek(0, pCsr);
145082
145083    if( rc==SQLITE_OK ){
145084      if( iCol==p->nColumn+2 ){
145085        int iLangid = 0;
145086        if( p->zLanguageid ){
145087          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
145088        }
145089        sqlite3_result_int(pCtx, iLangid);
145090      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
145091        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
145092      }
145093    }
145094  }
145095
145096  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
145097  return rc;
145098}
145099
145100/*
145101** This function is the implementation of the xUpdate callback used by
145102** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
145103** inserted, updated or deleted.
145104*/
145105static int fts3UpdateMethod(
145106  sqlite3_vtab *pVtab,            /* Virtual table handle */
145107  int nArg,                       /* Size of argument array */
145108  sqlite3_value **apVal,          /* Array of arguments */
145109  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
145110){
145111  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
145112}
145113
145114/*
145115** Implementation of xSync() method. Flush the contents of the pending-terms
145116** hash-table to the database.
145117*/
145118static int fts3SyncMethod(sqlite3_vtab *pVtab){
145119
145120  /* Following an incremental-merge operation, assuming that the input
145121  ** segments are not completely consumed (the usual case), they are updated
145122  ** in place to remove the entries that have already been merged. This
145123  ** involves updating the leaf block that contains the smallest unmerged
145124  ** entry and each block (if any) between the leaf and the root node. So
145125  ** if the height of the input segment b-trees is N, and input segments
145126  ** are merged eight at a time, updating the input segments at the end
145127  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
145128  ** small - often between 0 and 2. So the overhead of the incremental
145129  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
145130  ** dwarfing the actual productive work accomplished, the incremental merge
145131  ** is only attempted if it will write at least 64 leaf blocks. Hence
145132  ** nMinMerge.
145133  **
145134  ** Of course, updating the input segments also involves deleting a bunch
145135  ** of blocks from the segments table. But this is not considered overhead
145136  ** as it would also be required by a crisis-merge that used the same input
145137  ** segments.
145138  */
145139  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
145140
145141  Fts3Table *p = (Fts3Table*)pVtab;
145142  int rc = sqlite3Fts3PendingTermsFlush(p);
145143
145144  if( rc==SQLITE_OK
145145   && p->nLeafAdd>(nMinMerge/16)
145146   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
145147  ){
145148    int mxLevel = 0;              /* Maximum relative level value in db */
145149    int A;                        /* Incr-merge parameter A */
145150
145151    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
145152    assert( rc==SQLITE_OK || mxLevel==0 );
145153    A = p->nLeafAdd * mxLevel;
145154    A += (A/2);
145155    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
145156  }
145157  sqlite3Fts3SegmentsClose(p);
145158  return rc;
145159}
145160
145161/*
145162** If it is currently unknown whether or not the FTS table has an %_stat
145163** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
145164** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
145165** if an error occurs.
145166*/
145167static int fts3SetHasStat(Fts3Table *p){
145168  int rc = SQLITE_OK;
145169  if( p->bHasStat==2 ){
145170    const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
145171    char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
145172    if( zSql ){
145173      sqlite3_stmt *pStmt = 0;
145174      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
145175      if( rc==SQLITE_OK ){
145176        int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
145177        rc = sqlite3_finalize(pStmt);
145178        if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
145179      }
145180      sqlite3_free(zSql);
145181    }else{
145182      rc = SQLITE_NOMEM;
145183    }
145184  }
145185  return rc;
145186}
145187
145188/*
145189** Implementation of xBegin() method.
145190*/
145191static int fts3BeginMethod(sqlite3_vtab *pVtab){
145192  Fts3Table *p = (Fts3Table*)pVtab;
145193  UNUSED_PARAMETER(pVtab);
145194  assert( p->pSegments==0 );
145195  assert( p->nPendingData==0 );
145196  assert( p->inTransaction!=1 );
145197  TESTONLY( p->inTransaction = 1 );
145198  TESTONLY( p->mxSavepoint = -1; );
145199  p->nLeafAdd = 0;
145200  return fts3SetHasStat(p);
145201}
145202
145203/*
145204** Implementation of xCommit() method. This is a no-op. The contents of
145205** the pending-terms hash-table have already been flushed into the database
145206** by fts3SyncMethod().
145207*/
145208static int fts3CommitMethod(sqlite3_vtab *pVtab){
145209  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
145210  UNUSED_PARAMETER(pVtab);
145211  assert( p->nPendingData==0 );
145212  assert( p->inTransaction!=0 );
145213  assert( p->pSegments==0 );
145214  TESTONLY( p->inTransaction = 0 );
145215  TESTONLY( p->mxSavepoint = -1; );
145216  return SQLITE_OK;
145217}
145218
145219/*
145220** Implementation of xRollback(). Discard the contents of the pending-terms
145221** hash-table. Any changes made to the database are reverted by SQLite.
145222*/
145223static int fts3RollbackMethod(sqlite3_vtab *pVtab){
145224  Fts3Table *p = (Fts3Table*)pVtab;
145225  sqlite3Fts3PendingTermsClear(p);
145226  assert( p->inTransaction!=0 );
145227  TESTONLY( p->inTransaction = 0 );
145228  TESTONLY( p->mxSavepoint = -1; );
145229  return SQLITE_OK;
145230}
145231
145232/*
145233** When called, *ppPoslist must point to the byte immediately following the
145234** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
145235** moves *ppPoslist so that it instead points to the first byte of the
145236** same position list.
145237*/
145238static void fts3ReversePoslist(char *pStart, char **ppPoslist){
145239  char *p = &(*ppPoslist)[-2];
145240  char c = 0;
145241
145242  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
145243  while( p>pStart && (c=*p--)==0 );
145244
145245  /* Search backwards for a varint with value zero (the end of the previous
145246  ** poslist). This is an 0x00 byte preceded by some byte that does not
145247  ** have the 0x80 bit set.  */
145248  while( p>pStart && (*p & 0x80) | c ){
145249    c = *p--;
145250  }
145251  assert( p==pStart || c==0 );
145252
145253  /* At this point p points to that preceding byte without the 0x80 bit
145254  ** set. So to find the start of the poslist, skip forward 2 bytes then
145255  ** over a varint.
145256  **
145257  ** Normally. The other case is that p==pStart and the poslist to return
145258  ** is the first in the doclist. In this case do not skip forward 2 bytes.
145259  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
145260  ** is required for cases where the first byte of a doclist and the
145261  ** doclist is empty. For example, if the first docid is 10, a doclist
145262  ** that begins with:
145263  **
145264  **   0x0A 0x00 <next docid delta varint>
145265  */
145266  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
145267  while( *p++&0x80 );
145268  *ppPoslist = p;
145269}
145270
145271/*
145272** Helper function used by the implementation of the overloaded snippet(),
145273** offsets() and optimize() SQL functions.
145274**
145275** If the value passed as the third argument is a blob of size
145276** sizeof(Fts3Cursor*), then the blob contents are copied to the
145277** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
145278** message is written to context pContext and SQLITE_ERROR returned. The
145279** string passed via zFunc is used as part of the error message.
145280*/
145281static int fts3FunctionArg(
145282  sqlite3_context *pContext,      /* SQL function call context */
145283  const char *zFunc,              /* Function name */
145284  sqlite3_value *pVal,            /* argv[0] passed to function */
145285  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
145286){
145287  Fts3Cursor *pRet;
145288  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
145289   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
145290  ){
145291    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
145292    sqlite3_result_error(pContext, zErr, -1);
145293    sqlite3_free(zErr);
145294    return SQLITE_ERROR;
145295  }
145296  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
145297  *ppCsr = pRet;
145298  return SQLITE_OK;
145299}
145300
145301/*
145302** Implementation of the snippet() function for FTS3
145303*/
145304static void fts3SnippetFunc(
145305  sqlite3_context *pContext,      /* SQLite function call context */
145306  int nVal,                       /* Size of apVal[] array */
145307  sqlite3_value **apVal           /* Array of arguments */
145308){
145309  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145310  const char *zStart = "<b>";
145311  const char *zEnd = "</b>";
145312  const char *zEllipsis = "<b>...</b>";
145313  int iCol = -1;
145314  int nToken = 15;                /* Default number of tokens in snippet */
145315
145316  /* There must be at least one argument passed to this function (otherwise
145317  ** the non-overloaded version would have been called instead of this one).
145318  */
145319  assert( nVal>=1 );
145320
145321  if( nVal>6 ){
145322    sqlite3_result_error(pContext,
145323        "wrong number of arguments to function snippet()", -1);
145324    return;
145325  }
145326  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
145327
145328  switch( nVal ){
145329    case 6: nToken = sqlite3_value_int(apVal[5]);
145330    case 5: iCol = sqlite3_value_int(apVal[4]);
145331    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
145332    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
145333    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
145334  }
145335  if( !zEllipsis || !zEnd || !zStart ){
145336    sqlite3_result_error_nomem(pContext);
145337  }else if( nToken==0 ){
145338    sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
145339  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
145340    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
145341  }
145342}
145343
145344/*
145345** Implementation of the offsets() function for FTS3
145346*/
145347static void fts3OffsetsFunc(
145348  sqlite3_context *pContext,      /* SQLite function call context */
145349  int nVal,                       /* Size of argument array */
145350  sqlite3_value **apVal           /* Array of arguments */
145351){
145352  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145353
145354  UNUSED_PARAMETER(nVal);
145355
145356  assert( nVal==1 );
145357  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
145358  assert( pCsr );
145359  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
145360    sqlite3Fts3Offsets(pContext, pCsr);
145361  }
145362}
145363
145364/*
145365** Implementation of the special optimize() function for FTS3. This
145366** function merges all segments in the database to a single segment.
145367** Example usage is:
145368**
145369**   SELECT optimize(t) FROM t LIMIT 1;
145370**
145371** where 't' is the name of an FTS3 table.
145372*/
145373static void fts3OptimizeFunc(
145374  sqlite3_context *pContext,      /* SQLite function call context */
145375  int nVal,                       /* Size of argument array */
145376  sqlite3_value **apVal           /* Array of arguments */
145377){
145378  int rc;                         /* Return code */
145379  Fts3Table *p;                   /* Virtual table handle */
145380  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
145381
145382  UNUSED_PARAMETER(nVal);
145383
145384  assert( nVal==1 );
145385  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
145386  p = (Fts3Table *)pCursor->base.pVtab;
145387  assert( p );
145388
145389  rc = sqlite3Fts3Optimize(p);
145390
145391  switch( rc ){
145392    case SQLITE_OK:
145393      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
145394      break;
145395    case SQLITE_DONE:
145396      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
145397      break;
145398    default:
145399      sqlite3_result_error_code(pContext, rc);
145400      break;
145401  }
145402}
145403
145404/*
145405** Implementation of the matchinfo() function for FTS3
145406*/
145407static void fts3MatchinfoFunc(
145408  sqlite3_context *pContext,      /* SQLite function call context */
145409  int nVal,                       /* Size of argument array */
145410  sqlite3_value **apVal           /* Array of arguments */
145411){
145412  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145413  assert( nVal==1 || nVal==2 );
145414  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
145415    const char *zArg = 0;
145416    if( nVal>1 ){
145417      zArg = (const char *)sqlite3_value_text(apVal[1]);
145418    }
145419    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
145420  }
145421}
145422
145423/*
145424** This routine implements the xFindFunction method for the FTS3
145425** virtual table.
145426*/
145427static int fts3FindFunctionMethod(
145428  sqlite3_vtab *pVtab,            /* Virtual table handle */
145429  int nArg,                       /* Number of SQL function arguments */
145430  const char *zName,              /* Name of SQL function */
145431  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
145432  void **ppArg                    /* Unused */
145433){
145434  struct Overloaded {
145435    const char *zName;
145436    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
145437  } aOverload[] = {
145438    { "snippet", fts3SnippetFunc },
145439    { "offsets", fts3OffsetsFunc },
145440    { "optimize", fts3OptimizeFunc },
145441    { "matchinfo", fts3MatchinfoFunc },
145442  };
145443  int i;                          /* Iterator variable */
145444
145445  UNUSED_PARAMETER(pVtab);
145446  UNUSED_PARAMETER(nArg);
145447  UNUSED_PARAMETER(ppArg);
145448
145449  for(i=0; i<SizeofArray(aOverload); i++){
145450    if( strcmp(zName, aOverload[i].zName)==0 ){
145451      *pxFunc = aOverload[i].xFunc;
145452      return 1;
145453    }
145454  }
145455
145456  /* No function of the specified name was found. Return 0. */
145457  return 0;
145458}
145459
145460/*
145461** Implementation of FTS3 xRename method. Rename an fts3 table.
145462*/
145463static int fts3RenameMethod(
145464  sqlite3_vtab *pVtab,            /* Virtual table handle */
145465  const char *zName               /* New name of table */
145466){
145467  Fts3Table *p = (Fts3Table *)pVtab;
145468  sqlite3 *db = p->db;            /* Database connection */
145469  int rc;                         /* Return Code */
145470
145471  /* At this point it must be known if the %_stat table exists or not.
145472  ** So bHasStat may not be 2.  */
145473  rc = fts3SetHasStat(p);
145474
145475  /* As it happens, the pending terms table is always empty here. This is
145476  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
145477  ** always opens a savepoint transaction. And the xSavepoint() method
145478  ** flushes the pending terms table. But leave the (no-op) call to
145479  ** PendingTermsFlush() in in case that changes.
145480  */
145481  assert( p->nPendingData==0 );
145482  if( rc==SQLITE_OK ){
145483    rc = sqlite3Fts3PendingTermsFlush(p);
145484  }
145485
145486  if( p->zContentTbl==0 ){
145487    fts3DbExec(&rc, db,
145488      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
145489      p->zDb, p->zName, zName
145490    );
145491  }
145492
145493  if( p->bHasDocsize ){
145494    fts3DbExec(&rc, db,
145495      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
145496      p->zDb, p->zName, zName
145497    );
145498  }
145499  if( p->bHasStat ){
145500    fts3DbExec(&rc, db,
145501      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
145502      p->zDb, p->zName, zName
145503    );
145504  }
145505  fts3DbExec(&rc, db,
145506    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
145507    p->zDb, p->zName, zName
145508  );
145509  fts3DbExec(&rc, db,
145510    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
145511    p->zDb, p->zName, zName
145512  );
145513  return rc;
145514}
145515
145516/*
145517** The xSavepoint() method.
145518**
145519** Flush the contents of the pending-terms table to disk.
145520*/
145521static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
145522  int rc = SQLITE_OK;
145523  UNUSED_PARAMETER(iSavepoint);
145524  assert( ((Fts3Table *)pVtab)->inTransaction );
145525  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
145526  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
145527  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
145528    rc = fts3SyncMethod(pVtab);
145529  }
145530  return rc;
145531}
145532
145533/*
145534** The xRelease() method.
145535**
145536** This is a no-op.
145537*/
145538static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
145539  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
145540  UNUSED_PARAMETER(iSavepoint);
145541  UNUSED_PARAMETER(pVtab);
145542  assert( p->inTransaction );
145543  assert( p->mxSavepoint >= iSavepoint );
145544  TESTONLY( p->mxSavepoint = iSavepoint-1 );
145545  return SQLITE_OK;
145546}
145547
145548/*
145549** The xRollbackTo() method.
145550**
145551** Discard the contents of the pending terms table.
145552*/
145553static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
145554  Fts3Table *p = (Fts3Table*)pVtab;
145555  UNUSED_PARAMETER(iSavepoint);
145556  assert( p->inTransaction );
145557  assert( p->mxSavepoint >= iSavepoint );
145558  TESTONLY( p->mxSavepoint = iSavepoint );
145559  sqlite3Fts3PendingTermsClear(p);
145560  return SQLITE_OK;
145561}
145562
145563static const sqlite3_module fts3Module = {
145564  /* iVersion      */ 2,
145565  /* xCreate       */ fts3CreateMethod,
145566  /* xConnect      */ fts3ConnectMethod,
145567  /* xBestIndex    */ fts3BestIndexMethod,
145568  /* xDisconnect   */ fts3DisconnectMethod,
145569  /* xDestroy      */ fts3DestroyMethod,
145570  /* xOpen         */ fts3OpenMethod,
145571  /* xClose        */ fts3CloseMethod,
145572  /* xFilter       */ fts3FilterMethod,
145573  /* xNext         */ fts3NextMethod,
145574  /* xEof          */ fts3EofMethod,
145575  /* xColumn       */ fts3ColumnMethod,
145576  /* xRowid        */ fts3RowidMethod,
145577  /* xUpdate       */ fts3UpdateMethod,
145578  /* xBegin        */ fts3BeginMethod,
145579  /* xSync         */ fts3SyncMethod,
145580  /* xCommit       */ fts3CommitMethod,
145581  /* xRollback     */ fts3RollbackMethod,
145582  /* xFindFunction */ fts3FindFunctionMethod,
145583  /* xRename */       fts3RenameMethod,
145584  /* xSavepoint    */ fts3SavepointMethod,
145585  /* xRelease      */ fts3ReleaseMethod,
145586  /* xRollbackTo   */ fts3RollbackToMethod,
145587};
145588
145589/*
145590** This function is registered as the module destructor (called when an
145591** FTS3 enabled database connection is closed). It frees the memory
145592** allocated for the tokenizer hash table.
145593*/
145594static void hashDestroy(void *p){
145595  Fts3Hash *pHash = (Fts3Hash *)p;
145596  sqlite3Fts3HashClear(pHash);
145597  sqlite3_free(pHash);
145598}
145599
145600/*
145601** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
145602** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
145603** respectively. The following three forward declarations are for functions
145604** declared in these files used to retrieve the respective implementations.
145605**
145606** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
145607** to by the argument to point to the "simple" tokenizer implementation.
145608** And so on.
145609*/
145610SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145611SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145612#ifndef SQLITE_DISABLE_FTS3_UNICODE
145613SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
145614#endif
145615#ifdef SQLITE_ENABLE_ICU
145616SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145617#endif
145618
145619/*
145620** Initialize the fts3 extension. If this extension is built as part
145621** of the sqlite library, then this function is called directly by
145622** SQLite. If fts3 is built as a dynamically loadable extension, this
145623** function is called by the sqlite3_extension_init() entry point.
145624*/
145625SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
145626  int rc = SQLITE_OK;
145627  Fts3Hash *pHash = 0;
145628  const sqlite3_tokenizer_module *pSimple = 0;
145629  const sqlite3_tokenizer_module *pPorter = 0;
145630#ifndef SQLITE_DISABLE_FTS3_UNICODE
145631  const sqlite3_tokenizer_module *pUnicode = 0;
145632#endif
145633
145634#ifdef SQLITE_ENABLE_ICU
145635  const sqlite3_tokenizer_module *pIcu = 0;
145636  sqlite3Fts3IcuTokenizerModule(&pIcu);
145637#endif
145638
145639#ifndef SQLITE_DISABLE_FTS3_UNICODE
145640  sqlite3Fts3UnicodeTokenizer(&pUnicode);
145641#endif
145642
145643#ifdef SQLITE_TEST
145644  rc = sqlite3Fts3InitTerm(db);
145645  if( rc!=SQLITE_OK ) return rc;
145646#endif
145647
145648  rc = sqlite3Fts3InitAux(db);
145649  if( rc!=SQLITE_OK ) return rc;
145650
145651  sqlite3Fts3SimpleTokenizerModule(&pSimple);
145652  sqlite3Fts3PorterTokenizerModule(&pPorter);
145653
145654  /* Allocate and initialize the hash-table used to store tokenizers. */
145655  pHash = sqlite3_malloc(sizeof(Fts3Hash));
145656  if( !pHash ){
145657    rc = SQLITE_NOMEM;
145658  }else{
145659    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
145660  }
145661
145662  /* Load the built-in tokenizers into the hash table */
145663  if( rc==SQLITE_OK ){
145664    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
145665     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
145666
145667#ifndef SQLITE_DISABLE_FTS3_UNICODE
145668     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
145669#endif
145670#ifdef SQLITE_ENABLE_ICU
145671     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
145672#endif
145673    ){
145674      rc = SQLITE_NOMEM;
145675    }
145676  }
145677
145678#ifdef SQLITE_TEST
145679  if( rc==SQLITE_OK ){
145680    rc = sqlite3Fts3ExprInitTestInterface(db);
145681  }
145682#endif
145683
145684  /* Create the virtual table wrapper around the hash-table and overload
145685  ** the two scalar functions. If this is successful, register the
145686  ** module with sqlite.
145687  */
145688  if( SQLITE_OK==rc
145689   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
145690   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
145691   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
145692   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
145693   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
145694   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
145695  ){
145696    rc = sqlite3_create_module_v2(
145697        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
145698    );
145699    if( rc==SQLITE_OK ){
145700      rc = sqlite3_create_module_v2(
145701          db, "fts4", &fts3Module, (void *)pHash, 0
145702      );
145703    }
145704    if( rc==SQLITE_OK ){
145705      rc = sqlite3Fts3InitTok(db, (void *)pHash);
145706    }
145707    return rc;
145708  }
145709
145710
145711  /* An error has occurred. Delete the hash table and return the error code. */
145712  assert( rc!=SQLITE_OK );
145713  if( pHash ){
145714    sqlite3Fts3HashClear(pHash);
145715    sqlite3_free(pHash);
145716  }
145717  return rc;
145718}
145719
145720/*
145721** Allocate an Fts3MultiSegReader for each token in the expression headed
145722** by pExpr.
145723**
145724** An Fts3SegReader object is a cursor that can seek or scan a range of
145725** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
145726** Fts3SegReader objects internally to provide an interface to seek or scan
145727** within the union of all segments of a b-tree. Hence the name.
145728**
145729** If the allocated Fts3MultiSegReader just seeks to a single entry in a
145730** segment b-tree (if the term is not a prefix or it is a prefix for which
145731** there exists prefix b-tree of the right length) then it may be traversed
145732** and merged incrementally. Otherwise, it has to be merged into an in-memory
145733** doclist and then traversed.
145734*/
145735static void fts3EvalAllocateReaders(
145736  Fts3Cursor *pCsr,               /* FTS cursor handle */
145737  Fts3Expr *pExpr,                /* Allocate readers for this expression */
145738  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
145739  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
145740  int *pRc                        /* IN/OUT: Error code */
145741){
145742  if( pExpr && SQLITE_OK==*pRc ){
145743    if( pExpr->eType==FTSQUERY_PHRASE ){
145744      int i;
145745      int nToken = pExpr->pPhrase->nToken;
145746      *pnToken += nToken;
145747      for(i=0; i<nToken; i++){
145748        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
145749        int rc = fts3TermSegReaderCursor(pCsr,
145750            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
145751        );
145752        if( rc!=SQLITE_OK ){
145753          *pRc = rc;
145754          return;
145755        }
145756      }
145757      assert( pExpr->pPhrase->iDoclistToken==0 );
145758      pExpr->pPhrase->iDoclistToken = -1;
145759    }else{
145760      *pnOr += (pExpr->eType==FTSQUERY_OR);
145761      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
145762      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
145763    }
145764  }
145765}
145766
145767/*
145768** Arguments pList/nList contain the doclist for token iToken of phrase p.
145769** It is merged into the main doclist stored in p->doclist.aAll/nAll.
145770**
145771** This function assumes that pList points to a buffer allocated using
145772** sqlite3_malloc(). This function takes responsibility for eventually
145773** freeing the buffer.
145774**
145775** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
145776*/
145777static int fts3EvalPhraseMergeToken(
145778  Fts3Table *pTab,                /* FTS Table pointer */
145779  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
145780  int iToken,                     /* Token pList/nList corresponds to */
145781  char *pList,                    /* Pointer to doclist */
145782  int nList                       /* Number of bytes in pList */
145783){
145784  int rc = SQLITE_OK;
145785  assert( iToken!=p->iDoclistToken );
145786
145787  if( pList==0 ){
145788    sqlite3_free(p->doclist.aAll);
145789    p->doclist.aAll = 0;
145790    p->doclist.nAll = 0;
145791  }
145792
145793  else if( p->iDoclistToken<0 ){
145794    p->doclist.aAll = pList;
145795    p->doclist.nAll = nList;
145796  }
145797
145798  else if( p->doclist.aAll==0 ){
145799    sqlite3_free(pList);
145800  }
145801
145802  else {
145803    char *pLeft;
145804    char *pRight;
145805    int nLeft;
145806    int nRight;
145807    int nDiff;
145808
145809    if( p->iDoclistToken<iToken ){
145810      pLeft = p->doclist.aAll;
145811      nLeft = p->doclist.nAll;
145812      pRight = pList;
145813      nRight = nList;
145814      nDiff = iToken - p->iDoclistToken;
145815    }else{
145816      pRight = p->doclist.aAll;
145817      nRight = p->doclist.nAll;
145818      pLeft = pList;
145819      nLeft = nList;
145820      nDiff = p->iDoclistToken - iToken;
145821    }
145822
145823    rc = fts3DoclistPhraseMerge(
145824        pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
145825    );
145826    sqlite3_free(pLeft);
145827    p->doclist.aAll = pRight;
145828    p->doclist.nAll = nRight;
145829  }
145830
145831  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
145832  return rc;
145833}
145834
145835/*
145836** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
145837** does not take deferred tokens into account.
145838**
145839** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145840*/
145841static int fts3EvalPhraseLoad(
145842  Fts3Cursor *pCsr,               /* FTS Cursor handle */
145843  Fts3Phrase *p                   /* Phrase object */
145844){
145845  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145846  int iToken;
145847  int rc = SQLITE_OK;
145848
145849  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
145850    Fts3PhraseToken *pToken = &p->aToken[iToken];
145851    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
145852
145853    if( pToken->pSegcsr ){
145854      int nThis = 0;
145855      char *pThis = 0;
145856      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
145857      if( rc==SQLITE_OK ){
145858        rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
145859      }
145860    }
145861    assert( pToken->pSegcsr==0 );
145862  }
145863
145864  return rc;
145865}
145866
145867/*
145868** This function is called on each phrase after the position lists for
145869** any deferred tokens have been loaded into memory. It updates the phrases
145870** current position list to include only those positions that are really
145871** instances of the phrase (after considering deferred tokens). If this
145872** means that the phrase does not appear in the current row, doclist.pList
145873** and doclist.nList are both zeroed.
145874**
145875** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145876*/
145877static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
145878  int iToken;                     /* Used to iterate through phrase tokens */
145879  char *aPoslist = 0;             /* Position list for deferred tokens */
145880  int nPoslist = 0;               /* Number of bytes in aPoslist */
145881  int iPrev = -1;                 /* Token number of previous deferred token */
145882
145883  assert( pPhrase->doclist.bFreeList==0 );
145884
145885  for(iToken=0; iToken<pPhrase->nToken; iToken++){
145886    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
145887    Fts3DeferredToken *pDeferred = pToken->pDeferred;
145888
145889    if( pDeferred ){
145890      char *pList;
145891      int nList;
145892      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
145893      if( rc!=SQLITE_OK ) return rc;
145894
145895      if( pList==0 ){
145896        sqlite3_free(aPoslist);
145897        pPhrase->doclist.pList = 0;
145898        pPhrase->doclist.nList = 0;
145899        return SQLITE_OK;
145900
145901      }else if( aPoslist==0 ){
145902        aPoslist = pList;
145903        nPoslist = nList;
145904
145905      }else{
145906        char *aOut = pList;
145907        char *p1 = aPoslist;
145908        char *p2 = aOut;
145909
145910        assert( iPrev>=0 );
145911        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
145912        sqlite3_free(aPoslist);
145913        aPoslist = pList;
145914        nPoslist = (int)(aOut - aPoslist);
145915        if( nPoslist==0 ){
145916          sqlite3_free(aPoslist);
145917          pPhrase->doclist.pList = 0;
145918          pPhrase->doclist.nList = 0;
145919          return SQLITE_OK;
145920        }
145921      }
145922      iPrev = iToken;
145923    }
145924  }
145925
145926  if( iPrev>=0 ){
145927    int nMaxUndeferred = pPhrase->iDoclistToken;
145928    if( nMaxUndeferred<0 ){
145929      pPhrase->doclist.pList = aPoslist;
145930      pPhrase->doclist.nList = nPoslist;
145931      pPhrase->doclist.iDocid = pCsr->iPrevId;
145932      pPhrase->doclist.bFreeList = 1;
145933    }else{
145934      int nDistance;
145935      char *p1;
145936      char *p2;
145937      char *aOut;
145938
145939      if( nMaxUndeferred>iPrev ){
145940        p1 = aPoslist;
145941        p2 = pPhrase->doclist.pList;
145942        nDistance = nMaxUndeferred - iPrev;
145943      }else{
145944        p1 = pPhrase->doclist.pList;
145945        p2 = aPoslist;
145946        nDistance = iPrev - nMaxUndeferred;
145947      }
145948
145949      aOut = (char *)sqlite3_malloc(nPoslist+8);
145950      if( !aOut ){
145951        sqlite3_free(aPoslist);
145952        return SQLITE_NOMEM;
145953      }
145954
145955      pPhrase->doclist.pList = aOut;
145956      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
145957        pPhrase->doclist.bFreeList = 1;
145958        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
145959      }else{
145960        sqlite3_free(aOut);
145961        pPhrase->doclist.pList = 0;
145962        pPhrase->doclist.nList = 0;
145963      }
145964      sqlite3_free(aPoslist);
145965    }
145966  }
145967
145968  return SQLITE_OK;
145969}
145970
145971/*
145972** Maximum number of tokens a phrase may have to be considered for the
145973** incremental doclists strategy.
145974*/
145975#define MAX_INCR_PHRASE_TOKENS 4
145976
145977/*
145978** This function is called for each Fts3Phrase in a full-text query
145979** expression to initialize the mechanism for returning rows. Once this
145980** function has been called successfully on an Fts3Phrase, it may be
145981** used with fts3EvalPhraseNext() to iterate through the matching docids.
145982**
145983** If parameter bOptOk is true, then the phrase may (or may not) use the
145984** incremental loading strategy. Otherwise, the entire doclist is loaded into
145985** memory within this call.
145986**
145987** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145988*/
145989static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
145990  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145991  int rc = SQLITE_OK;             /* Error code */
145992  int i;
145993
145994  /* Determine if doclists may be loaded from disk incrementally. This is
145995  ** possible if the bOptOk argument is true, the FTS doclists will be
145996  ** scanned in forward order, and the phrase consists of
145997  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
145998  ** tokens or prefix tokens that cannot use a prefix-index.  */
145999  int bHaveIncr = 0;
146000  int bIncrOk = (bOptOk
146001   && pCsr->bDesc==pTab->bDescIdx
146002   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
146003#ifdef SQLITE_TEST
146004   && pTab->bNoIncrDoclist==0
146005#endif
146006  );
146007  for(i=0; bIncrOk==1 && i<p->nToken; i++){
146008    Fts3PhraseToken *pToken = &p->aToken[i];
146009    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
146010      bIncrOk = 0;
146011    }
146012    if( pToken->pSegcsr ) bHaveIncr = 1;
146013  }
146014
146015  if( bIncrOk && bHaveIncr ){
146016    /* Use the incremental approach. */
146017    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
146018    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
146019      Fts3PhraseToken *pToken = &p->aToken[i];
146020      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
146021      if( pSegcsr ){
146022        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
146023      }
146024    }
146025    p->bIncr = 1;
146026  }else{
146027    /* Load the full doclist for the phrase into memory. */
146028    rc = fts3EvalPhraseLoad(pCsr, p);
146029    p->bIncr = 0;
146030  }
146031
146032  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
146033  return rc;
146034}
146035
146036/*
146037** This function is used to iterate backwards (from the end to start)
146038** through doclists. It is used by this module to iterate through phrase
146039** doclists in reverse and by the fts3_write.c module to iterate through
146040** pending-terms lists when writing to databases with "order=desc".
146041**
146042** The doclist may be sorted in ascending (parameter bDescIdx==0) or
146043** descending (parameter bDescIdx==1) order of docid. Regardless, this
146044** function iterates from the end of the doclist to the beginning.
146045*/
146046SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
146047  int bDescIdx,                   /* True if the doclist is desc */
146048  char *aDoclist,                 /* Pointer to entire doclist */
146049  int nDoclist,                   /* Length of aDoclist in bytes */
146050  char **ppIter,                  /* IN/OUT: Iterator pointer */
146051  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
146052  int *pnList,                    /* OUT: List length pointer */
146053  u8 *pbEof                       /* OUT: End-of-file flag */
146054){
146055  char *p = *ppIter;
146056
146057  assert( nDoclist>0 );
146058  assert( *pbEof==0 );
146059  assert( p || *piDocid==0 );
146060  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
146061
146062  if( p==0 ){
146063    sqlite3_int64 iDocid = 0;
146064    char *pNext = 0;
146065    char *pDocid = aDoclist;
146066    char *pEnd = &aDoclist[nDoclist];
146067    int iMul = 1;
146068
146069    while( pDocid<pEnd ){
146070      sqlite3_int64 iDelta;
146071      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
146072      iDocid += (iMul * iDelta);
146073      pNext = pDocid;
146074      fts3PoslistCopy(0, &pDocid);
146075      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
146076      iMul = (bDescIdx ? -1 : 1);
146077    }
146078
146079    *pnList = (int)(pEnd - pNext);
146080    *ppIter = pNext;
146081    *piDocid = iDocid;
146082  }else{
146083    int iMul = (bDescIdx ? -1 : 1);
146084    sqlite3_int64 iDelta;
146085    fts3GetReverseVarint(&p, aDoclist, &iDelta);
146086    *piDocid -= (iMul * iDelta);
146087
146088    if( p==aDoclist ){
146089      *pbEof = 1;
146090    }else{
146091      char *pSave = p;
146092      fts3ReversePoslist(aDoclist, &p);
146093      *pnList = (int)(pSave - p);
146094    }
146095    *ppIter = p;
146096  }
146097}
146098
146099/*
146100** Iterate forwards through a doclist.
146101*/
146102SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
146103  int bDescIdx,                   /* True if the doclist is desc */
146104  char *aDoclist,                 /* Pointer to entire doclist */
146105  int nDoclist,                   /* Length of aDoclist in bytes */
146106  char **ppIter,                  /* IN/OUT: Iterator pointer */
146107  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
146108  u8 *pbEof                       /* OUT: End-of-file flag */
146109){
146110  char *p = *ppIter;
146111
146112  assert( nDoclist>0 );
146113  assert( *pbEof==0 );
146114  assert( p || *piDocid==0 );
146115  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
146116
146117  if( p==0 ){
146118    p = aDoclist;
146119    p += sqlite3Fts3GetVarint(p, piDocid);
146120  }else{
146121    fts3PoslistCopy(0, &p);
146122    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
146123    if( p>=&aDoclist[nDoclist] ){
146124      *pbEof = 1;
146125    }else{
146126      sqlite3_int64 iVar;
146127      p += sqlite3Fts3GetVarint(p, &iVar);
146128      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
146129    }
146130  }
146131
146132  *ppIter = p;
146133}
146134
146135/*
146136** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
146137** to true if EOF is reached.
146138*/
146139static void fts3EvalDlPhraseNext(
146140  Fts3Table *pTab,
146141  Fts3Doclist *pDL,
146142  u8 *pbEof
146143){
146144  char *pIter;                            /* Used to iterate through aAll */
146145  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
146146
146147  if( pDL->pNextDocid ){
146148    pIter = pDL->pNextDocid;
146149  }else{
146150    pIter = pDL->aAll;
146151  }
146152
146153  if( pIter>=pEnd ){
146154    /* We have already reached the end of this doclist. EOF. */
146155    *pbEof = 1;
146156  }else{
146157    sqlite3_int64 iDelta;
146158    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
146159    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
146160      pDL->iDocid += iDelta;
146161    }else{
146162      pDL->iDocid -= iDelta;
146163    }
146164    pDL->pList = pIter;
146165    fts3PoslistCopy(0, &pIter);
146166    pDL->nList = (int)(pIter - pDL->pList);
146167
146168    /* pIter now points just past the 0x00 that terminates the position-
146169    ** list for document pDL->iDocid. However, if this position-list was
146170    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
146171    ** point to the start of the next docid value. The following line deals
146172    ** with this case by advancing pIter past the zero-padding added by
146173    ** fts3EvalNearTrim().  */
146174    while( pIter<pEnd && *pIter==0 ) pIter++;
146175
146176    pDL->pNextDocid = pIter;
146177    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
146178    *pbEof = 0;
146179  }
146180}
146181
146182/*
146183** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
146184*/
146185typedef struct TokenDoclist TokenDoclist;
146186struct TokenDoclist {
146187  int bIgnore;
146188  sqlite3_int64 iDocid;
146189  char *pList;
146190  int nList;
146191};
146192
146193/*
146194** Token pToken is an incrementally loaded token that is part of a
146195** multi-token phrase. Advance it to the next matching document in the
146196** database and populate output variable *p with the details of the new
146197** entry. Or, if the iterator has reached EOF, set *pbEof to true.
146198**
146199** If an error occurs, return an SQLite error code. Otherwise, return
146200** SQLITE_OK.
146201*/
146202static int incrPhraseTokenNext(
146203  Fts3Table *pTab,                /* Virtual table handle */
146204  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
146205  int iToken,                     /* Specific token to advance */
146206  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
146207  u8 *pbEof                       /* OUT: True if iterator is at EOF */
146208){
146209  int rc = SQLITE_OK;
146210
146211  if( pPhrase->iDoclistToken==iToken ){
146212    assert( p->bIgnore==0 );
146213    assert( pPhrase->aToken[iToken].pSegcsr==0 );
146214    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
146215    p->pList = pPhrase->doclist.pList;
146216    p->nList = pPhrase->doclist.nList;
146217    p->iDocid = pPhrase->doclist.iDocid;
146218  }else{
146219    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
146220    assert( pToken->pDeferred==0 );
146221    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
146222    if( pToken->pSegcsr ){
146223      assert( p->bIgnore==0 );
146224      rc = sqlite3Fts3MsrIncrNext(
146225          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
146226      );
146227      if( p->pList==0 ) *pbEof = 1;
146228    }else{
146229      p->bIgnore = 1;
146230    }
146231  }
146232
146233  return rc;
146234}
146235
146236
146237/*
146238** The phrase iterator passed as the second argument:
146239**
146240**   * features at least one token that uses an incremental doclist, and
146241**
146242**   * does not contain any deferred tokens.
146243**
146244** Advance it to the next matching documnent in the database and populate
146245** the Fts3Doclist.pList and nList fields.
146246**
146247** If there is no "next" entry and no error occurs, then *pbEof is set to
146248** 1 before returning. Otherwise, if no error occurs and the iterator is
146249** successfully advanced, *pbEof is set to 0.
146250**
146251** If an error occurs, return an SQLite error code. Otherwise, return
146252** SQLITE_OK.
146253*/
146254static int fts3EvalIncrPhraseNext(
146255  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146256  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
146257  u8 *pbEof                       /* OUT: Set to 1 if EOF */
146258){
146259  int rc = SQLITE_OK;
146260  Fts3Doclist *pDL = &p->doclist;
146261  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146262  u8 bEof = 0;
146263
146264  /* This is only called if it is guaranteed that the phrase has at least
146265  ** one incremental token. In which case the bIncr flag is set. */
146266  assert( p->bIncr==1 );
146267
146268  if( p->nToken==1 && p->bIncr ){
146269    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
146270        &pDL->iDocid, &pDL->pList, &pDL->nList
146271    );
146272    if( pDL->pList==0 ) bEof = 1;
146273  }else{
146274    int bDescDoclist = pCsr->bDesc;
146275    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
146276
146277    memset(a, 0, sizeof(a));
146278    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
146279    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
146280
146281    while( bEof==0 ){
146282      int bMaxSet = 0;
146283      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
146284      int i;                      /* Used to iterate through tokens */
146285
146286      /* Advance the iterator for each token in the phrase once. */
146287      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
146288        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
146289        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
146290          iMax = a[i].iDocid;
146291          bMaxSet = 1;
146292        }
146293      }
146294      assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
146295      assert( rc!=SQLITE_OK || bMaxSet );
146296
146297      /* Keep advancing iterators until they all point to the same document */
146298      for(i=0; i<p->nToken; i++){
146299        while( rc==SQLITE_OK && bEof==0
146300            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
146301        ){
146302          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
146303          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
146304            iMax = a[i].iDocid;
146305            i = 0;
146306          }
146307        }
146308      }
146309
146310      /* Check if the current entries really are a phrase match */
146311      if( bEof==0 ){
146312        int nList = 0;
146313        int nByte = a[p->nToken-1].nList;
146314        char *aDoclist = sqlite3_malloc(nByte+1);
146315        if( !aDoclist ) return SQLITE_NOMEM;
146316        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
146317
146318        for(i=0; i<(p->nToken-1); i++){
146319          if( a[i].bIgnore==0 ){
146320            char *pL = a[i].pList;
146321            char *pR = aDoclist;
146322            char *pOut = aDoclist;
146323            int nDist = p->nToken-1-i;
146324            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
146325            if( res==0 ) break;
146326            nList = (int)(pOut - aDoclist);
146327          }
146328        }
146329        if( i==(p->nToken-1) ){
146330          pDL->iDocid = iMax;
146331          pDL->pList = aDoclist;
146332          pDL->nList = nList;
146333          pDL->bFreeList = 1;
146334          break;
146335        }
146336        sqlite3_free(aDoclist);
146337      }
146338    }
146339  }
146340
146341  *pbEof = bEof;
146342  return rc;
146343}
146344
146345/*
146346** Attempt to move the phrase iterator to point to the next matching docid.
146347** If an error occurs, return an SQLite error code. Otherwise, return
146348** SQLITE_OK.
146349**
146350** If there is no "next" entry and no error occurs, then *pbEof is set to
146351** 1 before returning. Otherwise, if no error occurs and the iterator is
146352** successfully advanced, *pbEof is set to 0.
146353*/
146354static int fts3EvalPhraseNext(
146355  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146356  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
146357  u8 *pbEof                       /* OUT: Set to 1 if EOF */
146358){
146359  int rc = SQLITE_OK;
146360  Fts3Doclist *pDL = &p->doclist;
146361  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146362
146363  if( p->bIncr ){
146364    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
146365  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
146366    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
146367        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
146368    );
146369    pDL->pList = pDL->pNextDocid;
146370  }else{
146371    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
146372  }
146373
146374  return rc;
146375}
146376
146377/*
146378**
146379** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146380** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
146381** expression. Also the Fts3Expr.bDeferred variable is set to true for any
146382** expressions for which all descendent tokens are deferred.
146383**
146384** If parameter bOptOk is zero, then it is guaranteed that the
146385** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
146386** each phrase in the expression (subject to deferred token processing).
146387** Or, if bOptOk is non-zero, then one or more tokens within the expression
146388** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
146389**
146390** If an error occurs within this function, *pRc is set to an SQLite error
146391** code before returning.
146392*/
146393static void fts3EvalStartReaders(
146394  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146395  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
146396  int *pRc                        /* IN/OUT: Error code */
146397){
146398  if( pExpr && SQLITE_OK==*pRc ){
146399    if( pExpr->eType==FTSQUERY_PHRASE ){
146400      int nToken = pExpr->pPhrase->nToken;
146401      if( nToken ){
146402        int i;
146403        for(i=0; i<nToken; i++){
146404          if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
146405        }
146406        pExpr->bDeferred = (i==nToken);
146407      }
146408      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
146409    }else{
146410      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
146411      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
146412      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
146413    }
146414  }
146415}
146416
146417/*
146418** An array of the following structures is assembled as part of the process
146419** of selecting tokens to defer before the query starts executing (as part
146420** of the xFilter() method). There is one element in the array for each
146421** token in the FTS expression.
146422**
146423** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
146424** to phrases that are connected only by AND and NEAR operators (not OR or
146425** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
146426** separately. The root of a tokens AND/NEAR cluster is stored in
146427** Fts3TokenAndCost.pRoot.
146428*/
146429typedef struct Fts3TokenAndCost Fts3TokenAndCost;
146430struct Fts3TokenAndCost {
146431  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
146432  int iToken;                     /* Position of token in phrase */
146433  Fts3PhraseToken *pToken;        /* The token itself */
146434  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
146435  int nOvfl;                      /* Number of overflow pages to load doclist */
146436  int iCol;                       /* The column the token must match */
146437};
146438
146439/*
146440** This function is used to populate an allocated Fts3TokenAndCost array.
146441**
146442** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146443** Otherwise, if an error occurs during execution, *pRc is set to an
146444** SQLite error code.
146445*/
146446static void fts3EvalTokenCosts(
146447  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146448  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
146449  Fts3Expr *pExpr,                /* Expression to consider */
146450  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
146451  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
146452  int *pRc                        /* IN/OUT: Error code */
146453){
146454  if( *pRc==SQLITE_OK ){
146455    if( pExpr->eType==FTSQUERY_PHRASE ){
146456      Fts3Phrase *pPhrase = pExpr->pPhrase;
146457      int i;
146458      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
146459        Fts3TokenAndCost *pTC = (*ppTC)++;
146460        pTC->pPhrase = pPhrase;
146461        pTC->iToken = i;
146462        pTC->pRoot = pRoot;
146463        pTC->pToken = &pPhrase->aToken[i];
146464        pTC->iCol = pPhrase->iColumn;
146465        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
146466      }
146467    }else if( pExpr->eType!=FTSQUERY_NOT ){
146468      assert( pExpr->eType==FTSQUERY_OR
146469           || pExpr->eType==FTSQUERY_AND
146470           || pExpr->eType==FTSQUERY_NEAR
146471      );
146472      assert( pExpr->pLeft && pExpr->pRight );
146473      if( pExpr->eType==FTSQUERY_OR ){
146474        pRoot = pExpr->pLeft;
146475        **ppOr = pRoot;
146476        (*ppOr)++;
146477      }
146478      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
146479      if( pExpr->eType==FTSQUERY_OR ){
146480        pRoot = pExpr->pRight;
146481        **ppOr = pRoot;
146482        (*ppOr)++;
146483      }
146484      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
146485    }
146486  }
146487}
146488
146489/*
146490** Determine the average document (row) size in pages. If successful,
146491** write this value to *pnPage and return SQLITE_OK. Otherwise, return
146492** an SQLite error code.
146493**
146494** The average document size in pages is calculated by first calculating
146495** determining the average size in bytes, B. If B is less than the amount
146496** of data that will fit on a single leaf page of an intkey table in
146497** this database, then the average docsize is 1. Otherwise, it is 1 plus
146498** the number of overflow pages consumed by a record B bytes in size.
146499*/
146500static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
146501  if( pCsr->nRowAvg==0 ){
146502    /* The average document size, which is required to calculate the cost
146503    ** of each doclist, has not yet been determined. Read the required
146504    ** data from the %_stat table to calculate it.
146505    **
146506    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
146507    ** varints, where nCol is the number of columns in the FTS3 table.
146508    ** The first varint is the number of documents currently stored in
146509    ** the table. The following nCol varints contain the total amount of
146510    ** data stored in all rows of each column of the table, from left
146511    ** to right.
146512    */
146513    int rc;
146514    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
146515    sqlite3_stmt *pStmt;
146516    sqlite3_int64 nDoc = 0;
146517    sqlite3_int64 nByte = 0;
146518    const char *pEnd;
146519    const char *a;
146520
146521    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
146522    if( rc!=SQLITE_OK ) return rc;
146523    a = sqlite3_column_blob(pStmt, 0);
146524    assert( a );
146525
146526    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
146527    a += sqlite3Fts3GetVarint(a, &nDoc);
146528    while( a<pEnd ){
146529      a += sqlite3Fts3GetVarint(a, &nByte);
146530    }
146531    if( nDoc==0 || nByte==0 ){
146532      sqlite3_reset(pStmt);
146533      return FTS_CORRUPT_VTAB;
146534    }
146535
146536    pCsr->nDoc = nDoc;
146537    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
146538    assert( pCsr->nRowAvg>0 );
146539    rc = sqlite3_reset(pStmt);
146540    if( rc!=SQLITE_OK ) return rc;
146541  }
146542
146543  *pnPage = pCsr->nRowAvg;
146544  return SQLITE_OK;
146545}
146546
146547/*
146548** This function is called to select the tokens (if any) that will be
146549** deferred. The array aTC[] has already been populated when this is
146550** called.
146551**
146552** This function is called once for each AND/NEAR cluster in the
146553** expression. Each invocation determines which tokens to defer within
146554** the cluster with root node pRoot. See comments above the definition
146555** of struct Fts3TokenAndCost for more details.
146556**
146557** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
146558** called on each token to defer. Otherwise, an SQLite error code is
146559** returned.
146560*/
146561static int fts3EvalSelectDeferred(
146562  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146563  Fts3Expr *pRoot,                /* Consider tokens with this root node */
146564  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
146565  int nTC                         /* Number of entries in aTC[] */
146566){
146567  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146568  int nDocSize = 0;               /* Number of pages per doc loaded */
146569  int rc = SQLITE_OK;             /* Return code */
146570  int ii;                         /* Iterator variable for various purposes */
146571  int nOvfl = 0;                  /* Total overflow pages used by doclists */
146572  int nToken = 0;                 /* Total number of tokens in cluster */
146573
146574  int nMinEst = 0;                /* The minimum count for any phrase so far. */
146575  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
146576
146577  /* Tokens are never deferred for FTS tables created using the content=xxx
146578  ** option. The reason being that it is not guaranteed that the content
146579  ** table actually contains the same data as the index. To prevent this from
146580  ** causing any problems, the deferred token optimization is completely
146581  ** disabled for content=xxx tables. */
146582  if( pTab->zContentTbl ){
146583    return SQLITE_OK;
146584  }
146585
146586  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
146587  ** associated with the tokens spill onto overflow pages, or if there is
146588  ** only 1 token, exit early. No tokens to defer in this case. */
146589  for(ii=0; ii<nTC; ii++){
146590    if( aTC[ii].pRoot==pRoot ){
146591      nOvfl += aTC[ii].nOvfl;
146592      nToken++;
146593    }
146594  }
146595  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
146596
146597  /* Obtain the average docsize (in pages). */
146598  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
146599  assert( rc!=SQLITE_OK || nDocSize>0 );
146600
146601
146602  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
146603  ** of the number of overflow pages that will be loaded by the pager layer
146604  ** to retrieve the entire doclist for the token from the full-text index.
146605  ** Load the doclists for tokens that are either:
146606  **
146607  **   a. The cheapest token in the entire query (i.e. the one visited by the
146608  **      first iteration of this loop), or
146609  **
146610  **   b. Part of a multi-token phrase.
146611  **
146612  ** After each token doclist is loaded, merge it with the others from the
146613  ** same phrase and count the number of documents that the merged doclist
146614  ** contains. Set variable "nMinEst" to the smallest number of documents in
146615  ** any phrase doclist for which 1 or more token doclists have been loaded.
146616  ** Let nOther be the number of other phrases for which it is certain that
146617  ** one or more tokens will not be deferred.
146618  **
146619  ** Then, for each token, defer it if loading the doclist would result in
146620  ** loading N or more overflow pages into memory, where N is computed as:
146621  **
146622  **    (nMinEst + 4^nOther - 1) / (4^nOther)
146623  */
146624  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
146625    int iTC;                      /* Used to iterate through aTC[] array. */
146626    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
146627
146628    /* Set pTC to point to the cheapest remaining token. */
146629    for(iTC=0; iTC<nTC; iTC++){
146630      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
146631       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
146632      ){
146633        pTC = &aTC[iTC];
146634      }
146635    }
146636    assert( pTC );
146637
146638    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
146639      /* The number of overflow pages to load for this (and therefore all
146640      ** subsequent) tokens is greater than the estimated number of pages
146641      ** that will be loaded if all subsequent tokens are deferred.
146642      */
146643      Fts3PhraseToken *pToken = pTC->pToken;
146644      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
146645      fts3SegReaderCursorFree(pToken->pSegcsr);
146646      pToken->pSegcsr = 0;
146647    }else{
146648      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
146649      ** for-loop. Except, limit the value to 2^24 to prevent it from
146650      ** overflowing the 32-bit integer it is stored in. */
146651      if( ii<12 ) nLoad4 = nLoad4*4;
146652
146653      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
146654        /* Either this is the cheapest token in the entire query, or it is
146655        ** part of a multi-token phrase. Either way, the entire doclist will
146656        ** (eventually) be loaded into memory. It may as well be now. */
146657        Fts3PhraseToken *pToken = pTC->pToken;
146658        int nList = 0;
146659        char *pList = 0;
146660        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
146661        assert( rc==SQLITE_OK || pList==0 );
146662        if( rc==SQLITE_OK ){
146663          rc = fts3EvalPhraseMergeToken(
146664              pTab, pTC->pPhrase, pTC->iToken,pList,nList
146665          );
146666        }
146667        if( rc==SQLITE_OK ){
146668          int nCount;
146669          nCount = fts3DoclistCountDocids(
146670              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
146671          );
146672          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
146673        }
146674      }
146675    }
146676    pTC->pToken = 0;
146677  }
146678
146679  return rc;
146680}
146681
146682/*
146683** This function is called from within the xFilter method. It initializes
146684** the full-text query currently stored in pCsr->pExpr. To iterate through
146685** the results of a query, the caller does:
146686**
146687**    fts3EvalStart(pCsr);
146688**    while( 1 ){
146689**      fts3EvalNext(pCsr);
146690**      if( pCsr->bEof ) break;
146691**      ... return row pCsr->iPrevId to the caller ...
146692**    }
146693*/
146694static int fts3EvalStart(Fts3Cursor *pCsr){
146695  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146696  int rc = SQLITE_OK;
146697  int nToken = 0;
146698  int nOr = 0;
146699
146700  /* Allocate a MultiSegReader for each token in the expression. */
146701  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
146702
146703  /* Determine which, if any, tokens in the expression should be deferred. */
146704#ifndef SQLITE_DISABLE_FTS4_DEFERRED
146705  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
146706    Fts3TokenAndCost *aTC;
146707    Fts3Expr **apOr;
146708    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
146709        sizeof(Fts3TokenAndCost) * nToken
146710      + sizeof(Fts3Expr *) * nOr * 2
146711    );
146712    apOr = (Fts3Expr **)&aTC[nToken];
146713
146714    if( !aTC ){
146715      rc = SQLITE_NOMEM;
146716    }else{
146717      int ii;
146718      Fts3TokenAndCost *pTC = aTC;
146719      Fts3Expr **ppOr = apOr;
146720
146721      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
146722      nToken = (int)(pTC-aTC);
146723      nOr = (int)(ppOr-apOr);
146724
146725      if( rc==SQLITE_OK ){
146726        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
146727        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
146728          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
146729        }
146730      }
146731
146732      sqlite3_free(aTC);
146733    }
146734  }
146735#endif
146736
146737  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
146738  return rc;
146739}
146740
146741/*
146742** Invalidate the current position list for phrase pPhrase.
146743*/
146744static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
146745  if( pPhrase->doclist.bFreeList ){
146746    sqlite3_free(pPhrase->doclist.pList);
146747  }
146748  pPhrase->doclist.pList = 0;
146749  pPhrase->doclist.nList = 0;
146750  pPhrase->doclist.bFreeList = 0;
146751}
146752
146753/*
146754** This function is called to edit the position list associated with
146755** the phrase object passed as the fifth argument according to a NEAR
146756** condition. For example:
146757**
146758**     abc NEAR/5 "def ghi"
146759**
146760** Parameter nNear is passed the NEAR distance of the expression (5 in
146761** the example above). When this function is called, *paPoslist points to
146762** the position list, and *pnToken is the number of phrase tokens in, the
146763** phrase on the other side of the NEAR operator to pPhrase. For example,
146764** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
146765** the position list associated with phrase "abc".
146766**
146767** All positions in the pPhrase position list that are not sufficiently
146768** close to a position in the *paPoslist position list are removed. If this
146769** leaves 0 positions, zero is returned. Otherwise, non-zero.
146770**
146771** Before returning, *paPoslist is set to point to the position lsit
146772** associated with pPhrase. And *pnToken is set to the number of tokens in
146773** pPhrase.
146774*/
146775static int fts3EvalNearTrim(
146776  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
146777  char *aTmp,                     /* Temporary space to use */
146778  char **paPoslist,               /* IN/OUT: Position list */
146779  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
146780  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
146781){
146782  int nParam1 = nNear + pPhrase->nToken;
146783  int nParam2 = nNear + *pnToken;
146784  int nNew;
146785  char *p2;
146786  char *pOut;
146787  int res;
146788
146789  assert( pPhrase->doclist.pList );
146790
146791  p2 = pOut = pPhrase->doclist.pList;
146792  res = fts3PoslistNearMerge(
146793    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
146794  );
146795  if( res ){
146796    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
146797    assert( pPhrase->doclist.pList[nNew]=='\0' );
146798    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
146799    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
146800    pPhrase->doclist.nList = nNew;
146801    *paPoslist = pPhrase->doclist.pList;
146802    *pnToken = pPhrase->nToken;
146803  }
146804
146805  return res;
146806}
146807
146808/*
146809** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
146810** Otherwise, it advances the expression passed as the second argument to
146811** point to the next matching row in the database. Expressions iterate through
146812** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
146813** or descending if it is non-zero.
146814**
146815** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
146816** successful, the following variables in pExpr are set:
146817**
146818**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
146819**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
146820**
146821** If the expression is of type FTSQUERY_PHRASE, and the expression is not
146822** at EOF, then the following variables are populated with the position list
146823** for the phrase for the visited row:
146824**
146825**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
146826**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
146827**
146828** It says above that this function advances the expression to the next
146829** matching row. This is usually true, but there are the following exceptions:
146830**
146831**   1. Deferred tokens are not taken into account. If a phrase consists
146832**      entirely of deferred tokens, it is assumed to match every row in
146833**      the db. In this case the position-list is not populated at all.
146834**
146835**      Or, if a phrase contains one or more deferred tokens and one or
146836**      more non-deferred tokens, then the expression is advanced to the
146837**      next possible match, considering only non-deferred tokens. In other
146838**      words, if the phrase is "A B C", and "B" is deferred, the expression
146839**      is advanced to the next row that contains an instance of "A * C",
146840**      where "*" may match any single token. The position list in this case
146841**      is populated as for "A * C" before returning.
146842**
146843**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
146844**      advanced to point to the next row that matches "x AND y".
146845**
146846** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
146847** really a match, taking into account deferred tokens and NEAR operators.
146848*/
146849static void fts3EvalNextRow(
146850  Fts3Cursor *pCsr,               /* FTS Cursor handle */
146851  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
146852  int *pRc                        /* IN/OUT: Error code */
146853){
146854  if( *pRc==SQLITE_OK ){
146855    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
146856    assert( pExpr->bEof==0 );
146857    pExpr->bStart = 1;
146858
146859    switch( pExpr->eType ){
146860      case FTSQUERY_NEAR:
146861      case FTSQUERY_AND: {
146862        Fts3Expr *pLeft = pExpr->pLeft;
146863        Fts3Expr *pRight = pExpr->pRight;
146864        assert( !pLeft->bDeferred || !pRight->bDeferred );
146865
146866        if( pLeft->bDeferred ){
146867          /* LHS is entirely deferred. So we assume it matches every row.
146868          ** Advance the RHS iterator to find the next row visited. */
146869          fts3EvalNextRow(pCsr, pRight, pRc);
146870          pExpr->iDocid = pRight->iDocid;
146871          pExpr->bEof = pRight->bEof;
146872        }else if( pRight->bDeferred ){
146873          /* RHS is entirely deferred. So we assume it matches every row.
146874          ** Advance the LHS iterator to find the next row visited. */
146875          fts3EvalNextRow(pCsr, pLeft, pRc);
146876          pExpr->iDocid = pLeft->iDocid;
146877          pExpr->bEof = pLeft->bEof;
146878        }else{
146879          /* Neither the RHS or LHS are deferred. */
146880          fts3EvalNextRow(pCsr, pLeft, pRc);
146881          fts3EvalNextRow(pCsr, pRight, pRc);
146882          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
146883            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146884            if( iDiff==0 ) break;
146885            if( iDiff<0 ){
146886              fts3EvalNextRow(pCsr, pLeft, pRc);
146887            }else{
146888              fts3EvalNextRow(pCsr, pRight, pRc);
146889            }
146890          }
146891          pExpr->iDocid = pLeft->iDocid;
146892          pExpr->bEof = (pLeft->bEof || pRight->bEof);
146893          if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
146894            if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
146895              Fts3Doclist *pDl = &pRight->pPhrase->doclist;
146896              while( *pRc==SQLITE_OK && pRight->bEof==0 ){
146897                memset(pDl->pList, 0, pDl->nList);
146898                fts3EvalNextRow(pCsr, pRight, pRc);
146899              }
146900            }
146901            if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
146902              Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
146903              while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
146904                memset(pDl->pList, 0, pDl->nList);
146905                fts3EvalNextRow(pCsr, pLeft, pRc);
146906              }
146907            }
146908          }
146909        }
146910        break;
146911      }
146912
146913      case FTSQUERY_OR: {
146914        Fts3Expr *pLeft = pExpr->pLeft;
146915        Fts3Expr *pRight = pExpr->pRight;
146916        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146917
146918        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
146919        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
146920
146921        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
146922          fts3EvalNextRow(pCsr, pLeft, pRc);
146923        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
146924          fts3EvalNextRow(pCsr, pRight, pRc);
146925        }else{
146926          fts3EvalNextRow(pCsr, pLeft, pRc);
146927          fts3EvalNextRow(pCsr, pRight, pRc);
146928        }
146929
146930        pExpr->bEof = (pLeft->bEof && pRight->bEof);
146931        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146932        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
146933          pExpr->iDocid = pLeft->iDocid;
146934        }else{
146935          pExpr->iDocid = pRight->iDocid;
146936        }
146937
146938        break;
146939      }
146940
146941      case FTSQUERY_NOT: {
146942        Fts3Expr *pLeft = pExpr->pLeft;
146943        Fts3Expr *pRight = pExpr->pRight;
146944
146945        if( pRight->bStart==0 ){
146946          fts3EvalNextRow(pCsr, pRight, pRc);
146947          assert( *pRc!=SQLITE_OK || pRight->bStart );
146948        }
146949
146950        fts3EvalNextRow(pCsr, pLeft, pRc);
146951        if( pLeft->bEof==0 ){
146952          while( !*pRc
146953              && !pRight->bEof
146954              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
146955          ){
146956            fts3EvalNextRow(pCsr, pRight, pRc);
146957          }
146958        }
146959        pExpr->iDocid = pLeft->iDocid;
146960        pExpr->bEof = pLeft->bEof;
146961        break;
146962      }
146963
146964      default: {
146965        Fts3Phrase *pPhrase = pExpr->pPhrase;
146966        fts3EvalInvalidatePoslist(pPhrase);
146967        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
146968        pExpr->iDocid = pPhrase->doclist.iDocid;
146969        break;
146970      }
146971    }
146972  }
146973}
146974
146975/*
146976** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
146977** cluster, then this function returns 1 immediately.
146978**
146979** Otherwise, it checks if the current row really does match the NEAR
146980** expression, using the data currently stored in the position lists
146981** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
146982**
146983** If the current row is a match, the position list associated with each
146984** phrase in the NEAR expression is edited in place to contain only those
146985** phrase instances sufficiently close to their peers to satisfy all NEAR
146986** constraints. In this case it returns 1. If the NEAR expression does not
146987** match the current row, 0 is returned. The position lists may or may not
146988** be edited if 0 is returned.
146989*/
146990static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
146991  int res = 1;
146992
146993  /* The following block runs if pExpr is the root of a NEAR query.
146994  ** For example, the query:
146995  **
146996  **         "w" NEAR "x" NEAR "y" NEAR "z"
146997  **
146998  ** which is represented in tree form as:
146999  **
147000  **                               |
147001  **                          +--NEAR--+      <-- root of NEAR query
147002  **                          |        |
147003  **                     +--NEAR--+   "z"
147004  **                     |        |
147005  **                +--NEAR--+   "y"
147006  **                |        |
147007  **               "w"      "x"
147008  **
147009  ** The right-hand child of a NEAR node is always a phrase. The
147010  ** left-hand child may be either a phrase or a NEAR node. There are
147011  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
147012  */
147013  if( *pRc==SQLITE_OK
147014   && pExpr->eType==FTSQUERY_NEAR
147015   && pExpr->bEof==0
147016   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
147017  ){
147018    Fts3Expr *p;
147019    int nTmp = 0;                 /* Bytes of temp space */
147020    char *aTmp;                   /* Temp space for PoslistNearMerge() */
147021
147022    /* Allocate temporary working space. */
147023    for(p=pExpr; p->pLeft; p=p->pLeft){
147024      nTmp += p->pRight->pPhrase->doclist.nList;
147025    }
147026    nTmp += p->pPhrase->doclist.nList;
147027    if( nTmp==0 ){
147028      res = 0;
147029    }else{
147030      aTmp = sqlite3_malloc(nTmp*2);
147031      if( !aTmp ){
147032        *pRc = SQLITE_NOMEM;
147033        res = 0;
147034      }else{
147035        char *aPoslist = p->pPhrase->doclist.pList;
147036        int nToken = p->pPhrase->nToken;
147037
147038        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
147039          Fts3Phrase *pPhrase = p->pRight->pPhrase;
147040          int nNear = p->nNear;
147041          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
147042        }
147043
147044        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
147045        nToken = pExpr->pRight->pPhrase->nToken;
147046        for(p=pExpr->pLeft; p && res; p=p->pLeft){
147047          int nNear;
147048          Fts3Phrase *pPhrase;
147049          assert( p->pParent && p->pParent->pLeft==p );
147050          nNear = p->pParent->nNear;
147051          pPhrase = (
147052              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
147053              );
147054          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
147055        }
147056      }
147057
147058      sqlite3_free(aTmp);
147059    }
147060  }
147061
147062  return res;
147063}
147064
147065/*
147066** This function is a helper function for sqlite3Fts3EvalTestDeferred().
147067** Assuming no error occurs or has occurred, It returns non-zero if the
147068** expression passed as the second argument matches the row that pCsr
147069** currently points to, or zero if it does not.
147070**
147071** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147072** If an error occurs during execution of this function, *pRc is set to
147073** the appropriate SQLite error code. In this case the returned value is
147074** undefined.
147075*/
147076static int fts3EvalTestExpr(
147077  Fts3Cursor *pCsr,               /* FTS cursor handle */
147078  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
147079  int *pRc                        /* IN/OUT: Error code */
147080){
147081  int bHit = 1;                   /* Return value */
147082  if( *pRc==SQLITE_OK ){
147083    switch( pExpr->eType ){
147084      case FTSQUERY_NEAR:
147085      case FTSQUERY_AND:
147086        bHit = (
147087            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
147088         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
147089         && fts3EvalNearTest(pExpr, pRc)
147090        );
147091
147092        /* If the NEAR expression does not match any rows, zero the doclist for
147093        ** all phrases involved in the NEAR. This is because the snippet(),
147094        ** offsets() and matchinfo() functions are not supposed to recognize
147095        ** any instances of phrases that are part of unmatched NEAR queries.
147096        ** For example if this expression:
147097        **
147098        **    ... MATCH 'a OR (b NEAR c)'
147099        **
147100        ** is matched against a row containing:
147101        **
147102        **        'a b d e'
147103        **
147104        ** then any snippet() should ony highlight the "a" term, not the "b"
147105        ** (as "b" is part of a non-matching NEAR clause).
147106        */
147107        if( bHit==0
147108         && pExpr->eType==FTSQUERY_NEAR
147109         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
147110        ){
147111          Fts3Expr *p;
147112          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
147113            if( p->pRight->iDocid==pCsr->iPrevId ){
147114              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
147115            }
147116          }
147117          if( p->iDocid==pCsr->iPrevId ){
147118            fts3EvalInvalidatePoslist(p->pPhrase);
147119          }
147120        }
147121
147122        break;
147123
147124      case FTSQUERY_OR: {
147125        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
147126        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
147127        bHit = bHit1 || bHit2;
147128        break;
147129      }
147130
147131      case FTSQUERY_NOT:
147132        bHit = (
147133            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
147134         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
147135        );
147136        break;
147137
147138      default: {
147139#ifndef SQLITE_DISABLE_FTS4_DEFERRED
147140        if( pCsr->pDeferred
147141         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
147142        ){
147143          Fts3Phrase *pPhrase = pExpr->pPhrase;
147144          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
147145          if( pExpr->bDeferred ){
147146            fts3EvalInvalidatePoslist(pPhrase);
147147          }
147148          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
147149          bHit = (pPhrase->doclist.pList!=0);
147150          pExpr->iDocid = pCsr->iPrevId;
147151        }else
147152#endif
147153        {
147154          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
147155        }
147156        break;
147157      }
147158    }
147159  }
147160  return bHit;
147161}
147162
147163/*
147164** This function is called as the second part of each xNext operation when
147165** iterating through the results of a full-text query. At this point the
147166** cursor points to a row that matches the query expression, with the
147167** following caveats:
147168**
147169**   * Up until this point, "NEAR" operators in the expression have been
147170**     treated as "AND".
147171**
147172**   * Deferred tokens have not yet been considered.
147173**
147174** If *pRc is not SQLITE_OK when this function is called, it immediately
147175** returns 0. Otherwise, it tests whether or not after considering NEAR
147176** operators and deferred tokens the current row is still a match for the
147177** expression. It returns 1 if both of the following are true:
147178**
147179**   1. *pRc is SQLITE_OK when this function returns, and
147180**
147181**   2. After scanning the current FTS table row for the deferred tokens,
147182**      it is determined that the row does *not* match the query.
147183**
147184** Or, if no error occurs and it seems the current row does match the FTS
147185** query, return 0.
147186*/
147187SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
147188  int rc = *pRc;
147189  int bMiss = 0;
147190  if( rc==SQLITE_OK ){
147191
147192    /* If there are one or more deferred tokens, load the current row into
147193    ** memory and scan it to determine the position list for each deferred
147194    ** token. Then, see if this row is really a match, considering deferred
147195    ** tokens and NEAR operators (neither of which were taken into account
147196    ** earlier, by fts3EvalNextRow()).
147197    */
147198    if( pCsr->pDeferred ){
147199      rc = fts3CursorSeek(0, pCsr);
147200      if( rc==SQLITE_OK ){
147201        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
147202      }
147203    }
147204    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
147205
147206    /* Free the position-lists accumulated for each deferred token above. */
147207    sqlite3Fts3FreeDeferredDoclists(pCsr);
147208    *pRc = rc;
147209  }
147210  return (rc==SQLITE_OK && bMiss);
147211}
147212
147213/*
147214** Advance to the next document that matches the FTS expression in
147215** Fts3Cursor.pExpr.
147216*/
147217static int fts3EvalNext(Fts3Cursor *pCsr){
147218  int rc = SQLITE_OK;             /* Return Code */
147219  Fts3Expr *pExpr = pCsr->pExpr;
147220  assert( pCsr->isEof==0 );
147221  if( pExpr==0 ){
147222    pCsr->isEof = 1;
147223  }else{
147224    do {
147225      if( pCsr->isRequireSeek==0 ){
147226        sqlite3_reset(pCsr->pStmt);
147227      }
147228      assert( sqlite3_data_count(pCsr->pStmt)==0 );
147229      fts3EvalNextRow(pCsr, pExpr, &rc);
147230      pCsr->isEof = pExpr->bEof;
147231      pCsr->isRequireSeek = 1;
147232      pCsr->isMatchinfoNeeded = 1;
147233      pCsr->iPrevId = pExpr->iDocid;
147234    }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
147235  }
147236
147237  /* Check if the cursor is past the end of the docid range specified
147238  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
147239  if( rc==SQLITE_OK && (
147240        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
147241     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
147242  )){
147243    pCsr->isEof = 1;
147244  }
147245
147246  return rc;
147247}
147248
147249/*
147250** Restart interation for expression pExpr so that the next call to
147251** fts3EvalNext() visits the first row. Do not allow incremental
147252** loading or merging of phrase doclists for this iteration.
147253**
147254** If *pRc is other than SQLITE_OK when this function is called, it is
147255** a no-op. If an error occurs within this function, *pRc is set to an
147256** SQLite error code before returning.
147257*/
147258static void fts3EvalRestart(
147259  Fts3Cursor *pCsr,
147260  Fts3Expr *pExpr,
147261  int *pRc
147262){
147263  if( pExpr && *pRc==SQLITE_OK ){
147264    Fts3Phrase *pPhrase = pExpr->pPhrase;
147265
147266    if( pPhrase ){
147267      fts3EvalInvalidatePoslist(pPhrase);
147268      if( pPhrase->bIncr ){
147269        int i;
147270        for(i=0; i<pPhrase->nToken; i++){
147271          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
147272          assert( pToken->pDeferred==0 );
147273          if( pToken->pSegcsr ){
147274            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
147275          }
147276        }
147277        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
147278      }
147279      pPhrase->doclist.pNextDocid = 0;
147280      pPhrase->doclist.iDocid = 0;
147281      pPhrase->pOrPoslist = 0;
147282    }
147283
147284    pExpr->iDocid = 0;
147285    pExpr->bEof = 0;
147286    pExpr->bStart = 0;
147287
147288    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
147289    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
147290  }
147291}
147292
147293/*
147294** After allocating the Fts3Expr.aMI[] array for each phrase in the
147295** expression rooted at pExpr, the cursor iterates through all rows matched
147296** by pExpr, calling this function for each row. This function increments
147297** the values in Fts3Expr.aMI[] according to the position-list currently
147298** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
147299** expression nodes.
147300*/
147301static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
147302  if( pExpr ){
147303    Fts3Phrase *pPhrase = pExpr->pPhrase;
147304    if( pPhrase && pPhrase->doclist.pList ){
147305      int iCol = 0;
147306      char *p = pPhrase->doclist.pList;
147307
147308      assert( *p );
147309      while( 1 ){
147310        u8 c = 0;
147311        int iCnt = 0;
147312        while( 0xFE & (*p | c) ){
147313          if( (c&0x80)==0 ) iCnt++;
147314          c = *p++ & 0x80;
147315        }
147316
147317        /* aMI[iCol*3 + 1] = Number of occurrences
147318        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
147319        */
147320        pExpr->aMI[iCol*3 + 1] += iCnt;
147321        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
147322        if( *p==0x00 ) break;
147323        p++;
147324        p += fts3GetVarint32(p, &iCol);
147325      }
147326    }
147327
147328    fts3EvalUpdateCounts(pExpr->pLeft);
147329    fts3EvalUpdateCounts(pExpr->pRight);
147330  }
147331}
147332
147333/*
147334** Expression pExpr must be of type FTSQUERY_PHRASE.
147335**
147336** If it is not already allocated and populated, this function allocates and
147337** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
147338** of a NEAR expression, then it also allocates and populates the same array
147339** for all other phrases that are part of the NEAR expression.
147340**
147341** SQLITE_OK is returned if the aMI[] array is successfully allocated and
147342** populated. Otherwise, if an error occurs, an SQLite error code is returned.
147343*/
147344static int fts3EvalGatherStats(
147345  Fts3Cursor *pCsr,               /* Cursor object */
147346  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
147347){
147348  int rc = SQLITE_OK;             /* Return code */
147349
147350  assert( pExpr->eType==FTSQUERY_PHRASE );
147351  if( pExpr->aMI==0 ){
147352    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147353    Fts3Expr *pRoot;                /* Root of NEAR expression */
147354    Fts3Expr *p;                    /* Iterator used for several purposes */
147355
147356    sqlite3_int64 iPrevId = pCsr->iPrevId;
147357    sqlite3_int64 iDocid;
147358    u8 bEof;
147359
147360    /* Find the root of the NEAR expression */
147361    pRoot = pExpr;
147362    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
147363      pRoot = pRoot->pParent;
147364    }
147365    iDocid = pRoot->iDocid;
147366    bEof = pRoot->bEof;
147367    assert( pRoot->bStart );
147368
147369    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
147370    for(p=pRoot; p; p=p->pLeft){
147371      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
147372      assert( pE->aMI==0 );
147373      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
147374      if( !pE->aMI ) return SQLITE_NOMEM;
147375      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
147376    }
147377
147378    fts3EvalRestart(pCsr, pRoot, &rc);
147379
147380    while( pCsr->isEof==0 && rc==SQLITE_OK ){
147381
147382      do {
147383        /* Ensure the %_content statement is reset. */
147384        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
147385        assert( sqlite3_data_count(pCsr->pStmt)==0 );
147386
147387        /* Advance to the next document */
147388        fts3EvalNextRow(pCsr, pRoot, &rc);
147389        pCsr->isEof = pRoot->bEof;
147390        pCsr->isRequireSeek = 1;
147391        pCsr->isMatchinfoNeeded = 1;
147392        pCsr->iPrevId = pRoot->iDocid;
147393      }while( pCsr->isEof==0
147394           && pRoot->eType==FTSQUERY_NEAR
147395           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
147396      );
147397
147398      if( rc==SQLITE_OK && pCsr->isEof==0 ){
147399        fts3EvalUpdateCounts(pRoot);
147400      }
147401    }
147402
147403    pCsr->isEof = 0;
147404    pCsr->iPrevId = iPrevId;
147405
147406    if( bEof ){
147407      pRoot->bEof = bEof;
147408    }else{
147409      /* Caution: pRoot may iterate through docids in ascending or descending
147410      ** order. For this reason, even though it seems more defensive, the
147411      ** do loop can not be written:
147412      **
147413      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
147414      */
147415      fts3EvalRestart(pCsr, pRoot, &rc);
147416      do {
147417        fts3EvalNextRow(pCsr, pRoot, &rc);
147418        assert( pRoot->bEof==0 );
147419      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
147420    }
147421  }
147422  return rc;
147423}
147424
147425/*
147426** This function is used by the matchinfo() module to query a phrase
147427** expression node for the following information:
147428**
147429**   1. The total number of occurrences of the phrase in each column of
147430**      the FTS table (considering all rows), and
147431**
147432**   2. For each column, the number of rows in the table for which the
147433**      column contains at least one instance of the phrase.
147434**
147435** If no error occurs, SQLITE_OK is returned and the values for each column
147436** written into the array aiOut as follows:
147437**
147438**   aiOut[iCol*3 + 1] = Number of occurrences
147439**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
147440**
147441** Caveats:
147442**
147443**   * If a phrase consists entirely of deferred tokens, then all output
147444**     values are set to the number of documents in the table. In other
147445**     words we assume that very common tokens occur exactly once in each
147446**     column of each row of the table.
147447**
147448**   * If a phrase contains some deferred tokens (and some non-deferred
147449**     tokens), count the potential occurrence identified by considering
147450**     the non-deferred tokens instead of actual phrase occurrences.
147451**
147452**   * If the phrase is part of a NEAR expression, then only phrase instances
147453**     that meet the NEAR constraint are included in the counts.
147454*/
147455SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
147456  Fts3Cursor *pCsr,               /* FTS cursor handle */
147457  Fts3Expr *pExpr,                /* Phrase expression */
147458  u32 *aiOut                      /* Array to write results into (see above) */
147459){
147460  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147461  int rc = SQLITE_OK;
147462  int iCol;
147463
147464  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
147465    assert( pCsr->nDoc>0 );
147466    for(iCol=0; iCol<pTab->nColumn; iCol++){
147467      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
147468      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
147469    }
147470  }else{
147471    rc = fts3EvalGatherStats(pCsr, pExpr);
147472    if( rc==SQLITE_OK ){
147473      assert( pExpr->aMI );
147474      for(iCol=0; iCol<pTab->nColumn; iCol++){
147475        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
147476        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
147477      }
147478    }
147479  }
147480
147481  return rc;
147482}
147483
147484/*
147485** The expression pExpr passed as the second argument to this function
147486** must be of type FTSQUERY_PHRASE.
147487**
147488** The returned value is either NULL or a pointer to a buffer containing
147489** a position-list indicating the occurrences of the phrase in column iCol
147490** of the current row.
147491**
147492** More specifically, the returned buffer contains 1 varint for each
147493** occurrence of the phrase in the column, stored using the normal (delta+2)
147494** compression and is terminated by either an 0x01 or 0x00 byte. For example,
147495** if the requested column contains "a b X c d X X" and the position-list
147496** for 'X' is requested, the buffer returned may contain:
147497**
147498**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
147499**
147500** This function works regardless of whether or not the phrase is deferred,
147501** incremental, or neither.
147502*/
147503SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
147504  Fts3Cursor *pCsr,               /* FTS3 cursor object */
147505  Fts3Expr *pExpr,                /* Phrase to return doclist for */
147506  int iCol,                       /* Column to return position list for */
147507  char **ppOut                    /* OUT: Pointer to position list */
147508){
147509  Fts3Phrase *pPhrase = pExpr->pPhrase;
147510  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147511  char *pIter;
147512  int iThis;
147513  sqlite3_int64 iDocid;
147514
147515  /* If this phrase is applies specifically to some column other than
147516  ** column iCol, return a NULL pointer.  */
147517  *ppOut = 0;
147518  assert( iCol>=0 && iCol<pTab->nColumn );
147519  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
147520    return SQLITE_OK;
147521  }
147522
147523  iDocid = pExpr->iDocid;
147524  pIter = pPhrase->doclist.pList;
147525  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
147526    int rc = SQLITE_OK;
147527    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
147528    int bOr = 0;
147529    u8 bTreeEof = 0;
147530    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
147531    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
147532    int bMatch;
147533
147534    /* Check if this phrase descends from an OR expression node. If not,
147535    ** return NULL. Otherwise, the entry that corresponds to docid
147536    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
147537    ** tree that the node is part of has been marked as EOF, but the node
147538    ** itself is not EOF, then it may point to an earlier entry. */
147539    pNear = pExpr;
147540    for(p=pExpr->pParent; p; p=p->pParent){
147541      if( p->eType==FTSQUERY_OR ) bOr = 1;
147542      if( p->eType==FTSQUERY_NEAR ) pNear = p;
147543      if( p->bEof ) bTreeEof = 1;
147544    }
147545    if( bOr==0 ) return SQLITE_OK;
147546
147547    /* This is the descendent of an OR node. In this case we cannot use
147548    ** an incremental phrase. Load the entire doclist for the phrase
147549    ** into memory in this case.  */
147550    if( pPhrase->bIncr ){
147551      int bEofSave = pNear->bEof;
147552      fts3EvalRestart(pCsr, pNear, &rc);
147553      while( rc==SQLITE_OK && !pNear->bEof ){
147554        fts3EvalNextRow(pCsr, pNear, &rc);
147555        if( bEofSave==0 && pNear->iDocid==iDocid ) break;
147556      }
147557      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
147558    }
147559    if( bTreeEof ){
147560      while( rc==SQLITE_OK && !pNear->bEof ){
147561        fts3EvalNextRow(pCsr, pNear, &rc);
147562      }
147563    }
147564    if( rc!=SQLITE_OK ) return rc;
147565
147566    bMatch = 1;
147567    for(p=pNear; p; p=p->pLeft){
147568      u8 bEof = 0;
147569      Fts3Expr *pTest = p;
147570      Fts3Phrase *pPh;
147571      assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
147572      if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
147573      assert( pTest->eType==FTSQUERY_PHRASE );
147574      pPh = pTest->pPhrase;
147575
147576      pIter = pPh->pOrPoslist;
147577      iDocid = pPh->iOrDocid;
147578      if( pCsr->bDesc==bDescDoclist ){
147579        bEof = !pPh->doclist.nAll ||
147580          (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
147581        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
147582          sqlite3Fts3DoclistNext(
147583              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
147584              &pIter, &iDocid, &bEof
147585          );
147586        }
147587      }else{
147588        bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
147589        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
147590          int dummy;
147591          sqlite3Fts3DoclistPrev(
147592              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
147593              &pIter, &iDocid, &dummy, &bEof
147594              );
147595        }
147596      }
147597      pPh->pOrPoslist = pIter;
147598      pPh->iOrDocid = iDocid;
147599      if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
147600    }
147601
147602    if( bMatch ){
147603      pIter = pPhrase->pOrPoslist;
147604    }else{
147605      pIter = 0;
147606    }
147607  }
147608  if( pIter==0 ) return SQLITE_OK;
147609
147610  if( *pIter==0x01 ){
147611    pIter++;
147612    pIter += fts3GetVarint32(pIter, &iThis);
147613  }else{
147614    iThis = 0;
147615  }
147616  while( iThis<iCol ){
147617    fts3ColumnlistCopy(0, &pIter);
147618    if( *pIter==0x00 ) return SQLITE_OK;
147619    pIter++;
147620    pIter += fts3GetVarint32(pIter, &iThis);
147621  }
147622  if( *pIter==0x00 ){
147623    pIter = 0;
147624  }
147625
147626  *ppOut = ((iCol==iThis)?pIter:0);
147627  return SQLITE_OK;
147628}
147629
147630/*
147631** Free all components of the Fts3Phrase structure that were allocated by
147632** the eval module. Specifically, this means to free:
147633**
147634**   * the contents of pPhrase->doclist, and
147635**   * any Fts3MultiSegReader objects held by phrase tokens.
147636*/
147637SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
147638  if( pPhrase ){
147639    int i;
147640    sqlite3_free(pPhrase->doclist.aAll);
147641    fts3EvalInvalidatePoslist(pPhrase);
147642    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
147643    for(i=0; i<pPhrase->nToken; i++){
147644      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
147645      pPhrase->aToken[i].pSegcsr = 0;
147646    }
147647  }
147648}
147649
147650
147651/*
147652** Return SQLITE_CORRUPT_VTAB.
147653*/
147654#ifdef SQLITE_DEBUG
147655SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
147656  return SQLITE_CORRUPT_VTAB;
147657}
147658#endif
147659
147660#if !SQLITE_CORE
147661/*
147662** Initialize API pointer table, if required.
147663*/
147664#ifdef _WIN32
147665__declspec(dllexport)
147666#endif
147667SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
147668  sqlite3 *db,
147669  char **pzErrMsg,
147670  const sqlite3_api_routines *pApi
147671){
147672  SQLITE_EXTENSION_INIT2(pApi)
147673  return sqlite3Fts3Init(db);
147674}
147675#endif
147676
147677#endif
147678
147679/************** End of fts3.c ************************************************/
147680/************** Begin file fts3_aux.c ****************************************/
147681/*
147682** 2011 Jan 27
147683**
147684** The author disclaims copyright to this source code.  In place of
147685** a legal notice, here is a blessing:
147686**
147687**    May you do good and not evil.
147688**    May you find forgiveness for yourself and forgive others.
147689**    May you share freely, never taking more than you give.
147690**
147691******************************************************************************
147692**
147693*/
147694/* #include "fts3Int.h" */
147695#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147696
147697/* #include <string.h> */
147698/* #include <assert.h> */
147699
147700typedef struct Fts3auxTable Fts3auxTable;
147701typedef struct Fts3auxCursor Fts3auxCursor;
147702
147703struct Fts3auxTable {
147704  sqlite3_vtab base;              /* Base class used by SQLite core */
147705  Fts3Table *pFts3Tab;
147706};
147707
147708struct Fts3auxCursor {
147709  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
147710  Fts3MultiSegReader csr;        /* Must be right after "base" */
147711  Fts3SegFilter filter;
147712  char *zStop;
147713  int nStop;                      /* Byte-length of string zStop */
147714  int iLangid;                    /* Language id to query */
147715  int isEof;                      /* True if cursor is at EOF */
147716  sqlite3_int64 iRowid;           /* Current rowid */
147717
147718  int iCol;                       /* Current value of 'col' column */
147719  int nStat;                      /* Size of aStat[] array */
147720  struct Fts3auxColstats {
147721    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
147722    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
147723  } *aStat;
147724};
147725
147726/*
147727** Schema of the terms table.
147728*/
147729#define FTS3_AUX_SCHEMA \
147730  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
147731
147732/*
147733** This function does all the work for both the xConnect and xCreate methods.
147734** These tables have no persistent representation of their own, so xConnect
147735** and xCreate are identical operations.
147736*/
147737static int fts3auxConnectMethod(
147738  sqlite3 *db,                    /* Database connection */
147739  void *pUnused,                  /* Unused */
147740  int argc,                       /* Number of elements in argv array */
147741  const char * const *argv,       /* xCreate/xConnect argument array */
147742  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
147743  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
147744){
147745  char const *zDb;                /* Name of database (e.g. "main") */
147746  char const *zFts3;              /* Name of fts3 table */
147747  int nDb;                        /* Result of strlen(zDb) */
147748  int nFts3;                      /* Result of strlen(zFts3) */
147749  int nByte;                      /* Bytes of space to allocate here */
147750  int rc;                         /* value returned by declare_vtab() */
147751  Fts3auxTable *p;                /* Virtual table object to return */
147752
147753  UNUSED_PARAMETER(pUnused);
147754
147755  /* The user should invoke this in one of two forms:
147756  **
147757  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
147758  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
147759  */
147760  if( argc!=4 && argc!=5 ) goto bad_args;
147761
147762  zDb = argv[1];
147763  nDb = (int)strlen(zDb);
147764  if( argc==5 ){
147765    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
147766      zDb = argv[3];
147767      nDb = (int)strlen(zDb);
147768      zFts3 = argv[4];
147769    }else{
147770      goto bad_args;
147771    }
147772  }else{
147773    zFts3 = argv[3];
147774  }
147775  nFts3 = (int)strlen(zFts3);
147776
147777  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
147778  if( rc!=SQLITE_OK ) return rc;
147779
147780  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
147781  p = (Fts3auxTable *)sqlite3_malloc(nByte);
147782  if( !p ) return SQLITE_NOMEM;
147783  memset(p, 0, nByte);
147784
147785  p->pFts3Tab = (Fts3Table *)&p[1];
147786  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
147787  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
147788  p->pFts3Tab->db = db;
147789  p->pFts3Tab->nIndex = 1;
147790
147791  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
147792  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
147793  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
147794
147795  *ppVtab = (sqlite3_vtab *)p;
147796  return SQLITE_OK;
147797
147798 bad_args:
147799  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
147800  return SQLITE_ERROR;
147801}
147802
147803/*
147804** This function does the work for both the xDisconnect and xDestroy methods.
147805** These tables have no persistent representation of their own, so xDisconnect
147806** and xDestroy are identical operations.
147807*/
147808static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
147809  Fts3auxTable *p = (Fts3auxTable *)pVtab;
147810  Fts3Table *pFts3 = p->pFts3Tab;
147811  int i;
147812
147813  /* Free any prepared statements held */
147814  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
147815    sqlite3_finalize(pFts3->aStmt[i]);
147816  }
147817  sqlite3_free(pFts3->zSegmentsTbl);
147818  sqlite3_free(p);
147819  return SQLITE_OK;
147820}
147821
147822#define FTS4AUX_EQ_CONSTRAINT 1
147823#define FTS4AUX_GE_CONSTRAINT 2
147824#define FTS4AUX_LE_CONSTRAINT 4
147825
147826/*
147827** xBestIndex - Analyze a WHERE and ORDER BY clause.
147828*/
147829static int fts3auxBestIndexMethod(
147830  sqlite3_vtab *pVTab,
147831  sqlite3_index_info *pInfo
147832){
147833  int i;
147834  int iEq = -1;
147835  int iGe = -1;
147836  int iLe = -1;
147837  int iLangid = -1;
147838  int iNext = 1;                  /* Next free argvIndex value */
147839
147840  UNUSED_PARAMETER(pVTab);
147841
147842  /* This vtab delivers always results in "ORDER BY term ASC" order. */
147843  if( pInfo->nOrderBy==1
147844   && pInfo->aOrderBy[0].iColumn==0
147845   && pInfo->aOrderBy[0].desc==0
147846  ){
147847    pInfo->orderByConsumed = 1;
147848  }
147849
147850  /* Search for equality and range constraints on the "term" column.
147851  ** And equality constraints on the hidden "languageid" column. */
147852  for(i=0; i<pInfo->nConstraint; i++){
147853    if( pInfo->aConstraint[i].usable ){
147854      int op = pInfo->aConstraint[i].op;
147855      int iCol = pInfo->aConstraint[i].iColumn;
147856
147857      if( iCol==0 ){
147858        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
147859        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
147860        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
147861        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
147862        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
147863      }
147864      if( iCol==4 ){
147865        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
147866      }
147867    }
147868  }
147869
147870  if( iEq>=0 ){
147871    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
147872    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
147873    pInfo->estimatedCost = 5;
147874  }else{
147875    pInfo->idxNum = 0;
147876    pInfo->estimatedCost = 20000;
147877    if( iGe>=0 ){
147878      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
147879      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
147880      pInfo->estimatedCost /= 2;
147881    }
147882    if( iLe>=0 ){
147883      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
147884      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
147885      pInfo->estimatedCost /= 2;
147886    }
147887  }
147888  if( iLangid>=0 ){
147889    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
147890    pInfo->estimatedCost--;
147891  }
147892
147893  return SQLITE_OK;
147894}
147895
147896/*
147897** xOpen - Open a cursor.
147898*/
147899static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
147900  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
147901
147902  UNUSED_PARAMETER(pVTab);
147903
147904  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
147905  if( !pCsr ) return SQLITE_NOMEM;
147906  memset(pCsr, 0, sizeof(Fts3auxCursor));
147907
147908  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
147909  return SQLITE_OK;
147910}
147911
147912/*
147913** xClose - Close a cursor.
147914*/
147915static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
147916  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147917  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147918
147919  sqlite3Fts3SegmentsClose(pFts3);
147920  sqlite3Fts3SegReaderFinish(&pCsr->csr);
147921  sqlite3_free((void *)pCsr->filter.zTerm);
147922  sqlite3_free(pCsr->zStop);
147923  sqlite3_free(pCsr->aStat);
147924  sqlite3_free(pCsr);
147925  return SQLITE_OK;
147926}
147927
147928static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
147929  if( nSize>pCsr->nStat ){
147930    struct Fts3auxColstats *aNew;
147931    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
147932        sizeof(struct Fts3auxColstats) * nSize
147933    );
147934    if( aNew==0 ) return SQLITE_NOMEM;
147935    memset(&aNew[pCsr->nStat], 0,
147936        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
147937    );
147938    pCsr->aStat = aNew;
147939    pCsr->nStat = nSize;
147940  }
147941  return SQLITE_OK;
147942}
147943
147944/*
147945** xNext - Advance the cursor to the next row, if any.
147946*/
147947static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
147948  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147949  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147950  int rc;
147951
147952  /* Increment our pretend rowid value. */
147953  pCsr->iRowid++;
147954
147955  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
147956    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
147957  }
147958
147959  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
147960  if( rc==SQLITE_ROW ){
147961    int i = 0;
147962    int nDoclist = pCsr->csr.nDoclist;
147963    char *aDoclist = pCsr->csr.aDoclist;
147964    int iCol;
147965
147966    int eState = 0;
147967
147968    if( pCsr->zStop ){
147969      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
147970      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
147971      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
147972        pCsr->isEof = 1;
147973        return SQLITE_OK;
147974      }
147975    }
147976
147977    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
147978    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
147979    iCol = 0;
147980
147981    while( i<nDoclist ){
147982      sqlite3_int64 v = 0;
147983
147984      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
147985      switch( eState ){
147986        /* State 0. In this state the integer just read was a docid. */
147987        case 0:
147988          pCsr->aStat[0].nDoc++;
147989          eState = 1;
147990          iCol = 0;
147991          break;
147992
147993        /* State 1. In this state we are expecting either a 1, indicating
147994        ** that the following integer will be a column number, or the
147995        ** start of a position list for column 0.
147996        **
147997        ** The only difference between state 1 and state 2 is that if the
147998        ** integer encountered in state 1 is not 0 or 1, then we need to
147999        ** increment the column 0 "nDoc" count for this term.
148000        */
148001        case 1:
148002          assert( iCol==0 );
148003          if( v>1 ){
148004            pCsr->aStat[1].nDoc++;
148005          }
148006          eState = 2;
148007          /* fall through */
148008
148009        case 2:
148010          if( v==0 ){       /* 0x00. Next integer will be a docid. */
148011            eState = 0;
148012          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
148013            eState = 3;
148014          }else{            /* 2 or greater. A position. */
148015            pCsr->aStat[iCol+1].nOcc++;
148016            pCsr->aStat[0].nOcc++;
148017          }
148018          break;
148019
148020        /* State 3. The integer just read is a column number. */
148021        default: assert( eState==3 );
148022          iCol = (int)v;
148023          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
148024          pCsr->aStat[iCol+1].nDoc++;
148025          eState = 2;
148026          break;
148027      }
148028    }
148029
148030    pCsr->iCol = 0;
148031    rc = SQLITE_OK;
148032  }else{
148033    pCsr->isEof = 1;
148034  }
148035  return rc;
148036}
148037
148038/*
148039** xFilter - Initialize a cursor to point at the start of its data.
148040*/
148041static int fts3auxFilterMethod(
148042  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
148043  int idxNum,                     /* Strategy index */
148044  const char *idxStr,             /* Unused */
148045  int nVal,                       /* Number of elements in apVal */
148046  sqlite3_value **apVal           /* Arguments for the indexing scheme */
148047){
148048  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148049  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
148050  int rc;
148051  int isScan = 0;
148052  int iLangVal = 0;               /* Language id to query */
148053
148054  int iEq = -1;                   /* Index of term=? value in apVal */
148055  int iGe = -1;                   /* Index of term>=? value in apVal */
148056  int iLe = -1;                   /* Index of term<=? value in apVal */
148057  int iLangid = -1;               /* Index of languageid=? value in apVal */
148058  int iNext = 0;
148059
148060  UNUSED_PARAMETER(nVal);
148061  UNUSED_PARAMETER(idxStr);
148062
148063  assert( idxStr==0 );
148064  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
148065       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
148066       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
148067  );
148068
148069  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
148070    iEq = iNext++;
148071  }else{
148072    isScan = 1;
148073    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
148074      iGe = iNext++;
148075    }
148076    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
148077      iLe = iNext++;
148078    }
148079  }
148080  if( iNext<nVal ){
148081    iLangid = iNext++;
148082  }
148083
148084  /* In case this cursor is being reused, close and zero it. */
148085  testcase(pCsr->filter.zTerm);
148086  sqlite3Fts3SegReaderFinish(&pCsr->csr);
148087  sqlite3_free((void *)pCsr->filter.zTerm);
148088  sqlite3_free(pCsr->aStat);
148089  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
148090
148091  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
148092  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
148093
148094  if( iEq>=0 || iGe>=0 ){
148095    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
148096    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
148097    if( zStr ){
148098      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
148099      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
148100      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
148101    }
148102  }
148103
148104  if( iLe>=0 ){
148105    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
148106    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
148107    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
148108  }
148109
148110  if( iLangid>=0 ){
148111    iLangVal = sqlite3_value_int(apVal[iLangid]);
148112
148113    /* If the user specified a negative value for the languageid, use zero
148114    ** instead. This works, as the "languageid=?" constraint will also
148115    ** be tested by the VDBE layer. The test will always be false (since
148116    ** this module will not return a row with a negative languageid), and
148117    ** so the overall query will return zero rows.  */
148118    if( iLangVal<0 ) iLangVal = 0;
148119  }
148120  pCsr->iLangid = iLangVal;
148121
148122  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
148123      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
148124  );
148125  if( rc==SQLITE_OK ){
148126    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
148127  }
148128
148129  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
148130  return rc;
148131}
148132
148133/*
148134** xEof - Return true if the cursor is at EOF, or false otherwise.
148135*/
148136static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
148137  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148138  return pCsr->isEof;
148139}
148140
148141/*
148142** xColumn - Return a column value.
148143*/
148144static int fts3auxColumnMethod(
148145  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148146  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
148147  int iCol                        /* Index of column to read value from */
148148){
148149  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
148150
148151  assert( p->isEof==0 );
148152  switch( iCol ){
148153    case 0: /* term */
148154      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
148155      break;
148156
148157    case 1: /* col */
148158      if( p->iCol ){
148159        sqlite3_result_int(pCtx, p->iCol-1);
148160      }else{
148161        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
148162      }
148163      break;
148164
148165    case 2: /* documents */
148166      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
148167      break;
148168
148169    case 3: /* occurrences */
148170      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
148171      break;
148172
148173    default: /* languageid */
148174      assert( iCol==4 );
148175      sqlite3_result_int(pCtx, p->iLangid);
148176      break;
148177  }
148178
148179  return SQLITE_OK;
148180}
148181
148182/*
148183** xRowid - Return the current rowid for the cursor.
148184*/
148185static int fts3auxRowidMethod(
148186  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148187  sqlite_int64 *pRowid            /* OUT: Rowid value */
148188){
148189  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148190  *pRowid = pCsr->iRowid;
148191  return SQLITE_OK;
148192}
148193
148194/*
148195** Register the fts3aux module with database connection db. Return SQLITE_OK
148196** if successful or an error code if sqlite3_create_module() fails.
148197*/
148198SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
148199  static const sqlite3_module fts3aux_module = {
148200     0,                           /* iVersion      */
148201     fts3auxConnectMethod,        /* xCreate       */
148202     fts3auxConnectMethod,        /* xConnect      */
148203     fts3auxBestIndexMethod,      /* xBestIndex    */
148204     fts3auxDisconnectMethod,     /* xDisconnect   */
148205     fts3auxDisconnectMethod,     /* xDestroy      */
148206     fts3auxOpenMethod,           /* xOpen         */
148207     fts3auxCloseMethod,          /* xClose        */
148208     fts3auxFilterMethod,         /* xFilter       */
148209     fts3auxNextMethod,           /* xNext         */
148210     fts3auxEofMethod,            /* xEof          */
148211     fts3auxColumnMethod,         /* xColumn       */
148212     fts3auxRowidMethod,          /* xRowid        */
148213     0,                           /* xUpdate       */
148214     0,                           /* xBegin        */
148215     0,                           /* xSync         */
148216     0,                           /* xCommit       */
148217     0,                           /* xRollback     */
148218     0,                           /* xFindFunction */
148219     0,                           /* xRename       */
148220     0,                           /* xSavepoint    */
148221     0,                           /* xRelease      */
148222     0                            /* xRollbackTo   */
148223  };
148224  int rc;                         /* Return code */
148225
148226  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
148227  return rc;
148228}
148229
148230#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
148231
148232/************** End of fts3_aux.c ********************************************/
148233/************** Begin file fts3_expr.c ***************************************/
148234/*
148235** 2008 Nov 28
148236**
148237** The author disclaims copyright to this source code.  In place of
148238** a legal notice, here is a blessing:
148239**
148240**    May you do good and not evil.
148241**    May you find forgiveness for yourself and forgive others.
148242**    May you share freely, never taking more than you give.
148243**
148244******************************************************************************
148245**
148246** This module contains code that implements a parser for fts3 query strings
148247** (the right-hand argument to the MATCH operator). Because the supported
148248** syntax is relatively simple, the whole tokenizer/parser system is
148249** hand-coded.
148250*/
148251/* #include "fts3Int.h" */
148252#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
148253
148254/*
148255** By default, this module parses the legacy syntax that has been
148256** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
148257** is defined, then it uses the new syntax. The differences between
148258** the new and the old syntaxes are:
148259**
148260**  a) The new syntax supports parenthesis. The old does not.
148261**
148262**  b) The new syntax supports the AND and NOT operators. The old does not.
148263**
148264**  c) The old syntax supports the "-" token qualifier. This is not
148265**     supported by the new syntax (it is replaced by the NOT operator).
148266**
148267**  d) When using the old syntax, the OR operator has a greater precedence
148268**     than an implicit AND. When using the new, both implicity and explicit
148269**     AND operators have a higher precedence than OR.
148270**
148271** If compiled with SQLITE_TEST defined, then this module exports the
148272** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
148273** to zero causes the module to use the old syntax. If it is set to
148274** non-zero the new syntax is activated. This is so both syntaxes can
148275** be tested using a single build of testfixture.
148276**
148277** The following describes the syntax supported by the fts3 MATCH
148278** operator in a similar format to that used by the lemon parser
148279** generator. This module does not use actually lemon, it uses a
148280** custom parser.
148281**
148282**   query ::= andexpr (OR andexpr)*.
148283**
148284**   andexpr ::= notexpr (AND? notexpr)*.
148285**
148286**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
148287**   notexpr ::= LP query RP.
148288**
148289**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
148290**
148291**   distance_opt ::= .
148292**   distance_opt ::= / INTEGER.
148293**
148294**   phrase ::= TOKEN.
148295**   phrase ::= COLUMN:TOKEN.
148296**   phrase ::= "TOKEN TOKEN TOKEN...".
148297*/
148298
148299#ifdef SQLITE_TEST
148300SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
148301#else
148302# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
148303#  define sqlite3_fts3_enable_parentheses 1
148304# else
148305#  define sqlite3_fts3_enable_parentheses 0
148306# endif
148307#endif
148308
148309/*
148310** Default span for NEAR operators.
148311*/
148312#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
148313
148314/* #include <string.h> */
148315/* #include <assert.h> */
148316
148317/*
148318** isNot:
148319**   This variable is used by function getNextNode(). When getNextNode() is
148320**   called, it sets ParseContext.isNot to true if the 'next node' is a
148321**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
148322**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
148323**   zero.
148324*/
148325typedef struct ParseContext ParseContext;
148326struct ParseContext {
148327  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
148328  int iLangid;                        /* Language id used with tokenizer */
148329  const char **azCol;                 /* Array of column names for fts3 table */
148330  int bFts4;                          /* True to allow FTS4-only syntax */
148331  int nCol;                           /* Number of entries in azCol[] */
148332  int iDefaultCol;                    /* Default column to query */
148333  int isNot;                          /* True if getNextNode() sees a unary - */
148334  sqlite3_context *pCtx;              /* Write error message here */
148335  int nNest;                          /* Number of nested brackets */
148336};
148337
148338/*
148339** This function is equivalent to the standard isspace() function.
148340**
148341** The standard isspace() can be awkward to use safely, because although it
148342** is defined to accept an argument of type int, its behavior when passed
148343** an integer that falls outside of the range of the unsigned char type
148344** is undefined (and sometimes, "undefined" means segfault). This wrapper
148345** is defined to accept an argument of type char, and always returns 0 for
148346** any values that fall outside of the range of the unsigned char type (i.e.
148347** negative values).
148348*/
148349static int fts3isspace(char c){
148350  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
148351}
148352
148353/*
148354** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
148355** zero the memory before returning a pointer to it. If unsuccessful,
148356** return NULL.
148357*/
148358static void *fts3MallocZero(int nByte){
148359  void *pRet = sqlite3_malloc(nByte);
148360  if( pRet ) memset(pRet, 0, nByte);
148361  return pRet;
148362}
148363
148364SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
148365  sqlite3_tokenizer *pTokenizer,
148366  int iLangid,
148367  const char *z,
148368  int n,
148369  sqlite3_tokenizer_cursor **ppCsr
148370){
148371  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148372  sqlite3_tokenizer_cursor *pCsr = 0;
148373  int rc;
148374
148375  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
148376  assert( rc==SQLITE_OK || pCsr==0 );
148377  if( rc==SQLITE_OK ){
148378    pCsr->pTokenizer = pTokenizer;
148379    if( pModule->iVersion>=1 ){
148380      rc = pModule->xLanguageid(pCsr, iLangid);
148381      if( rc!=SQLITE_OK ){
148382        pModule->xClose(pCsr);
148383        pCsr = 0;
148384      }
148385    }
148386  }
148387  *ppCsr = pCsr;
148388  return rc;
148389}
148390
148391/*
148392** Function getNextNode(), which is called by fts3ExprParse(), may itself
148393** call fts3ExprParse(). So this forward declaration is required.
148394*/
148395static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
148396
148397/*
148398** Extract the next token from buffer z (length n) using the tokenizer
148399** and other information (column names etc.) in pParse. Create an Fts3Expr
148400** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
148401** single token and set *ppExpr to point to it. If the end of the buffer is
148402** reached before a token is found, set *ppExpr to zero. It is the
148403** responsibility of the caller to eventually deallocate the allocated
148404** Fts3Expr structure (if any) by passing it to sqlite3_free().
148405**
148406** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
148407** fails.
148408*/
148409static int getNextToken(
148410  ParseContext *pParse,                   /* fts3 query parse context */
148411  int iCol,                               /* Value for Fts3Phrase.iColumn */
148412  const char *z, int n,                   /* Input string */
148413  Fts3Expr **ppExpr,                      /* OUT: expression */
148414  int *pnConsumed                         /* OUT: Number of bytes consumed */
148415){
148416  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
148417  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148418  int rc;
148419  sqlite3_tokenizer_cursor *pCursor;
148420  Fts3Expr *pRet = 0;
148421  int i = 0;
148422
148423  /* Set variable i to the maximum number of bytes of input to tokenize. */
148424  for(i=0; i<n; i++){
148425    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
148426    if( z[i]=='"' ) break;
148427  }
148428
148429  *pnConsumed = i;
148430  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
148431  if( rc==SQLITE_OK ){
148432    const char *zToken;
148433    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
148434    int nByte;                               /* total space to allocate */
148435
148436    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
148437    if( rc==SQLITE_OK ){
148438      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
148439      pRet = (Fts3Expr *)fts3MallocZero(nByte);
148440      if( !pRet ){
148441        rc = SQLITE_NOMEM;
148442      }else{
148443        pRet->eType = FTSQUERY_PHRASE;
148444        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
148445        pRet->pPhrase->nToken = 1;
148446        pRet->pPhrase->iColumn = iCol;
148447        pRet->pPhrase->aToken[0].n = nToken;
148448        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
148449        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
148450
148451        if( iEnd<n && z[iEnd]=='*' ){
148452          pRet->pPhrase->aToken[0].isPrefix = 1;
148453          iEnd++;
148454        }
148455
148456        while( 1 ){
148457          if( !sqlite3_fts3_enable_parentheses
148458           && iStart>0 && z[iStart-1]=='-'
148459          ){
148460            pParse->isNot = 1;
148461            iStart--;
148462          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
148463            pRet->pPhrase->aToken[0].bFirst = 1;
148464            iStart--;
148465          }else{
148466            break;
148467          }
148468        }
148469
148470      }
148471      *pnConsumed = iEnd;
148472    }else if( i && rc==SQLITE_DONE ){
148473      rc = SQLITE_OK;
148474    }
148475
148476    pModule->xClose(pCursor);
148477  }
148478
148479  *ppExpr = pRet;
148480  return rc;
148481}
148482
148483
148484/*
148485** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
148486** then free the old allocation.
148487*/
148488static void *fts3ReallocOrFree(void *pOrig, int nNew){
148489  void *pRet = sqlite3_realloc(pOrig, nNew);
148490  if( !pRet ){
148491    sqlite3_free(pOrig);
148492  }
148493  return pRet;
148494}
148495
148496/*
148497** Buffer zInput, length nInput, contains the contents of a quoted string
148498** that appeared as part of an fts3 query expression. Neither quote character
148499** is included in the buffer. This function attempts to tokenize the entire
148500** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
148501** containing the results.
148502**
148503** If successful, SQLITE_OK is returned and *ppExpr set to point at the
148504** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
148505** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
148506** to 0.
148507*/
148508static int getNextString(
148509  ParseContext *pParse,                   /* fts3 query parse context */
148510  const char *zInput, int nInput,         /* Input string */
148511  Fts3Expr **ppExpr                       /* OUT: expression */
148512){
148513  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
148514  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148515  int rc;
148516  Fts3Expr *p = 0;
148517  sqlite3_tokenizer_cursor *pCursor = 0;
148518  char *zTemp = 0;
148519  int nTemp = 0;
148520
148521  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
148522  int nToken = 0;
148523
148524  /* The final Fts3Expr data structure, including the Fts3Phrase,
148525  ** Fts3PhraseToken structures token buffers are all stored as a single
148526  ** allocation so that the expression can be freed with a single call to
148527  ** sqlite3_free(). Setting this up requires a two pass approach.
148528  **
148529  ** The first pass, in the block below, uses a tokenizer cursor to iterate
148530  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
148531  ** to assemble data in two dynamic buffers:
148532  **
148533  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
148534  **             structure, followed by the array of Fts3PhraseToken
148535  **             structures. This pass only populates the Fts3PhraseToken array.
148536  **
148537  **   Buffer zTemp: Contains copies of all tokens.
148538  **
148539  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
148540  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
148541  ** structures.
148542  */
148543  rc = sqlite3Fts3OpenTokenizer(
148544      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
148545  if( rc==SQLITE_OK ){
148546    int ii;
148547    for(ii=0; rc==SQLITE_OK; ii++){
148548      const char *zByte;
148549      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
148550      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
148551      if( rc==SQLITE_OK ){
148552        Fts3PhraseToken *pToken;
148553
148554        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
148555        if( !p ) goto no_mem;
148556
148557        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
148558        if( !zTemp ) goto no_mem;
148559
148560        assert( nToken==ii );
148561        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
148562        memset(pToken, 0, sizeof(Fts3PhraseToken));
148563
148564        memcpy(&zTemp[nTemp], zByte, nByte);
148565        nTemp += nByte;
148566
148567        pToken->n = nByte;
148568        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
148569        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
148570        nToken = ii+1;
148571      }
148572    }
148573
148574    pModule->xClose(pCursor);
148575    pCursor = 0;
148576  }
148577
148578  if( rc==SQLITE_DONE ){
148579    int jj;
148580    char *zBuf = 0;
148581
148582    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
148583    if( !p ) goto no_mem;
148584    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
148585    p->eType = FTSQUERY_PHRASE;
148586    p->pPhrase = (Fts3Phrase *)&p[1];
148587    p->pPhrase->iColumn = pParse->iDefaultCol;
148588    p->pPhrase->nToken = nToken;
148589
148590    zBuf = (char *)&p->pPhrase->aToken[nToken];
148591    if( zTemp ){
148592      memcpy(zBuf, zTemp, nTemp);
148593      sqlite3_free(zTemp);
148594    }else{
148595      assert( nTemp==0 );
148596    }
148597
148598    for(jj=0; jj<p->pPhrase->nToken; jj++){
148599      p->pPhrase->aToken[jj].z = zBuf;
148600      zBuf += p->pPhrase->aToken[jj].n;
148601    }
148602    rc = SQLITE_OK;
148603  }
148604
148605  *ppExpr = p;
148606  return rc;
148607no_mem:
148608
148609  if( pCursor ){
148610    pModule->xClose(pCursor);
148611  }
148612  sqlite3_free(zTemp);
148613  sqlite3_free(p);
148614  *ppExpr = 0;
148615  return SQLITE_NOMEM;
148616}
148617
148618/*
148619** The output variable *ppExpr is populated with an allocated Fts3Expr
148620** structure, or set to 0 if the end of the input buffer is reached.
148621**
148622** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
148623** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
148624** If SQLITE_ERROR is returned, pContext is populated with an error message.
148625*/
148626static int getNextNode(
148627  ParseContext *pParse,                   /* fts3 query parse context */
148628  const char *z, int n,                   /* Input string */
148629  Fts3Expr **ppExpr,                      /* OUT: expression */
148630  int *pnConsumed                         /* OUT: Number of bytes consumed */
148631){
148632  static const struct Fts3Keyword {
148633    char *z;                              /* Keyword text */
148634    unsigned char n;                      /* Length of the keyword */
148635    unsigned char parenOnly;              /* Only valid in paren mode */
148636    unsigned char eType;                  /* Keyword code */
148637  } aKeyword[] = {
148638    { "OR" ,  2, 0, FTSQUERY_OR   },
148639    { "AND",  3, 1, FTSQUERY_AND  },
148640    { "NOT",  3, 1, FTSQUERY_NOT  },
148641    { "NEAR", 4, 0, FTSQUERY_NEAR }
148642  };
148643  int ii;
148644  int iCol;
148645  int iColLen;
148646  int rc;
148647  Fts3Expr *pRet = 0;
148648
148649  const char *zInput = z;
148650  int nInput = n;
148651
148652  pParse->isNot = 0;
148653
148654  /* Skip over any whitespace before checking for a keyword, an open or
148655  ** close bracket, or a quoted string.
148656  */
148657  while( nInput>0 && fts3isspace(*zInput) ){
148658    nInput--;
148659    zInput++;
148660  }
148661  if( nInput==0 ){
148662    return SQLITE_DONE;
148663  }
148664
148665  /* See if we are dealing with a keyword. */
148666  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
148667    const struct Fts3Keyword *pKey = &aKeyword[ii];
148668
148669    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
148670      continue;
148671    }
148672
148673    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
148674      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
148675      int nKey = pKey->n;
148676      char cNext;
148677
148678      /* If this is a "NEAR" keyword, check for an explicit nearness. */
148679      if( pKey->eType==FTSQUERY_NEAR ){
148680        assert( nKey==4 );
148681        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
148682          nNear = 0;
148683          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
148684            nNear = nNear * 10 + (zInput[nKey] - '0');
148685          }
148686        }
148687      }
148688
148689      /* At this point this is probably a keyword. But for that to be true,
148690      ** the next byte must contain either whitespace, an open or close
148691      ** parenthesis, a quote character, or EOF.
148692      */
148693      cNext = zInput[nKey];
148694      if( fts3isspace(cNext)
148695       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
148696      ){
148697        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
148698        if( !pRet ){
148699          return SQLITE_NOMEM;
148700        }
148701        pRet->eType = pKey->eType;
148702        pRet->nNear = nNear;
148703        *ppExpr = pRet;
148704        *pnConsumed = (int)((zInput - z) + nKey);
148705        return SQLITE_OK;
148706      }
148707
148708      /* Turns out that wasn't a keyword after all. This happens if the
148709      ** user has supplied a token such as "ORacle". Continue.
148710      */
148711    }
148712  }
148713
148714  /* See if we are dealing with a quoted phrase. If this is the case, then
148715  ** search for the closing quote and pass the whole string to getNextString()
148716  ** for processing. This is easy to do, as fts3 has no syntax for escaping
148717  ** a quote character embedded in a string.
148718  */
148719  if( *zInput=='"' ){
148720    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
148721    *pnConsumed = (int)((zInput - z) + ii + 1);
148722    if( ii==nInput ){
148723      return SQLITE_ERROR;
148724    }
148725    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
148726  }
148727
148728  if( sqlite3_fts3_enable_parentheses ){
148729    if( *zInput=='(' ){
148730      int nConsumed = 0;
148731      pParse->nNest++;
148732      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
148733      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
148734      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
148735      return rc;
148736    }else if( *zInput==')' ){
148737      pParse->nNest--;
148738      *pnConsumed = (int)((zInput - z) + 1);
148739      *ppExpr = 0;
148740      return SQLITE_DONE;
148741    }
148742  }
148743
148744  /* If control flows to this point, this must be a regular token, or
148745  ** the end of the input. Read a regular token using the sqlite3_tokenizer
148746  ** interface. Before doing so, figure out if there is an explicit
148747  ** column specifier for the token.
148748  **
148749  ** TODO: Strangely, it is not possible to associate a column specifier
148750  ** with a quoted phrase, only with a single token. Not sure if this was
148751  ** an implementation artifact or an intentional decision when fts3 was
148752  ** first implemented. Whichever it was, this module duplicates the
148753  ** limitation.
148754  */
148755  iCol = pParse->iDefaultCol;
148756  iColLen = 0;
148757  for(ii=0; ii<pParse->nCol; ii++){
148758    const char *zStr = pParse->azCol[ii];
148759    int nStr = (int)strlen(zStr);
148760    if( nInput>nStr && zInput[nStr]==':'
148761     && sqlite3_strnicmp(zStr, zInput, nStr)==0
148762    ){
148763      iCol = ii;
148764      iColLen = (int)((zInput - z) + nStr + 1);
148765      break;
148766    }
148767  }
148768  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
148769  *pnConsumed += iColLen;
148770  return rc;
148771}
148772
148773/*
148774** The argument is an Fts3Expr structure for a binary operator (any type
148775** except an FTSQUERY_PHRASE). Return an integer value representing the
148776** precedence of the operator. Lower values have a higher precedence (i.e.
148777** group more tightly). For example, in the C language, the == operator
148778** groups more tightly than ||, and would therefore have a higher precedence.
148779**
148780** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
148781** is defined), the order of the operators in precedence from highest to
148782** lowest is:
148783**
148784**   NEAR
148785**   NOT
148786**   AND (including implicit ANDs)
148787**   OR
148788**
148789** Note that when using the old query syntax, the OR operator has a higher
148790** precedence than the AND operator.
148791*/
148792static int opPrecedence(Fts3Expr *p){
148793  assert( p->eType!=FTSQUERY_PHRASE );
148794  if( sqlite3_fts3_enable_parentheses ){
148795    return p->eType;
148796  }else if( p->eType==FTSQUERY_NEAR ){
148797    return 1;
148798  }else if( p->eType==FTSQUERY_OR ){
148799    return 2;
148800  }
148801  assert( p->eType==FTSQUERY_AND );
148802  return 3;
148803}
148804
148805/*
148806** Argument ppHead contains a pointer to the current head of a query
148807** expression tree being parsed. pPrev is the expression node most recently
148808** inserted into the tree. This function adds pNew, which is always a binary
148809** operator node, into the expression tree based on the relative precedence
148810** of pNew and the existing nodes of the tree. This may result in the head
148811** of the tree changing, in which case *ppHead is set to the new root node.
148812*/
148813static void insertBinaryOperator(
148814  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
148815  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
148816  Fts3Expr *pNew           /* New binary node to insert into expression tree */
148817){
148818  Fts3Expr *pSplit = pPrev;
148819  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
148820    pSplit = pSplit->pParent;
148821  }
148822
148823  if( pSplit->pParent ){
148824    assert( pSplit->pParent->pRight==pSplit );
148825    pSplit->pParent->pRight = pNew;
148826    pNew->pParent = pSplit->pParent;
148827  }else{
148828    *ppHead = pNew;
148829  }
148830  pNew->pLeft = pSplit;
148831  pSplit->pParent = pNew;
148832}
148833
148834/*
148835** Parse the fts3 query expression found in buffer z, length n. This function
148836** returns either when the end of the buffer is reached or an unmatched
148837** closing bracket - ')' - is encountered.
148838**
148839** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
148840** parsed form of the expression and *pnConsumed is set to the number of
148841** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
148842** (out of memory error) or SQLITE_ERROR (parse error) is returned.
148843*/
148844static int fts3ExprParse(
148845  ParseContext *pParse,                   /* fts3 query parse context */
148846  const char *z, int n,                   /* Text of MATCH query */
148847  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
148848  int *pnConsumed                         /* OUT: Number of bytes consumed */
148849){
148850  Fts3Expr *pRet = 0;
148851  Fts3Expr *pPrev = 0;
148852  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
148853  int nIn = n;
148854  const char *zIn = z;
148855  int rc = SQLITE_OK;
148856  int isRequirePhrase = 1;
148857
148858  while( rc==SQLITE_OK ){
148859    Fts3Expr *p = 0;
148860    int nByte = 0;
148861
148862    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
148863    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
148864    if( rc==SQLITE_OK ){
148865      if( p ){
148866        int isPhrase;
148867
148868        if( !sqlite3_fts3_enable_parentheses
148869            && p->eType==FTSQUERY_PHRASE && pParse->isNot
148870        ){
148871          /* Create an implicit NOT operator. */
148872          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
148873          if( !pNot ){
148874            sqlite3Fts3ExprFree(p);
148875            rc = SQLITE_NOMEM;
148876            goto exprparse_out;
148877          }
148878          pNot->eType = FTSQUERY_NOT;
148879          pNot->pRight = p;
148880          p->pParent = pNot;
148881          if( pNotBranch ){
148882            pNot->pLeft = pNotBranch;
148883            pNotBranch->pParent = pNot;
148884          }
148885          pNotBranch = pNot;
148886          p = pPrev;
148887        }else{
148888          int eType = p->eType;
148889          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
148890
148891          /* The isRequirePhrase variable is set to true if a phrase or
148892          ** an expression contained in parenthesis is required. If a
148893          ** binary operator (AND, OR, NOT or NEAR) is encounted when
148894          ** isRequirePhrase is set, this is a syntax error.
148895          */
148896          if( !isPhrase && isRequirePhrase ){
148897            sqlite3Fts3ExprFree(p);
148898            rc = SQLITE_ERROR;
148899            goto exprparse_out;
148900          }
148901
148902          if( isPhrase && !isRequirePhrase ){
148903            /* Insert an implicit AND operator. */
148904            Fts3Expr *pAnd;
148905            assert( pRet && pPrev );
148906            pAnd = fts3MallocZero(sizeof(Fts3Expr));
148907            if( !pAnd ){
148908              sqlite3Fts3ExprFree(p);
148909              rc = SQLITE_NOMEM;
148910              goto exprparse_out;
148911            }
148912            pAnd->eType = FTSQUERY_AND;
148913            insertBinaryOperator(&pRet, pPrev, pAnd);
148914            pPrev = pAnd;
148915          }
148916
148917          /* This test catches attempts to make either operand of a NEAR
148918           ** operator something other than a phrase. For example, either of
148919           ** the following:
148920           **
148921           **    (bracketed expression) NEAR phrase
148922           **    phrase NEAR (bracketed expression)
148923           **
148924           ** Return an error in either case.
148925           */
148926          if( pPrev && (
148927            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
148928         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
148929          )){
148930            sqlite3Fts3ExprFree(p);
148931            rc = SQLITE_ERROR;
148932            goto exprparse_out;
148933          }
148934
148935          if( isPhrase ){
148936            if( pRet ){
148937              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
148938              pPrev->pRight = p;
148939              p->pParent = pPrev;
148940            }else{
148941              pRet = p;
148942            }
148943          }else{
148944            insertBinaryOperator(&pRet, pPrev, p);
148945          }
148946          isRequirePhrase = !isPhrase;
148947        }
148948        pPrev = p;
148949      }
148950      assert( nByte>0 );
148951    }
148952    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
148953    nIn -= nByte;
148954    zIn += nByte;
148955  }
148956
148957  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
148958    rc = SQLITE_ERROR;
148959  }
148960
148961  if( rc==SQLITE_DONE ){
148962    rc = SQLITE_OK;
148963    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
148964      if( !pRet ){
148965        rc = SQLITE_ERROR;
148966      }else{
148967        Fts3Expr *pIter = pNotBranch;
148968        while( pIter->pLeft ){
148969          pIter = pIter->pLeft;
148970        }
148971        pIter->pLeft = pRet;
148972        pRet->pParent = pIter;
148973        pRet = pNotBranch;
148974      }
148975    }
148976  }
148977  *pnConsumed = n - nIn;
148978
148979exprparse_out:
148980  if( rc!=SQLITE_OK ){
148981    sqlite3Fts3ExprFree(pRet);
148982    sqlite3Fts3ExprFree(pNotBranch);
148983    pRet = 0;
148984  }
148985  *ppExpr = pRet;
148986  return rc;
148987}
148988
148989/*
148990** Return SQLITE_ERROR if the maximum depth of the expression tree passed
148991** as the only argument is more than nMaxDepth.
148992*/
148993static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
148994  int rc = SQLITE_OK;
148995  if( p ){
148996    if( nMaxDepth<0 ){
148997      rc = SQLITE_TOOBIG;
148998    }else{
148999      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
149000      if( rc==SQLITE_OK ){
149001        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
149002      }
149003    }
149004  }
149005  return rc;
149006}
149007
149008/*
149009** This function attempts to transform the expression tree at (*pp) to
149010** an equivalent but more balanced form. The tree is modified in place.
149011** If successful, SQLITE_OK is returned and (*pp) set to point to the
149012** new root expression node.
149013**
149014** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
149015**
149016** Otherwise, if an error occurs, an SQLite error code is returned and
149017** expression (*pp) freed.
149018*/
149019static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
149020  int rc = SQLITE_OK;             /* Return code */
149021  Fts3Expr *pRoot = *pp;          /* Initial root node */
149022  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
149023  int eType = pRoot->eType;       /* Type of node in this tree */
149024
149025  if( nMaxDepth==0 ){
149026    rc = SQLITE_ERROR;
149027  }
149028
149029  if( rc==SQLITE_OK ){
149030    if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
149031      Fts3Expr **apLeaf;
149032      apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
149033      if( 0==apLeaf ){
149034        rc = SQLITE_NOMEM;
149035      }else{
149036        memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
149037      }
149038
149039      if( rc==SQLITE_OK ){
149040        int i;
149041        Fts3Expr *p;
149042
149043        /* Set $p to point to the left-most leaf in the tree of eType nodes. */
149044        for(p=pRoot; p->eType==eType; p=p->pLeft){
149045          assert( p->pParent==0 || p->pParent->pLeft==p );
149046          assert( p->pLeft && p->pRight );
149047        }
149048
149049        /* This loop runs once for each leaf in the tree of eType nodes. */
149050        while( 1 ){
149051          int iLvl;
149052          Fts3Expr *pParent = p->pParent;     /* Current parent of p */
149053
149054          assert( pParent==0 || pParent->pLeft==p );
149055          p->pParent = 0;
149056          if( pParent ){
149057            pParent->pLeft = 0;
149058          }else{
149059            pRoot = 0;
149060          }
149061          rc = fts3ExprBalance(&p, nMaxDepth-1);
149062          if( rc!=SQLITE_OK ) break;
149063
149064          for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
149065            if( apLeaf[iLvl]==0 ){
149066              apLeaf[iLvl] = p;
149067              p = 0;
149068            }else{
149069              assert( pFree );
149070              pFree->pLeft = apLeaf[iLvl];
149071              pFree->pRight = p;
149072              pFree->pLeft->pParent = pFree;
149073              pFree->pRight->pParent = pFree;
149074
149075              p = pFree;
149076              pFree = pFree->pParent;
149077              p->pParent = 0;
149078              apLeaf[iLvl] = 0;
149079            }
149080          }
149081          if( p ){
149082            sqlite3Fts3ExprFree(p);
149083            rc = SQLITE_TOOBIG;
149084            break;
149085          }
149086
149087          /* If that was the last leaf node, break out of the loop */
149088          if( pParent==0 ) break;
149089
149090          /* Set $p to point to the next leaf in the tree of eType nodes */
149091          for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
149092
149093          /* Remove pParent from the original tree. */
149094          assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
149095          pParent->pRight->pParent = pParent->pParent;
149096          if( pParent->pParent ){
149097            pParent->pParent->pLeft = pParent->pRight;
149098          }else{
149099            assert( pParent==pRoot );
149100            pRoot = pParent->pRight;
149101          }
149102
149103          /* Link pParent into the free node list. It will be used as an
149104          ** internal node of the new tree.  */
149105          pParent->pParent = pFree;
149106          pFree = pParent;
149107        }
149108
149109        if( rc==SQLITE_OK ){
149110          p = 0;
149111          for(i=0; i<nMaxDepth; i++){
149112            if( apLeaf[i] ){
149113              if( p==0 ){
149114                p = apLeaf[i];
149115                p->pParent = 0;
149116              }else{
149117                assert( pFree!=0 );
149118                pFree->pRight = p;
149119                pFree->pLeft = apLeaf[i];
149120                pFree->pLeft->pParent = pFree;
149121                pFree->pRight->pParent = pFree;
149122
149123                p = pFree;
149124                pFree = pFree->pParent;
149125                p->pParent = 0;
149126              }
149127            }
149128          }
149129          pRoot = p;
149130        }else{
149131          /* An error occurred. Delete the contents of the apLeaf[] array
149132          ** and pFree list. Everything else is cleaned up by the call to
149133          ** sqlite3Fts3ExprFree(pRoot) below.  */
149134          Fts3Expr *pDel;
149135          for(i=0; i<nMaxDepth; i++){
149136            sqlite3Fts3ExprFree(apLeaf[i]);
149137          }
149138          while( (pDel=pFree)!=0 ){
149139            pFree = pDel->pParent;
149140            sqlite3_free(pDel);
149141          }
149142        }
149143
149144        assert( pFree==0 );
149145        sqlite3_free( apLeaf );
149146      }
149147    }else if( eType==FTSQUERY_NOT ){
149148      Fts3Expr *pLeft = pRoot->pLeft;
149149      Fts3Expr *pRight = pRoot->pRight;
149150
149151      pRoot->pLeft = 0;
149152      pRoot->pRight = 0;
149153      pLeft->pParent = 0;
149154      pRight->pParent = 0;
149155
149156      rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
149157      if( rc==SQLITE_OK ){
149158        rc = fts3ExprBalance(&pRight, nMaxDepth-1);
149159      }
149160
149161      if( rc!=SQLITE_OK ){
149162        sqlite3Fts3ExprFree(pRight);
149163        sqlite3Fts3ExprFree(pLeft);
149164      }else{
149165        assert( pLeft && pRight );
149166        pRoot->pLeft = pLeft;
149167        pLeft->pParent = pRoot;
149168        pRoot->pRight = pRight;
149169        pRight->pParent = pRoot;
149170      }
149171    }
149172  }
149173
149174  if( rc!=SQLITE_OK ){
149175    sqlite3Fts3ExprFree(pRoot);
149176    pRoot = 0;
149177  }
149178  *pp = pRoot;
149179  return rc;
149180}
149181
149182/*
149183** This function is similar to sqlite3Fts3ExprParse(), with the following
149184** differences:
149185**
149186**   1. It does not do expression rebalancing.
149187**   2. It does not check that the expression does not exceed the
149188**      maximum allowable depth.
149189**   3. Even if it fails, *ppExpr may still be set to point to an
149190**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
149191**      in this case.
149192*/
149193static int fts3ExprParseUnbalanced(
149194  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
149195  int iLangid,                        /* Language id for tokenizer */
149196  char **azCol,                       /* Array of column names for fts3 table */
149197  int bFts4,                          /* True to allow FTS4-only syntax */
149198  int nCol,                           /* Number of entries in azCol[] */
149199  int iDefaultCol,                    /* Default column to query */
149200  const char *z, int n,               /* Text of MATCH query */
149201  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
149202){
149203  int nParsed;
149204  int rc;
149205  ParseContext sParse;
149206
149207  memset(&sParse, 0, sizeof(ParseContext));
149208  sParse.pTokenizer = pTokenizer;
149209  sParse.iLangid = iLangid;
149210  sParse.azCol = (const char **)azCol;
149211  sParse.nCol = nCol;
149212  sParse.iDefaultCol = iDefaultCol;
149213  sParse.bFts4 = bFts4;
149214  if( z==0 ){
149215    *ppExpr = 0;
149216    return SQLITE_OK;
149217  }
149218  if( n<0 ){
149219    n = (int)strlen(z);
149220  }
149221  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
149222  assert( rc==SQLITE_OK || *ppExpr==0 );
149223
149224  /* Check for mismatched parenthesis */
149225  if( rc==SQLITE_OK && sParse.nNest ){
149226    rc = SQLITE_ERROR;
149227  }
149228
149229  return rc;
149230}
149231
149232/*
149233** Parameters z and n contain a pointer to and length of a buffer containing
149234** an fts3 query expression, respectively. This function attempts to parse the
149235** query expression and create a tree of Fts3Expr structures representing the
149236** parsed expression. If successful, *ppExpr is set to point to the head
149237** of the parsed expression tree and SQLITE_OK is returned. If an error
149238** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
149239** error) is returned and *ppExpr is set to 0.
149240**
149241** If parameter n is a negative number, then z is assumed to point to a
149242** nul-terminated string and the length is determined using strlen().
149243**
149244** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
149245** use to normalize query tokens while parsing the expression. The azCol[]
149246** array, which is assumed to contain nCol entries, should contain the names
149247** of each column in the target fts3 table, in order from left to right.
149248** Column names must be nul-terminated strings.
149249**
149250** The iDefaultCol parameter should be passed the index of the table column
149251** that appears on the left-hand-side of the MATCH operator (the default
149252** column to match against for tokens for which a column name is not explicitly
149253** specified as part of the query string), or -1 if tokens may by default
149254** match any table column.
149255*/
149256SQLITE_PRIVATE int sqlite3Fts3ExprParse(
149257  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
149258  int iLangid,                        /* Language id for tokenizer */
149259  char **azCol,                       /* Array of column names for fts3 table */
149260  int bFts4,                          /* True to allow FTS4-only syntax */
149261  int nCol,                           /* Number of entries in azCol[] */
149262  int iDefaultCol,                    /* Default column to query */
149263  const char *z, int n,               /* Text of MATCH query */
149264  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
149265  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
149266){
149267  int rc = fts3ExprParseUnbalanced(
149268      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
149269  );
149270
149271  /* Rebalance the expression. And check that its depth does not exceed
149272  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
149273  if( rc==SQLITE_OK && *ppExpr ){
149274    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
149275    if( rc==SQLITE_OK ){
149276      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
149277    }
149278  }
149279
149280  if( rc!=SQLITE_OK ){
149281    sqlite3Fts3ExprFree(*ppExpr);
149282    *ppExpr = 0;
149283    if( rc==SQLITE_TOOBIG ){
149284      sqlite3Fts3ErrMsg(pzErr,
149285          "FTS expression tree is too large (maximum depth %d)",
149286          SQLITE_FTS3_MAX_EXPR_DEPTH
149287      );
149288      rc = SQLITE_ERROR;
149289    }else if( rc==SQLITE_ERROR ){
149290      sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
149291    }
149292  }
149293
149294  return rc;
149295}
149296
149297/*
149298** Free a single node of an expression tree.
149299*/
149300static void fts3FreeExprNode(Fts3Expr *p){
149301  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
149302  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
149303  sqlite3_free(p->aMI);
149304  sqlite3_free(p);
149305}
149306
149307/*
149308** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
149309**
149310** This function would be simpler if it recursively called itself. But
149311** that would mean passing a sufficiently large expression to ExprParse()
149312** could cause a stack overflow.
149313*/
149314SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
149315  Fts3Expr *p;
149316  assert( pDel==0 || pDel->pParent==0 );
149317  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
149318    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
149319  }
149320  while( p ){
149321    Fts3Expr *pParent = p->pParent;
149322    fts3FreeExprNode(p);
149323    if( pParent && p==pParent->pLeft && pParent->pRight ){
149324      p = pParent->pRight;
149325      while( p && (p->pLeft || p->pRight) ){
149326        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
149327        p = (p->pLeft ? p->pLeft : p->pRight);
149328      }
149329    }else{
149330      p = pParent;
149331    }
149332  }
149333}
149334
149335/****************************************************************************
149336*****************************************************************************
149337** Everything after this point is just test code.
149338*/
149339
149340#ifdef SQLITE_TEST
149341
149342/* #include <stdio.h> */
149343
149344/*
149345** Function to query the hash-table of tokenizers (see README.tokenizers).
149346*/
149347static int queryTestTokenizer(
149348  sqlite3 *db,
149349  const char *zName,
149350  const sqlite3_tokenizer_module **pp
149351){
149352  int rc;
149353  sqlite3_stmt *pStmt;
149354  const char zSql[] = "SELECT fts3_tokenizer(?)";
149355
149356  *pp = 0;
149357  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
149358  if( rc!=SQLITE_OK ){
149359    return rc;
149360  }
149361
149362  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
149363  if( SQLITE_ROW==sqlite3_step(pStmt) ){
149364    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
149365      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
149366    }
149367  }
149368
149369  return sqlite3_finalize(pStmt);
149370}
149371
149372/*
149373** Return a pointer to a buffer containing a text representation of the
149374** expression passed as the first argument. The buffer is obtained from
149375** sqlite3_malloc(). It is the responsibility of the caller to use
149376** sqlite3_free() to release the memory. If an OOM condition is encountered,
149377** NULL is returned.
149378**
149379** If the second argument is not NULL, then its contents are prepended to
149380** the returned expression text and then freed using sqlite3_free().
149381*/
149382static char *exprToString(Fts3Expr *pExpr, char *zBuf){
149383  if( pExpr==0 ){
149384    return sqlite3_mprintf("");
149385  }
149386  switch( pExpr->eType ){
149387    case FTSQUERY_PHRASE: {
149388      Fts3Phrase *pPhrase = pExpr->pPhrase;
149389      int i;
149390      zBuf = sqlite3_mprintf(
149391          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
149392      for(i=0; zBuf && i<pPhrase->nToken; i++){
149393        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
149394            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
149395            (pPhrase->aToken[i].isPrefix?"+":"")
149396        );
149397      }
149398      return zBuf;
149399    }
149400
149401    case FTSQUERY_NEAR:
149402      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
149403      break;
149404    case FTSQUERY_NOT:
149405      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
149406      break;
149407    case FTSQUERY_AND:
149408      zBuf = sqlite3_mprintf("%zAND ", zBuf);
149409      break;
149410    case FTSQUERY_OR:
149411      zBuf = sqlite3_mprintf("%zOR ", zBuf);
149412      break;
149413  }
149414
149415  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
149416  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
149417  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
149418
149419  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
149420  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
149421
149422  return zBuf;
149423}
149424
149425/*
149426** This is the implementation of a scalar SQL function used to test the
149427** expression parser. It should be called as follows:
149428**
149429**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
149430**
149431** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
149432** to parse the query expression (see README.tokenizers). The second argument
149433** is the query expression to parse. Each subsequent argument is the name
149434** of a column of the fts3 table that the query expression may refer to.
149435** For example:
149436**
149437**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
149438*/
149439static void fts3ExprTest(
149440  sqlite3_context *context,
149441  int argc,
149442  sqlite3_value **argv
149443){
149444  sqlite3_tokenizer_module const *pModule = 0;
149445  sqlite3_tokenizer *pTokenizer = 0;
149446  int rc;
149447  char **azCol = 0;
149448  const char *zExpr;
149449  int nExpr;
149450  int nCol;
149451  int ii;
149452  Fts3Expr *pExpr;
149453  char *zBuf = 0;
149454  sqlite3 *db = sqlite3_context_db_handle(context);
149455
149456  if( argc<3 ){
149457    sqlite3_result_error(context,
149458        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
149459    );
149460    return;
149461  }
149462
149463  rc = queryTestTokenizer(db,
149464                          (const char *)sqlite3_value_text(argv[0]), &pModule);
149465  if( rc==SQLITE_NOMEM ){
149466    sqlite3_result_error_nomem(context);
149467    goto exprtest_out;
149468  }else if( !pModule ){
149469    sqlite3_result_error(context, "No such tokenizer module", -1);
149470    goto exprtest_out;
149471  }
149472
149473  rc = pModule->xCreate(0, 0, &pTokenizer);
149474  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
149475  if( rc==SQLITE_NOMEM ){
149476    sqlite3_result_error_nomem(context);
149477    goto exprtest_out;
149478  }
149479  pTokenizer->pModule = pModule;
149480
149481  zExpr = (const char *)sqlite3_value_text(argv[1]);
149482  nExpr = sqlite3_value_bytes(argv[1]);
149483  nCol = argc-2;
149484  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
149485  if( !azCol ){
149486    sqlite3_result_error_nomem(context);
149487    goto exprtest_out;
149488  }
149489  for(ii=0; ii<nCol; ii++){
149490    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
149491  }
149492
149493  if( sqlite3_user_data(context) ){
149494    char *zDummy = 0;
149495    rc = sqlite3Fts3ExprParse(
149496        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
149497    );
149498    assert( rc==SQLITE_OK || pExpr==0 );
149499    sqlite3_free(zDummy);
149500  }else{
149501    rc = fts3ExprParseUnbalanced(
149502        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
149503    );
149504  }
149505
149506  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
149507    sqlite3Fts3ExprFree(pExpr);
149508    sqlite3_result_error(context, "Error parsing expression", -1);
149509  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
149510    sqlite3_result_error_nomem(context);
149511  }else{
149512    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
149513    sqlite3_free(zBuf);
149514  }
149515
149516  sqlite3Fts3ExprFree(pExpr);
149517
149518exprtest_out:
149519  if( pModule && pTokenizer ){
149520    rc = pModule->xDestroy(pTokenizer);
149521  }
149522  sqlite3_free(azCol);
149523}
149524
149525/*
149526** Register the query expression parser test function fts3_exprtest()
149527** with database connection db.
149528*/
149529SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
149530  int rc = sqlite3_create_function(
149531      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
149532  );
149533  if( rc==SQLITE_OK ){
149534    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
149535        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
149536    );
149537  }
149538  return rc;
149539}
149540
149541#endif
149542#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149543
149544/************** End of fts3_expr.c *******************************************/
149545/************** Begin file fts3_hash.c ***************************************/
149546/*
149547** 2001 September 22
149548**
149549** The author disclaims copyright to this source code.  In place of
149550** a legal notice, here is a blessing:
149551**
149552**    May you do good and not evil.
149553**    May you find forgiveness for yourself and forgive others.
149554**    May you share freely, never taking more than you give.
149555**
149556*************************************************************************
149557** This is the implementation of generic hash-tables used in SQLite.
149558** We've modified it slightly to serve as a standalone hash table
149559** implementation for the full-text indexing module.
149560*/
149561
149562/*
149563** The code in this file is only compiled if:
149564**
149565**     * The FTS3 module is being built as an extension
149566**       (in which case SQLITE_CORE is not defined), or
149567**
149568**     * The FTS3 module is being built into the core of
149569**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149570*/
149571/* #include "fts3Int.h" */
149572#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149573
149574/* #include <assert.h> */
149575/* #include <stdlib.h> */
149576/* #include <string.h> */
149577
149578/* #include "fts3_hash.h" */
149579
149580/*
149581** Malloc and Free functions
149582*/
149583static void *fts3HashMalloc(int n){
149584  void *p = sqlite3_malloc(n);
149585  if( p ){
149586    memset(p, 0, n);
149587  }
149588  return p;
149589}
149590static void fts3HashFree(void *p){
149591  sqlite3_free(p);
149592}
149593
149594/* Turn bulk memory into a hash table object by initializing the
149595** fields of the Hash structure.
149596**
149597** "pNew" is a pointer to the hash table that is to be initialized.
149598** keyClass is one of the constants
149599** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
149600** determines what kind of key the hash table will use.  "copyKey" is
149601** true if the hash table should make its own private copy of keys and
149602** false if it should just use the supplied pointer.
149603*/
149604SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
149605  assert( pNew!=0 );
149606  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
149607  pNew->keyClass = keyClass;
149608  pNew->copyKey = copyKey;
149609  pNew->first = 0;
149610  pNew->count = 0;
149611  pNew->htsize = 0;
149612  pNew->ht = 0;
149613}
149614
149615/* Remove all entries from a hash table.  Reclaim all memory.
149616** Call this routine to delete a hash table or to reset a hash table
149617** to the empty state.
149618*/
149619SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
149620  Fts3HashElem *elem;         /* For looping over all elements of the table */
149621
149622  assert( pH!=0 );
149623  elem = pH->first;
149624  pH->first = 0;
149625  fts3HashFree(pH->ht);
149626  pH->ht = 0;
149627  pH->htsize = 0;
149628  while( elem ){
149629    Fts3HashElem *next_elem = elem->next;
149630    if( pH->copyKey && elem->pKey ){
149631      fts3HashFree(elem->pKey);
149632    }
149633    fts3HashFree(elem);
149634    elem = next_elem;
149635  }
149636  pH->count = 0;
149637}
149638
149639/*
149640** Hash and comparison functions when the mode is FTS3_HASH_STRING
149641*/
149642static int fts3StrHash(const void *pKey, int nKey){
149643  const char *z = (const char *)pKey;
149644  unsigned h = 0;
149645  if( nKey<=0 ) nKey = (int) strlen(z);
149646  while( nKey > 0  ){
149647    h = (h<<3) ^ h ^ *z++;
149648    nKey--;
149649  }
149650  return (int)(h & 0x7fffffff);
149651}
149652static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
149653  if( n1!=n2 ) return 1;
149654  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
149655}
149656
149657/*
149658** Hash and comparison functions when the mode is FTS3_HASH_BINARY
149659*/
149660static int fts3BinHash(const void *pKey, int nKey){
149661  int h = 0;
149662  const char *z = (const char *)pKey;
149663  while( nKey-- > 0 ){
149664    h = (h<<3) ^ h ^ *(z++);
149665  }
149666  return h & 0x7fffffff;
149667}
149668static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
149669  if( n1!=n2 ) return 1;
149670  return memcmp(pKey1,pKey2,n1);
149671}
149672
149673/*
149674** Return a pointer to the appropriate hash function given the key class.
149675**
149676** The C syntax in this function definition may be unfamilar to some
149677** programmers, so we provide the following additional explanation:
149678**
149679** The name of the function is "ftsHashFunction".  The function takes a
149680** single parameter "keyClass".  The return value of ftsHashFunction()
149681** is a pointer to another function.  Specifically, the return value
149682** of ftsHashFunction() is a pointer to a function that takes two parameters
149683** with types "const void*" and "int" and returns an "int".
149684*/
149685static int (*ftsHashFunction(int keyClass))(const void*,int){
149686  if( keyClass==FTS3_HASH_STRING ){
149687    return &fts3StrHash;
149688  }else{
149689    assert( keyClass==FTS3_HASH_BINARY );
149690    return &fts3BinHash;
149691  }
149692}
149693
149694/*
149695** Return a pointer to the appropriate hash function given the key class.
149696**
149697** For help in interpreted the obscure C code in the function definition,
149698** see the header comment on the previous function.
149699*/
149700static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
149701  if( keyClass==FTS3_HASH_STRING ){
149702    return &fts3StrCompare;
149703  }else{
149704    assert( keyClass==FTS3_HASH_BINARY );
149705    return &fts3BinCompare;
149706  }
149707}
149708
149709/* Link an element into the hash table
149710*/
149711static void fts3HashInsertElement(
149712  Fts3Hash *pH,            /* The complete hash table */
149713  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
149714  Fts3HashElem *pNew       /* The element to be inserted */
149715){
149716  Fts3HashElem *pHead;     /* First element already in pEntry */
149717  pHead = pEntry->chain;
149718  if( pHead ){
149719    pNew->next = pHead;
149720    pNew->prev = pHead->prev;
149721    if( pHead->prev ){ pHead->prev->next = pNew; }
149722    else             { pH->first = pNew; }
149723    pHead->prev = pNew;
149724  }else{
149725    pNew->next = pH->first;
149726    if( pH->first ){ pH->first->prev = pNew; }
149727    pNew->prev = 0;
149728    pH->first = pNew;
149729  }
149730  pEntry->count++;
149731  pEntry->chain = pNew;
149732}
149733
149734
149735/* Resize the hash table so that it cantains "new_size" buckets.
149736** "new_size" must be a power of 2.  The hash table might fail
149737** to resize if sqliteMalloc() fails.
149738**
149739** Return non-zero if a memory allocation error occurs.
149740*/
149741static int fts3Rehash(Fts3Hash *pH, int new_size){
149742  struct _fts3ht *new_ht;          /* The new hash table */
149743  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
149744  int (*xHash)(const void*,int);   /* The hash function */
149745
149746  assert( (new_size & (new_size-1))==0 );
149747  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
149748  if( new_ht==0 ) return 1;
149749  fts3HashFree(pH->ht);
149750  pH->ht = new_ht;
149751  pH->htsize = new_size;
149752  xHash = ftsHashFunction(pH->keyClass);
149753  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
149754    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
149755    next_elem = elem->next;
149756    fts3HashInsertElement(pH, &new_ht[h], elem);
149757  }
149758  return 0;
149759}
149760
149761/* This function (for internal use only) locates an element in an
149762** hash table that matches the given key.  The hash for this key has
149763** already been computed and is passed as the 4th parameter.
149764*/
149765static Fts3HashElem *fts3FindElementByHash(
149766  const Fts3Hash *pH, /* The pH to be searched */
149767  const void *pKey,   /* The key we are searching for */
149768  int nKey,
149769  int h               /* The hash for this key. */
149770){
149771  Fts3HashElem *elem;            /* Used to loop thru the element list */
149772  int count;                     /* Number of elements left to test */
149773  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
149774
149775  if( pH->ht ){
149776    struct _fts3ht *pEntry = &pH->ht[h];
149777    elem = pEntry->chain;
149778    count = pEntry->count;
149779    xCompare = ftsCompareFunction(pH->keyClass);
149780    while( count-- && elem ){
149781      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
149782        return elem;
149783      }
149784      elem = elem->next;
149785    }
149786  }
149787  return 0;
149788}
149789
149790/* Remove a single entry from the hash table given a pointer to that
149791** element and a hash on the element's key.
149792*/
149793static void fts3RemoveElementByHash(
149794  Fts3Hash *pH,         /* The pH containing "elem" */
149795  Fts3HashElem* elem,   /* The element to be removed from the pH */
149796  int h                 /* Hash value for the element */
149797){
149798  struct _fts3ht *pEntry;
149799  if( elem->prev ){
149800    elem->prev->next = elem->next;
149801  }else{
149802    pH->first = elem->next;
149803  }
149804  if( elem->next ){
149805    elem->next->prev = elem->prev;
149806  }
149807  pEntry = &pH->ht[h];
149808  if( pEntry->chain==elem ){
149809    pEntry->chain = elem->next;
149810  }
149811  pEntry->count--;
149812  if( pEntry->count<=0 ){
149813    pEntry->chain = 0;
149814  }
149815  if( pH->copyKey && elem->pKey ){
149816    fts3HashFree(elem->pKey);
149817  }
149818  fts3HashFree( elem );
149819  pH->count--;
149820  if( pH->count<=0 ){
149821    assert( pH->first==0 );
149822    assert( pH->count==0 );
149823    fts3HashClear(pH);
149824  }
149825}
149826
149827SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
149828  const Fts3Hash *pH,
149829  const void *pKey,
149830  int nKey
149831){
149832  int h;                          /* A hash on key */
149833  int (*xHash)(const void*,int);  /* The hash function */
149834
149835  if( pH==0 || pH->ht==0 ) return 0;
149836  xHash = ftsHashFunction(pH->keyClass);
149837  assert( xHash!=0 );
149838  h = (*xHash)(pKey,nKey);
149839  assert( (pH->htsize & (pH->htsize-1))==0 );
149840  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
149841}
149842
149843/*
149844** Attempt to locate an element of the hash table pH with a key
149845** that matches pKey,nKey.  Return the data for this element if it is
149846** found, or NULL if there is no match.
149847*/
149848SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
149849  Fts3HashElem *pElem;            /* The element that matches key (if any) */
149850
149851  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
149852  return pElem ? pElem->data : 0;
149853}
149854
149855/* Insert an element into the hash table pH.  The key is pKey,nKey
149856** and the data is "data".
149857**
149858** If no element exists with a matching key, then a new
149859** element is created.  A copy of the key is made if the copyKey
149860** flag is set.  NULL is returned.
149861**
149862** If another element already exists with the same key, then the
149863** new data replaces the old data and the old data is returned.
149864** The key is not copied in this instance.  If a malloc fails, then
149865** the new data is returned and the hash table is unchanged.
149866**
149867** If the "data" parameter to this function is NULL, then the
149868** element corresponding to "key" is removed from the hash table.
149869*/
149870SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
149871  Fts3Hash *pH,        /* The hash table to insert into */
149872  const void *pKey,    /* The key */
149873  int nKey,            /* Number of bytes in the key */
149874  void *data           /* The data */
149875){
149876  int hraw;                 /* Raw hash value of the key */
149877  int h;                    /* the hash of the key modulo hash table size */
149878  Fts3HashElem *elem;       /* Used to loop thru the element list */
149879  Fts3HashElem *new_elem;   /* New element added to the pH */
149880  int (*xHash)(const void*,int);  /* The hash function */
149881
149882  assert( pH!=0 );
149883  xHash = ftsHashFunction(pH->keyClass);
149884  assert( xHash!=0 );
149885  hraw = (*xHash)(pKey, nKey);
149886  assert( (pH->htsize & (pH->htsize-1))==0 );
149887  h = hraw & (pH->htsize-1);
149888  elem = fts3FindElementByHash(pH,pKey,nKey,h);
149889  if( elem ){
149890    void *old_data = elem->data;
149891    if( data==0 ){
149892      fts3RemoveElementByHash(pH,elem,h);
149893    }else{
149894      elem->data = data;
149895    }
149896    return old_data;
149897  }
149898  if( data==0 ) return 0;
149899  if( (pH->htsize==0 && fts3Rehash(pH,8))
149900   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
149901  ){
149902    pH->count = 0;
149903    return data;
149904  }
149905  assert( pH->htsize>0 );
149906  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
149907  if( new_elem==0 ) return data;
149908  if( pH->copyKey && pKey!=0 ){
149909    new_elem->pKey = fts3HashMalloc( nKey );
149910    if( new_elem->pKey==0 ){
149911      fts3HashFree(new_elem);
149912      return data;
149913    }
149914    memcpy((void*)new_elem->pKey, pKey, nKey);
149915  }else{
149916    new_elem->pKey = (void*)pKey;
149917  }
149918  new_elem->nKey = nKey;
149919  pH->count++;
149920  assert( pH->htsize>0 );
149921  assert( (pH->htsize & (pH->htsize-1))==0 );
149922  h = hraw & (pH->htsize-1);
149923  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
149924  new_elem->data = data;
149925  return 0;
149926}
149927
149928#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149929
149930/************** End of fts3_hash.c *******************************************/
149931/************** Begin file fts3_porter.c *************************************/
149932/*
149933** 2006 September 30
149934**
149935** The author disclaims copyright to this source code.  In place of
149936** a legal notice, here is a blessing:
149937**
149938**    May you do good and not evil.
149939**    May you find forgiveness for yourself and forgive others.
149940**    May you share freely, never taking more than you give.
149941**
149942*************************************************************************
149943** Implementation of the full-text-search tokenizer that implements
149944** a Porter stemmer.
149945*/
149946
149947/*
149948** The code in this file is only compiled if:
149949**
149950**     * The FTS3 module is being built as an extension
149951**       (in which case SQLITE_CORE is not defined), or
149952**
149953**     * The FTS3 module is being built into the core of
149954**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149955*/
149956/* #include "fts3Int.h" */
149957#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149958
149959/* #include <assert.h> */
149960/* #include <stdlib.h> */
149961/* #include <stdio.h> */
149962/* #include <string.h> */
149963
149964/* #include "fts3_tokenizer.h" */
149965
149966/*
149967** Class derived from sqlite3_tokenizer
149968*/
149969typedef struct porter_tokenizer {
149970  sqlite3_tokenizer base;      /* Base class */
149971} porter_tokenizer;
149972
149973/*
149974** Class derived from sqlite3_tokenizer_cursor
149975*/
149976typedef struct porter_tokenizer_cursor {
149977  sqlite3_tokenizer_cursor base;
149978  const char *zInput;          /* input we are tokenizing */
149979  int nInput;                  /* size of the input */
149980  int iOffset;                 /* current position in zInput */
149981  int iToken;                  /* index of next token to be returned */
149982  char *zToken;                /* storage for current token */
149983  int nAllocated;              /* space allocated to zToken buffer */
149984} porter_tokenizer_cursor;
149985
149986
149987/*
149988** Create a new tokenizer instance.
149989*/
149990static int porterCreate(
149991  int argc, const char * const *argv,
149992  sqlite3_tokenizer **ppTokenizer
149993){
149994  porter_tokenizer *t;
149995
149996  UNUSED_PARAMETER(argc);
149997  UNUSED_PARAMETER(argv);
149998
149999  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
150000  if( t==NULL ) return SQLITE_NOMEM;
150001  memset(t, 0, sizeof(*t));
150002  *ppTokenizer = &t->base;
150003  return SQLITE_OK;
150004}
150005
150006/*
150007** Destroy a tokenizer
150008*/
150009static int porterDestroy(sqlite3_tokenizer *pTokenizer){
150010  sqlite3_free(pTokenizer);
150011  return SQLITE_OK;
150012}
150013
150014/*
150015** Prepare to begin tokenizing a particular string.  The input
150016** string to be tokenized is zInput[0..nInput-1].  A cursor
150017** used to incrementally tokenize this string is returned in
150018** *ppCursor.
150019*/
150020static int porterOpen(
150021  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
150022  const char *zInput, int nInput,        /* String to be tokenized */
150023  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
150024){
150025  porter_tokenizer_cursor *c;
150026
150027  UNUSED_PARAMETER(pTokenizer);
150028
150029  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
150030  if( c==NULL ) return SQLITE_NOMEM;
150031
150032  c->zInput = zInput;
150033  if( zInput==0 ){
150034    c->nInput = 0;
150035  }else if( nInput<0 ){
150036    c->nInput = (int)strlen(zInput);
150037  }else{
150038    c->nInput = nInput;
150039  }
150040  c->iOffset = 0;                 /* start tokenizing at the beginning */
150041  c->iToken = 0;
150042  c->zToken = NULL;               /* no space allocated, yet. */
150043  c->nAllocated = 0;
150044
150045  *ppCursor = &c->base;
150046  return SQLITE_OK;
150047}
150048
150049/*
150050** Close a tokenization cursor previously opened by a call to
150051** porterOpen() above.
150052*/
150053static int porterClose(sqlite3_tokenizer_cursor *pCursor){
150054  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
150055  sqlite3_free(c->zToken);
150056  sqlite3_free(c);
150057  return SQLITE_OK;
150058}
150059/*
150060** Vowel or consonant
150061*/
150062static const char cType[] = {
150063   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
150064   1, 1, 1, 2, 1
150065};
150066
150067/*
150068** isConsonant() and isVowel() determine if their first character in
150069** the string they point to is a consonant or a vowel, according
150070** to Porter ruls.
150071**
150072** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
150073** 'Y' is a consonant unless it follows another consonant,
150074** in which case it is a vowel.
150075**
150076** In these routine, the letters are in reverse order.  So the 'y' rule
150077** is that 'y' is a consonant unless it is followed by another
150078** consonent.
150079*/
150080static int isVowel(const char*);
150081static int isConsonant(const char *z){
150082  int j;
150083  char x = *z;
150084  if( x==0 ) return 0;
150085  assert( x>='a' && x<='z' );
150086  j = cType[x-'a'];
150087  if( j<2 ) return j;
150088  return z[1]==0 || isVowel(z + 1);
150089}
150090static int isVowel(const char *z){
150091  int j;
150092  char x = *z;
150093  if( x==0 ) return 0;
150094  assert( x>='a' && x<='z' );
150095  j = cType[x-'a'];
150096  if( j<2 ) return 1-j;
150097  return isConsonant(z + 1);
150098}
150099
150100/*
150101** Let any sequence of one or more vowels be represented by V and let
150102** C be sequence of one or more consonants.  Then every word can be
150103** represented as:
150104**
150105**           [C] (VC){m} [V]
150106**
150107** In prose:  A word is an optional consonant followed by zero or
150108** vowel-consonant pairs followed by an optional vowel.  "m" is the
150109** number of vowel consonant pairs.  This routine computes the value
150110** of m for the first i bytes of a word.
150111**
150112** Return true if the m-value for z is 1 or more.  In other words,
150113** return true if z contains at least one vowel that is followed
150114** by a consonant.
150115**
150116** In this routine z[] is in reverse order.  So we are really looking
150117** for an instance of a consonant followed by a vowel.
150118*/
150119static int m_gt_0(const char *z){
150120  while( isVowel(z) ){ z++; }
150121  if( *z==0 ) return 0;
150122  while( isConsonant(z) ){ z++; }
150123  return *z!=0;
150124}
150125
150126/* Like mgt0 above except we are looking for a value of m which is
150127** exactly 1
150128*/
150129static int m_eq_1(const char *z){
150130  while( isVowel(z) ){ z++; }
150131  if( *z==0 ) return 0;
150132  while( isConsonant(z) ){ z++; }
150133  if( *z==0 ) return 0;
150134  while( isVowel(z) ){ z++; }
150135  if( *z==0 ) return 1;
150136  while( isConsonant(z) ){ z++; }
150137  return *z==0;
150138}
150139
150140/* Like mgt0 above except we are looking for a value of m>1 instead
150141** or m>0
150142*/
150143static int m_gt_1(const char *z){
150144  while( isVowel(z) ){ z++; }
150145  if( *z==0 ) return 0;
150146  while( isConsonant(z) ){ z++; }
150147  if( *z==0 ) return 0;
150148  while( isVowel(z) ){ z++; }
150149  if( *z==0 ) return 0;
150150  while( isConsonant(z) ){ z++; }
150151  return *z!=0;
150152}
150153
150154/*
150155** Return TRUE if there is a vowel anywhere within z[0..n-1]
150156*/
150157static int hasVowel(const char *z){
150158  while( isConsonant(z) ){ z++; }
150159  return *z!=0;
150160}
150161
150162/*
150163** Return TRUE if the word ends in a double consonant.
150164**
150165** The text is reversed here. So we are really looking at
150166** the first two characters of z[].
150167*/
150168static int doubleConsonant(const char *z){
150169  return isConsonant(z) && z[0]==z[1];
150170}
150171
150172/*
150173** Return TRUE if the word ends with three letters which
150174** are consonant-vowel-consonent and where the final consonant
150175** is not 'w', 'x', or 'y'.
150176**
150177** The word is reversed here.  So we are really checking the
150178** first three letters and the first one cannot be in [wxy].
150179*/
150180static int star_oh(const char *z){
150181  return
150182    isConsonant(z) &&
150183    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
150184    isVowel(z+1) &&
150185    isConsonant(z+2);
150186}
150187
150188/*
150189** If the word ends with zFrom and xCond() is true for the stem
150190** of the word that preceeds the zFrom ending, then change the
150191** ending to zTo.
150192**
150193** The input word *pz and zFrom are both in reverse order.  zTo
150194** is in normal order.
150195**
150196** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
150197** match.  Not that TRUE is returned even if xCond() fails and
150198** no substitution occurs.
150199*/
150200static int stem(
150201  char **pz,             /* The word being stemmed (Reversed) */
150202  const char *zFrom,     /* If the ending matches this... (Reversed) */
150203  const char *zTo,       /* ... change the ending to this (not reversed) */
150204  int (*xCond)(const char*)   /* Condition that must be true */
150205){
150206  char *z = *pz;
150207  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
150208  if( *zFrom!=0 ) return 0;
150209  if( xCond && !xCond(z) ) return 1;
150210  while( *zTo ){
150211    *(--z) = *(zTo++);
150212  }
150213  *pz = z;
150214  return 1;
150215}
150216
150217/*
150218** This is the fallback stemmer used when the porter stemmer is
150219** inappropriate.  The input word is copied into the output with
150220** US-ASCII case folding.  If the input word is too long (more
150221** than 20 bytes if it contains no digits or more than 6 bytes if
150222** it contains digits) then word is truncated to 20 or 6 bytes
150223** by taking 10 or 3 bytes from the beginning and end.
150224*/
150225static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
150226  int i, mx, j;
150227  int hasDigit = 0;
150228  for(i=0; i<nIn; i++){
150229    char c = zIn[i];
150230    if( c>='A' && c<='Z' ){
150231      zOut[i] = c - 'A' + 'a';
150232    }else{
150233      if( c>='0' && c<='9' ) hasDigit = 1;
150234      zOut[i] = c;
150235    }
150236  }
150237  mx = hasDigit ? 3 : 10;
150238  if( nIn>mx*2 ){
150239    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
150240      zOut[j] = zOut[i];
150241    }
150242    i = j;
150243  }
150244  zOut[i] = 0;
150245  *pnOut = i;
150246}
150247
150248
150249/*
150250** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
150251** zOut is at least big enough to hold nIn bytes.  Write the actual
150252** size of the output word (exclusive of the '\0' terminator) into *pnOut.
150253**
150254** Any upper-case characters in the US-ASCII character set ([A-Z])
150255** are converted to lower case.  Upper-case UTF characters are
150256** unchanged.
150257**
150258** Words that are longer than about 20 bytes are stemmed by retaining
150259** a few bytes from the beginning and the end of the word.  If the
150260** word contains digits, 3 bytes are taken from the beginning and
150261** 3 bytes from the end.  For long words without digits, 10 bytes
150262** are taken from each end.  US-ASCII case folding still applies.
150263**
150264** If the input word contains not digits but does characters not
150265** in [a-zA-Z] then no stemming is attempted and this routine just
150266** copies the input into the input into the output with US-ASCII
150267** case folding.
150268**
150269** Stemming never increases the length of the word.  So there is
150270** no chance of overflowing the zOut buffer.
150271*/
150272static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
150273  int i, j;
150274  char zReverse[28];
150275  char *z, *z2;
150276  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
150277    /* The word is too big or too small for the porter stemmer.
150278    ** Fallback to the copy stemmer */
150279    copy_stemmer(zIn, nIn, zOut, pnOut);
150280    return;
150281  }
150282  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
150283    char c = zIn[i];
150284    if( c>='A' && c<='Z' ){
150285      zReverse[j] = c + 'a' - 'A';
150286    }else if( c>='a' && c<='z' ){
150287      zReverse[j] = c;
150288    }else{
150289      /* The use of a character not in [a-zA-Z] means that we fallback
150290      ** to the copy stemmer */
150291      copy_stemmer(zIn, nIn, zOut, pnOut);
150292      return;
150293    }
150294  }
150295  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
150296  z = &zReverse[j+1];
150297
150298
150299  /* Step 1a */
150300  if( z[0]=='s' ){
150301    if(
150302     !stem(&z, "sess", "ss", 0) &&
150303     !stem(&z, "sei", "i", 0)  &&
150304     !stem(&z, "ss", "ss", 0)
150305    ){
150306      z++;
150307    }
150308  }
150309
150310  /* Step 1b */
150311  z2 = z;
150312  if( stem(&z, "dee", "ee", m_gt_0) ){
150313    /* Do nothing.  The work was all in the test */
150314  }else if(
150315     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
150316      && z!=z2
150317  ){
150318     if( stem(&z, "ta", "ate", 0) ||
150319         stem(&z, "lb", "ble", 0) ||
150320         stem(&z, "zi", "ize", 0) ){
150321       /* Do nothing.  The work was all in the test */
150322     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
150323       z++;
150324     }else if( m_eq_1(z) && star_oh(z) ){
150325       *(--z) = 'e';
150326     }
150327  }
150328
150329  /* Step 1c */
150330  if( z[0]=='y' && hasVowel(z+1) ){
150331    z[0] = 'i';
150332  }
150333
150334  /* Step 2 */
150335  switch( z[1] ){
150336   case 'a':
150337     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
150338       stem(&z, "lanoit", "tion", m_gt_0);
150339     }
150340     break;
150341   case 'c':
150342     if( !stem(&z, "icne", "ence", m_gt_0) ){
150343       stem(&z, "icna", "ance", m_gt_0);
150344     }
150345     break;
150346   case 'e':
150347     stem(&z, "rezi", "ize", m_gt_0);
150348     break;
150349   case 'g':
150350     stem(&z, "igol", "log", m_gt_0);
150351     break;
150352   case 'l':
150353     if( !stem(&z, "ilb", "ble", m_gt_0)
150354      && !stem(&z, "illa", "al", m_gt_0)
150355      && !stem(&z, "iltne", "ent", m_gt_0)
150356      && !stem(&z, "ile", "e", m_gt_0)
150357     ){
150358       stem(&z, "ilsuo", "ous", m_gt_0);
150359     }
150360     break;
150361   case 'o':
150362     if( !stem(&z, "noitazi", "ize", m_gt_0)
150363      && !stem(&z, "noita", "ate", m_gt_0)
150364     ){
150365       stem(&z, "rota", "ate", m_gt_0);
150366     }
150367     break;
150368   case 's':
150369     if( !stem(&z, "msila", "al", m_gt_0)
150370      && !stem(&z, "ssenevi", "ive", m_gt_0)
150371      && !stem(&z, "ssenluf", "ful", m_gt_0)
150372     ){
150373       stem(&z, "ssensuo", "ous", m_gt_0);
150374     }
150375     break;
150376   case 't':
150377     if( !stem(&z, "itila", "al", m_gt_0)
150378      && !stem(&z, "itivi", "ive", m_gt_0)
150379     ){
150380       stem(&z, "itilib", "ble", m_gt_0);
150381     }
150382     break;
150383  }
150384
150385  /* Step 3 */
150386  switch( z[0] ){
150387   case 'e':
150388     if( !stem(&z, "etaci", "ic", m_gt_0)
150389      && !stem(&z, "evita", "", m_gt_0)
150390     ){
150391       stem(&z, "ezila", "al", m_gt_0);
150392     }
150393     break;
150394   case 'i':
150395     stem(&z, "itici", "ic", m_gt_0);
150396     break;
150397   case 'l':
150398     if( !stem(&z, "laci", "ic", m_gt_0) ){
150399       stem(&z, "luf", "", m_gt_0);
150400     }
150401     break;
150402   case 's':
150403     stem(&z, "ssen", "", m_gt_0);
150404     break;
150405  }
150406
150407  /* Step 4 */
150408  switch( z[1] ){
150409   case 'a':
150410     if( z[0]=='l' && m_gt_1(z+2) ){
150411       z += 2;
150412     }
150413     break;
150414   case 'c':
150415     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
150416       z += 4;
150417     }
150418     break;
150419   case 'e':
150420     if( z[0]=='r' && m_gt_1(z+2) ){
150421       z += 2;
150422     }
150423     break;
150424   case 'i':
150425     if( z[0]=='c' && m_gt_1(z+2) ){
150426       z += 2;
150427     }
150428     break;
150429   case 'l':
150430     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
150431       z += 4;
150432     }
150433     break;
150434   case 'n':
150435     if( z[0]=='t' ){
150436       if( z[2]=='a' ){
150437         if( m_gt_1(z+3) ){
150438           z += 3;
150439         }
150440       }else if( z[2]=='e' ){
150441         if( !stem(&z, "tneme", "", m_gt_1)
150442          && !stem(&z, "tnem", "", m_gt_1)
150443         ){
150444           stem(&z, "tne", "", m_gt_1);
150445         }
150446       }
150447     }
150448     break;
150449   case 'o':
150450     if( z[0]=='u' ){
150451       if( m_gt_1(z+2) ){
150452         z += 2;
150453       }
150454     }else if( z[3]=='s' || z[3]=='t' ){
150455       stem(&z, "noi", "", m_gt_1);
150456     }
150457     break;
150458   case 's':
150459     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
150460       z += 3;
150461     }
150462     break;
150463   case 't':
150464     if( !stem(&z, "eta", "", m_gt_1) ){
150465       stem(&z, "iti", "", m_gt_1);
150466     }
150467     break;
150468   case 'u':
150469     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
150470       z += 3;
150471     }
150472     break;
150473   case 'v':
150474   case 'z':
150475     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
150476       z += 3;
150477     }
150478     break;
150479  }
150480
150481  /* Step 5a */
150482  if( z[0]=='e' ){
150483    if( m_gt_1(z+1) ){
150484      z++;
150485    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
150486      z++;
150487    }
150488  }
150489
150490  /* Step 5b */
150491  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
150492    z++;
150493  }
150494
150495  /* z[] is now the stemmed word in reverse order.  Flip it back
150496  ** around into forward order and return.
150497  */
150498  *pnOut = i = (int)strlen(z);
150499  zOut[i] = 0;
150500  while( *z ){
150501    zOut[--i] = *(z++);
150502  }
150503}
150504
150505/*
150506** Characters that can be part of a token.  We assume any character
150507** whose value is greater than 0x80 (any UTF character) can be
150508** part of a token.  In other words, delimiters all must have
150509** values of 0x7f or lower.
150510*/
150511static const char porterIdChar[] = {
150512/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
150513    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
150514    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
150515    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
150516    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
150517    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
150518};
150519#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
150520
150521/*
150522** Extract the next token from a tokenization cursor.  The cursor must
150523** have been opened by a prior call to porterOpen().
150524*/
150525static int porterNext(
150526  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
150527  const char **pzToken,               /* OUT: *pzToken is the token text */
150528  int *pnBytes,                       /* OUT: Number of bytes in token */
150529  int *piStartOffset,                 /* OUT: Starting offset of token */
150530  int *piEndOffset,                   /* OUT: Ending offset of token */
150531  int *piPosition                     /* OUT: Position integer of token */
150532){
150533  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
150534  const char *z = c->zInput;
150535
150536  while( c->iOffset<c->nInput ){
150537    int iStartOffset, ch;
150538
150539    /* Scan past delimiter characters */
150540    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
150541      c->iOffset++;
150542    }
150543
150544    /* Count non-delimiter characters. */
150545    iStartOffset = c->iOffset;
150546    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
150547      c->iOffset++;
150548    }
150549
150550    if( c->iOffset>iStartOffset ){
150551      int n = c->iOffset-iStartOffset;
150552      if( n>c->nAllocated ){
150553        char *pNew;
150554        c->nAllocated = n+20;
150555        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
150556        if( !pNew ) return SQLITE_NOMEM;
150557        c->zToken = pNew;
150558      }
150559      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
150560      *pzToken = c->zToken;
150561      *piStartOffset = iStartOffset;
150562      *piEndOffset = c->iOffset;
150563      *piPosition = c->iToken++;
150564      return SQLITE_OK;
150565    }
150566  }
150567  return SQLITE_DONE;
150568}
150569
150570/*
150571** The set of routines that implement the porter-stemmer tokenizer
150572*/
150573static const sqlite3_tokenizer_module porterTokenizerModule = {
150574  0,
150575  porterCreate,
150576  porterDestroy,
150577  porterOpen,
150578  porterClose,
150579  porterNext,
150580  0
150581};
150582
150583/*
150584** Allocate a new porter tokenizer.  Return a pointer to the new
150585** tokenizer in *ppModule
150586*/
150587SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
150588  sqlite3_tokenizer_module const**ppModule
150589){
150590  *ppModule = &porterTokenizerModule;
150591}
150592
150593#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150594
150595/************** End of fts3_porter.c *****************************************/
150596/************** Begin file fts3_tokenizer.c **********************************/
150597/*
150598** 2007 June 22
150599**
150600** The author disclaims copyright to this source code.  In place of
150601** a legal notice, here is a blessing:
150602**
150603**    May you do good and not evil.
150604**    May you find forgiveness for yourself and forgive others.
150605**    May you share freely, never taking more than you give.
150606**
150607******************************************************************************
150608**
150609** This is part of an SQLite module implementing full-text search.
150610** This particular file implements the generic tokenizer interface.
150611*/
150612
150613/*
150614** The code in this file is only compiled if:
150615**
150616**     * The FTS3 module is being built as an extension
150617**       (in which case SQLITE_CORE is not defined), or
150618**
150619**     * The FTS3 module is being built into the core of
150620**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
150621*/
150622/* #include "fts3Int.h" */
150623#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150624
150625/* #include <assert.h> */
150626/* #include <string.h> */
150627
150628/*
150629** Return true if the two-argument version of fts3_tokenizer()
150630** has been activated via a prior call to sqlite3_db_config(db,
150631** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
150632*/
150633static int fts3TokenizerEnabled(sqlite3_context *context){
150634  sqlite3 *db = sqlite3_context_db_handle(context);
150635  int isEnabled = 0;
150636  sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
150637  return isEnabled;
150638}
150639
150640/*
150641** Implementation of the SQL scalar function for accessing the underlying
150642** hash table. This function may be called as follows:
150643**
150644**   SELECT <function-name>(<key-name>);
150645**   SELECT <function-name>(<key-name>, <pointer>);
150646**
150647** where <function-name> is the name passed as the second argument
150648** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
150649**
150650** If the <pointer> argument is specified, it must be a blob value
150651** containing a pointer to be stored as the hash data corresponding
150652** to the string <key-name>. If <pointer> is not specified, then
150653** the string <key-name> must already exist in the has table. Otherwise,
150654** an error is returned.
150655**
150656** Whether or not the <pointer> argument is specified, the value returned
150657** is a blob containing the pointer stored as the hash data corresponding
150658** to string <key-name> (after the hash-table is updated, if applicable).
150659*/
150660static void fts3TokenizerFunc(
150661  sqlite3_context *context,
150662  int argc,
150663  sqlite3_value **argv
150664){
150665  Fts3Hash *pHash;
150666  void *pPtr = 0;
150667  const unsigned char *zName;
150668  int nName;
150669
150670  assert( argc==1 || argc==2 );
150671
150672  pHash = (Fts3Hash *)sqlite3_user_data(context);
150673
150674  zName = sqlite3_value_text(argv[0]);
150675  nName = sqlite3_value_bytes(argv[0])+1;
150676
150677  if( argc==2 ){
150678    if( fts3TokenizerEnabled(context) ){
150679      void *pOld;
150680      int n = sqlite3_value_bytes(argv[1]);
150681      if( zName==0 || n!=sizeof(pPtr) ){
150682        sqlite3_result_error(context, "argument type mismatch", -1);
150683        return;
150684      }
150685      pPtr = *(void **)sqlite3_value_blob(argv[1]);
150686      pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
150687      if( pOld==pPtr ){
150688        sqlite3_result_error(context, "out of memory", -1);
150689      }
150690    }else{
150691      sqlite3_result_error(context, "fts3tokenize disabled", -1);
150692      return;
150693    }
150694  }else{
150695    if( zName ){
150696      pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
150697    }
150698    if( !pPtr ){
150699      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
150700      sqlite3_result_error(context, zErr, -1);
150701      sqlite3_free(zErr);
150702      return;
150703    }
150704  }
150705  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
150706}
150707
150708SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
150709  static const char isFtsIdChar[] = {
150710      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
150711      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
150712      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
150713      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
150714      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
150715      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
150716      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
150717      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
150718  };
150719  return (c&0x80 || isFtsIdChar[(int)(c)]);
150720}
150721
150722SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
150723  const char *z1;
150724  const char *z2 = 0;
150725
150726  /* Find the start of the next token. */
150727  z1 = zStr;
150728  while( z2==0 ){
150729    char c = *z1;
150730    switch( c ){
150731      case '\0': return 0;        /* No more tokens here */
150732      case '\'':
150733      case '"':
150734      case '`': {
150735        z2 = z1;
150736        while( *++z2 && (*z2!=c || *++z2==c) );
150737        break;
150738      }
150739      case '[':
150740        z2 = &z1[1];
150741        while( *z2 && z2[0]!=']' ) z2++;
150742        if( *z2 ) z2++;
150743        break;
150744
150745      default:
150746        if( sqlite3Fts3IsIdChar(*z1) ){
150747          z2 = &z1[1];
150748          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
150749        }else{
150750          z1++;
150751        }
150752    }
150753  }
150754
150755  *pn = (int)(z2-z1);
150756  return z1;
150757}
150758
150759SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
150760  Fts3Hash *pHash,                /* Tokenizer hash table */
150761  const char *zArg,               /* Tokenizer name */
150762  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
150763  char **pzErr                    /* OUT: Set to malloced error message */
150764){
150765  int rc;
150766  char *z = (char *)zArg;
150767  int n = 0;
150768  char *zCopy;
150769  char *zEnd;                     /* Pointer to nul-term of zCopy */
150770  sqlite3_tokenizer_module *m;
150771
150772  zCopy = sqlite3_mprintf("%s", zArg);
150773  if( !zCopy ) return SQLITE_NOMEM;
150774  zEnd = &zCopy[strlen(zCopy)];
150775
150776  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
150777  if( z==0 ){
150778    assert( n==0 );
150779    z = zCopy;
150780  }
150781  z[n] = '\0';
150782  sqlite3Fts3Dequote(z);
150783
150784  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
150785  if( !m ){
150786    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
150787    rc = SQLITE_ERROR;
150788  }else{
150789    char const **aArg = 0;
150790    int iArg = 0;
150791    z = &z[n+1];
150792    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
150793      int nNew = sizeof(char *)*(iArg+1);
150794      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
150795      if( !aNew ){
150796        sqlite3_free(zCopy);
150797        sqlite3_free((void *)aArg);
150798        return SQLITE_NOMEM;
150799      }
150800      aArg = aNew;
150801      aArg[iArg++] = z;
150802      z[n] = '\0';
150803      sqlite3Fts3Dequote(z);
150804      z = &z[n+1];
150805    }
150806    rc = m->xCreate(iArg, aArg, ppTok);
150807    assert( rc!=SQLITE_OK || *ppTok );
150808    if( rc!=SQLITE_OK ){
150809      sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
150810    }else{
150811      (*ppTok)->pModule = m;
150812    }
150813    sqlite3_free((void *)aArg);
150814  }
150815
150816  sqlite3_free(zCopy);
150817  return rc;
150818}
150819
150820
150821#ifdef SQLITE_TEST
150822
150823#if defined(INCLUDE_SQLITE_TCL_H)
150824#  include "sqlite_tcl.h"
150825#else
150826#  include "tcl.h"
150827#endif
150828/* #include <string.h> */
150829
150830/*
150831** Implementation of a special SQL scalar function for testing tokenizers
150832** designed to be used in concert with the Tcl testing framework. This
150833** function must be called with two or more arguments:
150834**
150835**   SELECT <function-name>(<key-name>, ..., <input-string>);
150836**
150837** where <function-name> is the name passed as the second argument
150838** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
150839** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
150840**
150841** The return value is a string that may be interpreted as a Tcl
150842** list. For each token in the <input-string>, three elements are
150843** added to the returned list. The first is the token position, the
150844** second is the token text (folded, stemmed, etc.) and the third is the
150845** substring of <input-string> associated with the token. For example,
150846** using the built-in "simple" tokenizer:
150847**
150848**   SELECT fts_tokenizer_test('simple', 'I don't see how');
150849**
150850** will return the string:
150851**
150852**   "{0 i I 1 dont don't 2 see see 3 how how}"
150853**
150854*/
150855static void testFunc(
150856  sqlite3_context *context,
150857  int argc,
150858  sqlite3_value **argv
150859){
150860  Fts3Hash *pHash;
150861  sqlite3_tokenizer_module *p;
150862  sqlite3_tokenizer *pTokenizer = 0;
150863  sqlite3_tokenizer_cursor *pCsr = 0;
150864
150865  const char *zErr = 0;
150866
150867  const char *zName;
150868  int nName;
150869  const char *zInput;
150870  int nInput;
150871
150872  const char *azArg[64];
150873
150874  const char *zToken;
150875  int nToken = 0;
150876  int iStart = 0;
150877  int iEnd = 0;
150878  int iPos = 0;
150879  int i;
150880
150881  Tcl_Obj *pRet;
150882
150883  if( argc<2 ){
150884    sqlite3_result_error(context, "insufficient arguments", -1);
150885    return;
150886  }
150887
150888  nName = sqlite3_value_bytes(argv[0]);
150889  zName = (const char *)sqlite3_value_text(argv[0]);
150890  nInput = sqlite3_value_bytes(argv[argc-1]);
150891  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
150892
150893  pHash = (Fts3Hash *)sqlite3_user_data(context);
150894  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
150895
150896  if( !p ){
150897    char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
150898    sqlite3_result_error(context, zErr2, -1);
150899    sqlite3_free(zErr2);
150900    return;
150901  }
150902
150903  pRet = Tcl_NewObj();
150904  Tcl_IncrRefCount(pRet);
150905
150906  for(i=1; i<argc-1; i++){
150907    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
150908  }
150909
150910  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
150911    zErr = "error in xCreate()";
150912    goto finish;
150913  }
150914  pTokenizer->pModule = p;
150915  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
150916    zErr = "error in xOpen()";
150917    goto finish;
150918  }
150919
150920  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
150921    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
150922    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
150923    zToken = &zInput[iStart];
150924    nToken = iEnd-iStart;
150925    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
150926  }
150927
150928  if( SQLITE_OK!=p->xClose(pCsr) ){
150929    zErr = "error in xClose()";
150930    goto finish;
150931  }
150932  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
150933    zErr = "error in xDestroy()";
150934    goto finish;
150935  }
150936
150937finish:
150938  if( zErr ){
150939    sqlite3_result_error(context, zErr, -1);
150940  }else{
150941    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
150942  }
150943  Tcl_DecrRefCount(pRet);
150944}
150945
150946static
150947int registerTokenizer(
150948  sqlite3 *db,
150949  char *zName,
150950  const sqlite3_tokenizer_module *p
150951){
150952  int rc;
150953  sqlite3_stmt *pStmt;
150954  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
150955
150956  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150957  if( rc!=SQLITE_OK ){
150958    return rc;
150959  }
150960
150961  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150962  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
150963  sqlite3_step(pStmt);
150964
150965  return sqlite3_finalize(pStmt);
150966}
150967
150968
150969static
150970int queryTokenizer(
150971  sqlite3 *db,
150972  char *zName,
150973  const sqlite3_tokenizer_module **pp
150974){
150975  int rc;
150976  sqlite3_stmt *pStmt;
150977  const char zSql[] = "SELECT fts3_tokenizer(?)";
150978
150979  *pp = 0;
150980  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150981  if( rc!=SQLITE_OK ){
150982    return rc;
150983  }
150984
150985  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150986  if( SQLITE_ROW==sqlite3_step(pStmt) ){
150987    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
150988      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
150989    }
150990  }
150991
150992  return sqlite3_finalize(pStmt);
150993}
150994
150995SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
150996
150997/*
150998** Implementation of the scalar function fts3_tokenizer_internal_test().
150999** This function is used for testing only, it is not included in the
151000** build unless SQLITE_TEST is defined.
151001**
151002** The purpose of this is to test that the fts3_tokenizer() function
151003** can be used as designed by the C-code in the queryTokenizer and
151004** registerTokenizer() functions above. These two functions are repeated
151005** in the README.tokenizer file as an example, so it is important to
151006** test them.
151007**
151008** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
151009** function with no arguments. An assert() will fail if a problem is
151010** detected. i.e.:
151011**
151012**     SELECT fts3_tokenizer_internal_test();
151013**
151014*/
151015static void intTestFunc(
151016  sqlite3_context *context,
151017  int argc,
151018  sqlite3_value **argv
151019){
151020  int rc;
151021  const sqlite3_tokenizer_module *p1;
151022  const sqlite3_tokenizer_module *p2;
151023  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
151024
151025  UNUSED_PARAMETER(argc);
151026  UNUSED_PARAMETER(argv);
151027
151028  /* Test the query function */
151029  sqlite3Fts3SimpleTokenizerModule(&p1);
151030  rc = queryTokenizer(db, "simple", &p2);
151031  assert( rc==SQLITE_OK );
151032  assert( p1==p2 );
151033  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
151034  assert( rc==SQLITE_ERROR );
151035  assert( p2==0 );
151036  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
151037
151038  /* Test the storage function */
151039  if( fts3TokenizerEnabled(context) ){
151040    rc = registerTokenizer(db, "nosuchtokenizer", p1);
151041    assert( rc==SQLITE_OK );
151042    rc = queryTokenizer(db, "nosuchtokenizer", &p2);
151043    assert( rc==SQLITE_OK );
151044    assert( p2==p1 );
151045  }
151046
151047  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
151048}
151049
151050#endif
151051
151052/*
151053** Set up SQL objects in database db used to access the contents of
151054** the hash table pointed to by argument pHash. The hash table must
151055** been initialized to use string keys, and to take a private copy
151056** of the key when a value is inserted. i.e. by a call similar to:
151057**
151058**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
151059**
151060** This function adds a scalar function (see header comment above
151061** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
151062** defined at compilation time, a temporary virtual table (see header
151063** comment above struct HashTableVtab) to the database schema. Both
151064** provide read/write access to the contents of *pHash.
151065**
151066** The third argument to this function, zName, is used as the name
151067** of both the scalar and, if created, the virtual table.
151068*/
151069SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
151070  sqlite3 *db,
151071  Fts3Hash *pHash,
151072  const char *zName
151073){
151074  int rc = SQLITE_OK;
151075  void *p = (void *)pHash;
151076  const int any = SQLITE_ANY;
151077
151078#ifdef SQLITE_TEST
151079  char *zTest = 0;
151080  char *zTest2 = 0;
151081  void *pdb = (void *)db;
151082  zTest = sqlite3_mprintf("%s_test", zName);
151083  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
151084  if( !zTest || !zTest2 ){
151085    rc = SQLITE_NOMEM;
151086  }
151087#endif
151088
151089  if( SQLITE_OK==rc ){
151090    rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
151091  }
151092  if( SQLITE_OK==rc ){
151093    rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
151094  }
151095#ifdef SQLITE_TEST
151096  if( SQLITE_OK==rc ){
151097    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
151098  }
151099  if( SQLITE_OK==rc ){
151100    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
151101  }
151102#endif
151103
151104#ifdef SQLITE_TEST
151105  sqlite3_free(zTest);
151106  sqlite3_free(zTest2);
151107#endif
151108
151109  return rc;
151110}
151111
151112#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151113
151114/************** End of fts3_tokenizer.c **************************************/
151115/************** Begin file fts3_tokenizer1.c *********************************/
151116/*
151117** 2006 Oct 10
151118**
151119** The author disclaims copyright to this source code.  In place of
151120** a legal notice, here is a blessing:
151121**
151122**    May you do good and not evil.
151123**    May you find forgiveness for yourself and forgive others.
151124**    May you share freely, never taking more than you give.
151125**
151126******************************************************************************
151127**
151128** Implementation of the "simple" full-text-search tokenizer.
151129*/
151130
151131/*
151132** The code in this file is only compiled if:
151133**
151134**     * The FTS3 module is being built as an extension
151135**       (in which case SQLITE_CORE is not defined), or
151136**
151137**     * The FTS3 module is being built into the core of
151138**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151139*/
151140/* #include "fts3Int.h" */
151141#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151142
151143/* #include <assert.h> */
151144/* #include <stdlib.h> */
151145/* #include <stdio.h> */
151146/* #include <string.h> */
151147
151148/* #include "fts3_tokenizer.h" */
151149
151150typedef struct simple_tokenizer {
151151  sqlite3_tokenizer base;
151152  char delim[128];             /* flag ASCII delimiters */
151153} simple_tokenizer;
151154
151155typedef struct simple_tokenizer_cursor {
151156  sqlite3_tokenizer_cursor base;
151157  const char *pInput;          /* input we are tokenizing */
151158  int nBytes;                  /* size of the input */
151159  int iOffset;                 /* current position in pInput */
151160  int iToken;                  /* index of next token to be returned */
151161  char *pToken;                /* storage for current token */
151162  int nTokenAllocated;         /* space allocated to zToken buffer */
151163} simple_tokenizer_cursor;
151164
151165
151166static int simpleDelim(simple_tokenizer *t, unsigned char c){
151167  return c<0x80 && t->delim[c];
151168}
151169static int fts3_isalnum(int x){
151170  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
151171}
151172
151173/*
151174** Create a new tokenizer instance.
151175*/
151176static int simpleCreate(
151177  int argc, const char * const *argv,
151178  sqlite3_tokenizer **ppTokenizer
151179){
151180  simple_tokenizer *t;
151181
151182  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
151183  if( t==NULL ) return SQLITE_NOMEM;
151184  memset(t, 0, sizeof(*t));
151185
151186  /* TODO(shess) Delimiters need to remain the same from run to run,
151187  ** else we need to reindex.  One solution would be a meta-table to
151188  ** track such information in the database, then we'd only want this
151189  ** information on the initial create.
151190  */
151191  if( argc>1 ){
151192    int i, n = (int)strlen(argv[1]);
151193    for(i=0; i<n; i++){
151194      unsigned char ch = argv[1][i];
151195      /* We explicitly don't support UTF-8 delimiters for now. */
151196      if( ch>=0x80 ){
151197        sqlite3_free(t);
151198        return SQLITE_ERROR;
151199      }
151200      t->delim[ch] = 1;
151201    }
151202  } else {
151203    /* Mark non-alphanumeric ASCII characters as delimiters */
151204    int i;
151205    for(i=1; i<0x80; i++){
151206      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
151207    }
151208  }
151209
151210  *ppTokenizer = &t->base;
151211  return SQLITE_OK;
151212}
151213
151214/*
151215** Destroy a tokenizer
151216*/
151217static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
151218  sqlite3_free(pTokenizer);
151219  return SQLITE_OK;
151220}
151221
151222/*
151223** Prepare to begin tokenizing a particular string.  The input
151224** string to be tokenized is pInput[0..nBytes-1].  A cursor
151225** used to incrementally tokenize this string is returned in
151226** *ppCursor.
151227*/
151228static int simpleOpen(
151229  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
151230  const char *pInput, int nBytes,        /* String to be tokenized */
151231  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
151232){
151233  simple_tokenizer_cursor *c;
151234
151235  UNUSED_PARAMETER(pTokenizer);
151236
151237  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
151238  if( c==NULL ) return SQLITE_NOMEM;
151239
151240  c->pInput = pInput;
151241  if( pInput==0 ){
151242    c->nBytes = 0;
151243  }else if( nBytes<0 ){
151244    c->nBytes = (int)strlen(pInput);
151245  }else{
151246    c->nBytes = nBytes;
151247  }
151248  c->iOffset = 0;                 /* start tokenizing at the beginning */
151249  c->iToken = 0;
151250  c->pToken = NULL;               /* no space allocated, yet. */
151251  c->nTokenAllocated = 0;
151252
151253  *ppCursor = &c->base;
151254  return SQLITE_OK;
151255}
151256
151257/*
151258** Close a tokenization cursor previously opened by a call to
151259** simpleOpen() above.
151260*/
151261static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
151262  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
151263  sqlite3_free(c->pToken);
151264  sqlite3_free(c);
151265  return SQLITE_OK;
151266}
151267
151268/*
151269** Extract the next token from a tokenization cursor.  The cursor must
151270** have been opened by a prior call to simpleOpen().
151271*/
151272static int simpleNext(
151273  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
151274  const char **ppToken,               /* OUT: *ppToken is the token text */
151275  int *pnBytes,                       /* OUT: Number of bytes in token */
151276  int *piStartOffset,                 /* OUT: Starting offset of token */
151277  int *piEndOffset,                   /* OUT: Ending offset of token */
151278  int *piPosition                     /* OUT: Position integer of token */
151279){
151280  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
151281  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
151282  unsigned char *p = (unsigned char *)c->pInput;
151283
151284  while( c->iOffset<c->nBytes ){
151285    int iStartOffset;
151286
151287    /* Scan past delimiter characters */
151288    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
151289      c->iOffset++;
151290    }
151291
151292    /* Count non-delimiter characters. */
151293    iStartOffset = c->iOffset;
151294    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
151295      c->iOffset++;
151296    }
151297
151298    if( c->iOffset>iStartOffset ){
151299      int i, n = c->iOffset-iStartOffset;
151300      if( n>c->nTokenAllocated ){
151301        char *pNew;
151302        c->nTokenAllocated = n+20;
151303        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
151304        if( !pNew ) return SQLITE_NOMEM;
151305        c->pToken = pNew;
151306      }
151307      for(i=0; i<n; i++){
151308        /* TODO(shess) This needs expansion to handle UTF-8
151309        ** case-insensitivity.
151310        */
151311        unsigned char ch = p[iStartOffset+i];
151312        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
151313      }
151314      *ppToken = c->pToken;
151315      *pnBytes = n;
151316      *piStartOffset = iStartOffset;
151317      *piEndOffset = c->iOffset;
151318      *piPosition = c->iToken++;
151319
151320      return SQLITE_OK;
151321    }
151322  }
151323  return SQLITE_DONE;
151324}
151325
151326/*
151327** The set of routines that implement the simple tokenizer
151328*/
151329static const sqlite3_tokenizer_module simpleTokenizerModule = {
151330  0,
151331  simpleCreate,
151332  simpleDestroy,
151333  simpleOpen,
151334  simpleClose,
151335  simpleNext,
151336  0,
151337};
151338
151339/*
151340** Allocate a new simple tokenizer.  Return a pointer to the new
151341** tokenizer in *ppModule
151342*/
151343SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
151344  sqlite3_tokenizer_module const**ppModule
151345){
151346  *ppModule = &simpleTokenizerModule;
151347}
151348
151349#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151350
151351/************** End of fts3_tokenizer1.c *************************************/
151352/************** Begin file fts3_tokenize_vtab.c ******************************/
151353/*
151354** 2013 Apr 22
151355**
151356** The author disclaims copyright to this source code.  In place of
151357** a legal notice, here is a blessing:
151358**
151359**    May you do good and not evil.
151360**    May you find forgiveness for yourself and forgive others.
151361**    May you share freely, never taking more than you give.
151362**
151363******************************************************************************
151364**
151365** This file contains code for the "fts3tokenize" virtual table module.
151366** An fts3tokenize virtual table is created as follows:
151367**
151368**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
151369**       <tokenizer-name>, <arg-1>, ...
151370**   );
151371**
151372** The table created has the following schema:
151373**
151374**   CREATE TABLE <tbl>(input, token, start, end, position)
151375**
151376** When queried, the query must include a WHERE clause of type:
151377**
151378**   input = <string>
151379**
151380** The virtual table module tokenizes this <string>, using the FTS3
151381** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
151382** statement and returns one row for each token in the result. With
151383** fields set as follows:
151384**
151385**   input:   Always set to a copy of <string>
151386**   token:   A token from the input.
151387**   start:   Byte offset of the token within the input <string>.
151388**   end:     Byte offset of the byte immediately following the end of the
151389**            token within the input string.
151390**   pos:     Token offset of token within input.
151391**
151392*/
151393/* #include "fts3Int.h" */
151394#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151395
151396/* #include <string.h> */
151397/* #include <assert.h> */
151398
151399typedef struct Fts3tokTable Fts3tokTable;
151400typedef struct Fts3tokCursor Fts3tokCursor;
151401
151402/*
151403** Virtual table structure.
151404*/
151405struct Fts3tokTable {
151406  sqlite3_vtab base;              /* Base class used by SQLite core */
151407  const sqlite3_tokenizer_module *pMod;
151408  sqlite3_tokenizer *pTok;
151409};
151410
151411/*
151412** Virtual table cursor structure.
151413*/
151414struct Fts3tokCursor {
151415  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
151416  char *zInput;                   /* Input string */
151417  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
151418  int iRowid;                     /* Current 'rowid' value */
151419  const char *zToken;             /* Current 'token' value */
151420  int nToken;                     /* Size of zToken in bytes */
151421  int iStart;                     /* Current 'start' value */
151422  int iEnd;                       /* Current 'end' value */
151423  int iPos;                       /* Current 'pos' value */
151424};
151425
151426/*
151427** Query FTS for the tokenizer implementation named zName.
151428*/
151429static int fts3tokQueryTokenizer(
151430  Fts3Hash *pHash,
151431  const char *zName,
151432  const sqlite3_tokenizer_module **pp,
151433  char **pzErr
151434){
151435  sqlite3_tokenizer_module *p;
151436  int nName = (int)strlen(zName);
151437
151438  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
151439  if( !p ){
151440    sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
151441    return SQLITE_ERROR;
151442  }
151443
151444  *pp = p;
151445  return SQLITE_OK;
151446}
151447
151448/*
151449** The second argument, argv[], is an array of pointers to nul-terminated
151450** strings. This function makes a copy of the array and strings into a
151451** single block of memory. It then dequotes any of the strings that appear
151452** to be quoted.
151453**
151454** If successful, output parameter *pazDequote is set to point at the
151455** array of dequoted strings and SQLITE_OK is returned. The caller is
151456** responsible for eventually calling sqlite3_free() to free the array
151457** in this case. Or, if an error occurs, an SQLite error code is returned.
151458** The final value of *pazDequote is undefined in this case.
151459*/
151460static int fts3tokDequoteArray(
151461  int argc,                       /* Number of elements in argv[] */
151462  const char * const *argv,       /* Input array */
151463  char ***pazDequote              /* Output array */
151464){
151465  int rc = SQLITE_OK;             /* Return code */
151466  if( argc==0 ){
151467    *pazDequote = 0;
151468  }else{
151469    int i;
151470    int nByte = 0;
151471    char **azDequote;
151472
151473    for(i=0; i<argc; i++){
151474      nByte += (int)(strlen(argv[i]) + 1);
151475    }
151476
151477    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
151478    if( azDequote==0 ){
151479      rc = SQLITE_NOMEM;
151480    }else{
151481      char *pSpace = (char *)&azDequote[argc];
151482      for(i=0; i<argc; i++){
151483        int n = (int)strlen(argv[i]);
151484        azDequote[i] = pSpace;
151485        memcpy(pSpace, argv[i], n+1);
151486        sqlite3Fts3Dequote(pSpace);
151487        pSpace += (n+1);
151488      }
151489    }
151490  }
151491
151492  return rc;
151493}
151494
151495/*
151496** Schema of the tokenizer table.
151497*/
151498#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
151499
151500/*
151501** This function does all the work for both the xConnect and xCreate methods.
151502** These tables have no persistent representation of their own, so xConnect
151503** and xCreate are identical operations.
151504**
151505**   argv[0]: module name
151506**   argv[1]: database name
151507**   argv[2]: table name
151508**   argv[3]: first argument (tokenizer name)
151509*/
151510static int fts3tokConnectMethod(
151511  sqlite3 *db,                    /* Database connection */
151512  void *pHash,                    /* Hash table of tokenizers */
151513  int argc,                       /* Number of elements in argv array */
151514  const char * const *argv,       /* xCreate/xConnect argument array */
151515  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
151516  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
151517){
151518  Fts3tokTable *pTab = 0;
151519  const sqlite3_tokenizer_module *pMod = 0;
151520  sqlite3_tokenizer *pTok = 0;
151521  int rc;
151522  char **azDequote = 0;
151523  int nDequote;
151524
151525  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
151526  if( rc!=SQLITE_OK ) return rc;
151527
151528  nDequote = argc-3;
151529  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
151530
151531  if( rc==SQLITE_OK ){
151532    const char *zModule;
151533    if( nDequote<1 ){
151534      zModule = "simple";
151535    }else{
151536      zModule = azDequote[0];
151537    }
151538    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
151539  }
151540
151541  assert( (rc==SQLITE_OK)==(pMod!=0) );
151542  if( rc==SQLITE_OK ){
151543    const char * const *azArg = (const char * const *)&azDequote[1];
151544    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
151545  }
151546
151547  if( rc==SQLITE_OK ){
151548    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
151549    if( pTab==0 ){
151550      rc = SQLITE_NOMEM;
151551    }
151552  }
151553
151554  if( rc==SQLITE_OK ){
151555    memset(pTab, 0, sizeof(Fts3tokTable));
151556    pTab->pMod = pMod;
151557    pTab->pTok = pTok;
151558    *ppVtab = &pTab->base;
151559  }else{
151560    if( pTok ){
151561      pMod->xDestroy(pTok);
151562    }
151563  }
151564
151565  sqlite3_free(azDequote);
151566  return rc;
151567}
151568
151569/*
151570** This function does the work for both the xDisconnect and xDestroy methods.
151571** These tables have no persistent representation of their own, so xDisconnect
151572** and xDestroy are identical operations.
151573*/
151574static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
151575  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
151576
151577  pTab->pMod->xDestroy(pTab->pTok);
151578  sqlite3_free(pTab);
151579  return SQLITE_OK;
151580}
151581
151582/*
151583** xBestIndex - Analyze a WHERE and ORDER BY clause.
151584*/
151585static int fts3tokBestIndexMethod(
151586  sqlite3_vtab *pVTab,
151587  sqlite3_index_info *pInfo
151588){
151589  int i;
151590  UNUSED_PARAMETER(pVTab);
151591
151592  for(i=0; i<pInfo->nConstraint; i++){
151593    if( pInfo->aConstraint[i].usable
151594     && pInfo->aConstraint[i].iColumn==0
151595     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
151596    ){
151597      pInfo->idxNum = 1;
151598      pInfo->aConstraintUsage[i].argvIndex = 1;
151599      pInfo->aConstraintUsage[i].omit = 1;
151600      pInfo->estimatedCost = 1;
151601      return SQLITE_OK;
151602    }
151603  }
151604
151605  pInfo->idxNum = 0;
151606  assert( pInfo->estimatedCost>1000000.0 );
151607
151608  return SQLITE_OK;
151609}
151610
151611/*
151612** xOpen - Open a cursor.
151613*/
151614static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
151615  Fts3tokCursor *pCsr;
151616  UNUSED_PARAMETER(pVTab);
151617
151618  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
151619  if( pCsr==0 ){
151620    return SQLITE_NOMEM;
151621  }
151622  memset(pCsr, 0, sizeof(Fts3tokCursor));
151623
151624  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
151625  return SQLITE_OK;
151626}
151627
151628/*
151629** Reset the tokenizer cursor passed as the only argument. As if it had
151630** just been returned by fts3tokOpenMethod().
151631*/
151632static void fts3tokResetCursor(Fts3tokCursor *pCsr){
151633  if( pCsr->pCsr ){
151634    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
151635    pTab->pMod->xClose(pCsr->pCsr);
151636    pCsr->pCsr = 0;
151637  }
151638  sqlite3_free(pCsr->zInput);
151639  pCsr->zInput = 0;
151640  pCsr->zToken = 0;
151641  pCsr->nToken = 0;
151642  pCsr->iStart = 0;
151643  pCsr->iEnd = 0;
151644  pCsr->iPos = 0;
151645  pCsr->iRowid = 0;
151646}
151647
151648/*
151649** xClose - Close a cursor.
151650*/
151651static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
151652  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151653
151654  fts3tokResetCursor(pCsr);
151655  sqlite3_free(pCsr);
151656  return SQLITE_OK;
151657}
151658
151659/*
151660** xNext - Advance the cursor to the next row, if any.
151661*/
151662static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
151663  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151664  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
151665  int rc;                         /* Return code */
151666
151667  pCsr->iRowid++;
151668  rc = pTab->pMod->xNext(pCsr->pCsr,
151669      &pCsr->zToken, &pCsr->nToken,
151670      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
151671  );
151672
151673  if( rc!=SQLITE_OK ){
151674    fts3tokResetCursor(pCsr);
151675    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151676  }
151677
151678  return rc;
151679}
151680
151681/*
151682** xFilter - Initialize a cursor to point at the start of its data.
151683*/
151684static int fts3tokFilterMethod(
151685  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
151686  int idxNum,                     /* Strategy index */
151687  const char *idxStr,             /* Unused */
151688  int nVal,                       /* Number of elements in apVal */
151689  sqlite3_value **apVal           /* Arguments for the indexing scheme */
151690){
151691  int rc = SQLITE_ERROR;
151692  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151693  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
151694  UNUSED_PARAMETER(idxStr);
151695  UNUSED_PARAMETER(nVal);
151696
151697  fts3tokResetCursor(pCsr);
151698  if( idxNum==1 ){
151699    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
151700    int nByte = sqlite3_value_bytes(apVal[0]);
151701    pCsr->zInput = sqlite3_malloc(nByte+1);
151702    if( pCsr->zInput==0 ){
151703      rc = SQLITE_NOMEM;
151704    }else{
151705      memcpy(pCsr->zInput, zByte, nByte);
151706      pCsr->zInput[nByte] = 0;
151707      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
151708      if( rc==SQLITE_OK ){
151709        pCsr->pCsr->pTokenizer = pTab->pTok;
151710      }
151711    }
151712  }
151713
151714  if( rc!=SQLITE_OK ) return rc;
151715  return fts3tokNextMethod(pCursor);
151716}
151717
151718/*
151719** xEof - Return true if the cursor is at EOF, or false otherwise.
151720*/
151721static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
151722  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151723  return (pCsr->zToken==0);
151724}
151725
151726/*
151727** xColumn - Return a column value.
151728*/
151729static int fts3tokColumnMethod(
151730  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151731  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
151732  int iCol                        /* Index of column to read value from */
151733){
151734  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151735
151736  /* CREATE TABLE x(input, token, start, end, position) */
151737  switch( iCol ){
151738    case 0:
151739      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
151740      break;
151741    case 1:
151742      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
151743      break;
151744    case 2:
151745      sqlite3_result_int(pCtx, pCsr->iStart);
151746      break;
151747    case 3:
151748      sqlite3_result_int(pCtx, pCsr->iEnd);
151749      break;
151750    default:
151751      assert( iCol==4 );
151752      sqlite3_result_int(pCtx, pCsr->iPos);
151753      break;
151754  }
151755  return SQLITE_OK;
151756}
151757
151758/*
151759** xRowid - Return the current rowid for the cursor.
151760*/
151761static int fts3tokRowidMethod(
151762  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151763  sqlite_int64 *pRowid            /* OUT: Rowid value */
151764){
151765  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151766  *pRowid = (sqlite3_int64)pCsr->iRowid;
151767  return SQLITE_OK;
151768}
151769
151770/*
151771** Register the fts3tok module with database connection db. Return SQLITE_OK
151772** if successful or an error code if sqlite3_create_module() fails.
151773*/
151774SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
151775  static const sqlite3_module fts3tok_module = {
151776     0,                           /* iVersion      */
151777     fts3tokConnectMethod,        /* xCreate       */
151778     fts3tokConnectMethod,        /* xConnect      */
151779     fts3tokBestIndexMethod,      /* xBestIndex    */
151780     fts3tokDisconnectMethod,     /* xDisconnect   */
151781     fts3tokDisconnectMethod,     /* xDestroy      */
151782     fts3tokOpenMethod,           /* xOpen         */
151783     fts3tokCloseMethod,          /* xClose        */
151784     fts3tokFilterMethod,         /* xFilter       */
151785     fts3tokNextMethod,           /* xNext         */
151786     fts3tokEofMethod,            /* xEof          */
151787     fts3tokColumnMethod,         /* xColumn       */
151788     fts3tokRowidMethod,          /* xRowid        */
151789     0,                           /* xUpdate       */
151790     0,                           /* xBegin        */
151791     0,                           /* xSync         */
151792     0,                           /* xCommit       */
151793     0,                           /* xRollback     */
151794     0,                           /* xFindFunction */
151795     0,                           /* xRename       */
151796     0,                           /* xSavepoint    */
151797     0,                           /* xRelease      */
151798     0                            /* xRollbackTo   */
151799  };
151800  int rc;                         /* Return code */
151801
151802  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
151803  return rc;
151804}
151805
151806#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151807
151808/************** End of fts3_tokenize_vtab.c **********************************/
151809/************** Begin file fts3_write.c **************************************/
151810/*
151811** 2009 Oct 23
151812**
151813** The author disclaims copyright to this source code.  In place of
151814** a legal notice, here is a blessing:
151815**
151816**    May you do good and not evil.
151817**    May you find forgiveness for yourself and forgive others.
151818**    May you share freely, never taking more than you give.
151819**
151820******************************************************************************
151821**
151822** This file is part of the SQLite FTS3 extension module. Specifically,
151823** this file contains code to insert, update and delete rows from FTS3
151824** tables. It also contains code to merge FTS3 b-tree segments. Some
151825** of the sub-routines used to merge segments are also used by the query
151826** code in fts3.c.
151827*/
151828
151829/* #include "fts3Int.h" */
151830#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151831
151832/* #include <string.h> */
151833/* #include <assert.h> */
151834/* #include <stdlib.h> */
151835
151836
151837#define FTS_MAX_APPENDABLE_HEIGHT 16
151838
151839/*
151840** When full-text index nodes are loaded from disk, the buffer that they
151841** are loaded into has the following number of bytes of padding at the end
151842** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
151843** of 920 bytes is allocated for it.
151844**
151845** This means that if we have a pointer into a buffer containing node data,
151846** it is always safe to read up to two varints from it without risking an
151847** overread, even if the node data is corrupted.
151848*/
151849#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
151850
151851/*
151852** Under certain circumstances, b-tree nodes (doclists) can be loaded into
151853** memory incrementally instead of all at once. This can be a big performance
151854** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
151855** method before retrieving all query results (as may happen, for example,
151856** if a query has a LIMIT clause).
151857**
151858** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
151859** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
151860** The code is written so that the hard lower-limit for each of these values
151861** is 1. Clearly such small values would be inefficient, but can be useful
151862** for testing purposes.
151863**
151864** If this module is built with SQLITE_TEST defined, these constants may
151865** be overridden at runtime for testing purposes. File fts3_test.c contains
151866** a Tcl interface to read and write the values.
151867*/
151868#ifdef SQLITE_TEST
151869int test_fts3_node_chunksize = (4*1024);
151870int test_fts3_node_chunk_threshold = (4*1024)*4;
151871# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
151872# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
151873#else
151874# define FTS3_NODE_CHUNKSIZE (4*1024)
151875# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
151876#endif
151877
151878/*
151879** The two values that may be meaningfully bound to the :1 parameter in
151880** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
151881*/
151882#define FTS_STAT_DOCTOTAL      0
151883#define FTS_STAT_INCRMERGEHINT 1
151884#define FTS_STAT_AUTOINCRMERGE 2
151885
151886/*
151887** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
151888** and incremental merge operation that takes place. This is used for
151889** debugging FTS only, it should not usually be turned on in production
151890** systems.
151891*/
151892#ifdef FTS3_LOG_MERGES
151893static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
151894  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
151895}
151896#else
151897#define fts3LogMerge(x, y)
151898#endif
151899
151900
151901typedef struct PendingList PendingList;
151902typedef struct SegmentNode SegmentNode;
151903typedef struct SegmentWriter SegmentWriter;
151904
151905/*
151906** An instance of the following data structure is used to build doclists
151907** incrementally. See function fts3PendingListAppend() for details.
151908*/
151909struct PendingList {
151910  int nData;
151911  char *aData;
151912  int nSpace;
151913  sqlite3_int64 iLastDocid;
151914  sqlite3_int64 iLastCol;
151915  sqlite3_int64 iLastPos;
151916};
151917
151918
151919/*
151920** Each cursor has a (possibly empty) linked list of the following objects.
151921*/
151922struct Fts3DeferredToken {
151923  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
151924  int iCol;                       /* Column token must occur in */
151925  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
151926  PendingList *pList;             /* Doclist is assembled here */
151927};
151928
151929/*
151930** An instance of this structure is used to iterate through the terms on
151931** a contiguous set of segment b-tree leaf nodes. Although the details of
151932** this structure are only manipulated by code in this file, opaque handles
151933** of type Fts3SegReader* are also used by code in fts3.c to iterate through
151934** terms when querying the full-text index. See functions:
151935**
151936**   sqlite3Fts3SegReaderNew()
151937**   sqlite3Fts3SegReaderFree()
151938**   sqlite3Fts3SegReaderIterate()
151939**
151940** Methods used to manipulate Fts3SegReader structures:
151941**
151942**   fts3SegReaderNext()
151943**   fts3SegReaderFirstDocid()
151944**   fts3SegReaderNextDocid()
151945*/
151946struct Fts3SegReader {
151947  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
151948  u8 bLookup;                     /* True for a lookup only */
151949  u8 rootOnly;                    /* True for a root-only reader */
151950
151951  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
151952  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
151953  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
151954  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
151955
151956  char *aNode;                    /* Pointer to node data (or NULL) */
151957  int nNode;                      /* Size of buffer at aNode (or 0) */
151958  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
151959  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
151960
151961  Fts3HashElem **ppNextElem;
151962
151963  /* Variables set by fts3SegReaderNext(). These may be read directly
151964  ** by the caller. They are valid from the time SegmentReaderNew() returns
151965  ** until SegmentReaderNext() returns something other than SQLITE_OK
151966  ** (i.e. SQLITE_DONE).
151967  */
151968  int nTerm;                      /* Number of bytes in current term */
151969  char *zTerm;                    /* Pointer to current term */
151970  int nTermAlloc;                 /* Allocated size of zTerm buffer */
151971  char *aDoclist;                 /* Pointer to doclist of current entry */
151972  int nDoclist;                   /* Size of doclist in current entry */
151973
151974  /* The following variables are used by fts3SegReaderNextDocid() to iterate
151975  ** through the current doclist (aDoclist/nDoclist).
151976  */
151977  char *pOffsetList;
151978  int nOffsetList;                /* For descending pending seg-readers only */
151979  sqlite3_int64 iDocid;
151980};
151981
151982#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
151983#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
151984
151985/*
151986** An instance of this structure is used to create a segment b-tree in the
151987** database. The internal details of this type are only accessed by the
151988** following functions:
151989**
151990**   fts3SegWriterAdd()
151991**   fts3SegWriterFlush()
151992**   fts3SegWriterFree()
151993*/
151994struct SegmentWriter {
151995  SegmentNode *pTree;             /* Pointer to interior tree structure */
151996  sqlite3_int64 iFirst;           /* First slot in %_segments written */
151997  sqlite3_int64 iFree;            /* Next free slot in %_segments */
151998  char *zTerm;                    /* Pointer to previous term buffer */
151999  int nTerm;                      /* Number of bytes in zTerm */
152000  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
152001  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
152002  int nSize;                      /* Size of allocation at aData */
152003  int nData;                      /* Bytes of data in aData */
152004  char *aData;                    /* Pointer to block from malloc() */
152005  i64 nLeafData;                  /* Number of bytes of leaf data written */
152006};
152007
152008/*
152009** Type SegmentNode is used by the following three functions to create
152010** the interior part of the segment b+-tree structures (everything except
152011** the leaf nodes). These functions and type are only ever used by code
152012** within the fts3SegWriterXXX() family of functions described above.
152013**
152014**   fts3NodeAddTerm()
152015**   fts3NodeWrite()
152016**   fts3NodeFree()
152017**
152018** When a b+tree is written to the database (either as a result of a merge
152019** or the pending-terms table being flushed), leaves are written into the
152020** database file as soon as they are completely populated. The interior of
152021** the tree is assembled in memory and written out only once all leaves have
152022** been populated and stored. This is Ok, as the b+-tree fanout is usually
152023** very large, meaning that the interior of the tree consumes relatively
152024** little memory.
152025*/
152026struct SegmentNode {
152027  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
152028  SegmentNode *pRight;            /* Pointer to right-sibling */
152029  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
152030  int nEntry;                     /* Number of terms written to node so far */
152031  char *zTerm;                    /* Pointer to previous term buffer */
152032  int nTerm;                      /* Number of bytes in zTerm */
152033  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
152034  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
152035  int nData;                      /* Bytes of valid data so far */
152036  char *aData;                    /* Node data */
152037};
152038
152039/*
152040** Valid values for the second argument to fts3SqlStmt().
152041*/
152042#define SQL_DELETE_CONTENT             0
152043#define SQL_IS_EMPTY                   1
152044#define SQL_DELETE_ALL_CONTENT         2
152045#define SQL_DELETE_ALL_SEGMENTS        3
152046#define SQL_DELETE_ALL_SEGDIR          4
152047#define SQL_DELETE_ALL_DOCSIZE         5
152048#define SQL_DELETE_ALL_STAT            6
152049#define SQL_SELECT_CONTENT_BY_ROWID    7
152050#define SQL_NEXT_SEGMENT_INDEX         8
152051#define SQL_INSERT_SEGMENTS            9
152052#define SQL_NEXT_SEGMENTS_ID          10
152053#define SQL_INSERT_SEGDIR             11
152054#define SQL_SELECT_LEVEL              12
152055#define SQL_SELECT_LEVEL_RANGE        13
152056#define SQL_SELECT_LEVEL_COUNT        14
152057#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
152058#define SQL_DELETE_SEGDIR_LEVEL       16
152059#define SQL_DELETE_SEGMENTS_RANGE     17
152060#define SQL_CONTENT_INSERT            18
152061#define SQL_DELETE_DOCSIZE            19
152062#define SQL_REPLACE_DOCSIZE           20
152063#define SQL_SELECT_DOCSIZE            21
152064#define SQL_SELECT_STAT               22
152065#define SQL_REPLACE_STAT              23
152066
152067#define SQL_SELECT_ALL_PREFIX_LEVEL   24
152068#define SQL_DELETE_ALL_TERMS_SEGDIR   25
152069#define SQL_DELETE_SEGDIR_RANGE       26
152070#define SQL_SELECT_ALL_LANGID         27
152071#define SQL_FIND_MERGE_LEVEL          28
152072#define SQL_MAX_LEAF_NODE_ESTIMATE    29
152073#define SQL_DELETE_SEGDIR_ENTRY       30
152074#define SQL_SHIFT_SEGDIR_ENTRY        31
152075#define SQL_SELECT_SEGDIR             32
152076#define SQL_CHOMP_SEGDIR              33
152077#define SQL_SEGMENT_IS_APPENDABLE     34
152078#define SQL_SELECT_INDEXES            35
152079#define SQL_SELECT_MXLEVEL            36
152080
152081#define SQL_SELECT_LEVEL_RANGE2       37
152082#define SQL_UPDATE_LEVEL_IDX          38
152083#define SQL_UPDATE_LEVEL              39
152084
152085/*
152086** This function is used to obtain an SQLite prepared statement handle
152087** for the statement identified by the second argument. If successful,
152088** *pp is set to the requested statement handle and SQLITE_OK returned.
152089** Otherwise, an SQLite error code is returned and *pp is set to 0.
152090**
152091** If argument apVal is not NULL, then it must point to an array with
152092** at least as many entries as the requested statement has bound
152093** parameters. The values are bound to the statements parameters before
152094** returning.
152095*/
152096static int fts3SqlStmt(
152097  Fts3Table *p,                   /* Virtual table handle */
152098  int eStmt,                      /* One of the SQL_XXX constants above */
152099  sqlite3_stmt **pp,              /* OUT: Statement handle */
152100  sqlite3_value **apVal           /* Values to bind to statement */
152101){
152102  const char *azSql[] = {
152103/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
152104/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
152105/* 2  */  "DELETE FROM %Q.'%q_content'",
152106/* 3  */  "DELETE FROM %Q.'%q_segments'",
152107/* 4  */  "DELETE FROM %Q.'%q_segdir'",
152108/* 5  */  "DELETE FROM %Q.'%q_docsize'",
152109/* 6  */  "DELETE FROM %Q.'%q_stat'",
152110/* 7  */  "SELECT %s WHERE rowid=?",
152111/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
152112/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
152113/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
152114/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
152115
152116          /* Return segments in order from oldest to newest.*/
152117/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152118            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
152119/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152120            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
152121            "ORDER BY level DESC, idx ASC",
152122
152123/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
152124/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
152125
152126/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
152127/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
152128/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
152129/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
152130/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
152131/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
152132/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
152133/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
152134/* 24 */  "",
152135/* 25 */  "",
152136
152137/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
152138/* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
152139
152140/* This statement is used to determine which level to read the input from
152141** when performing an incremental merge. It returns the absolute level number
152142** of the oldest level in the db that contains at least ? segments. Or,
152143** if no level in the FTS index contains more than ? segments, the statement
152144** returns zero rows.  */
152145/* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
152146         "  GROUP BY level HAVING cnt>=?"
152147         "  ORDER BY (level %% 1024) ASC LIMIT 1",
152148
152149/* Estimate the upper limit on the number of leaf nodes in a new segment
152150** created by merging the oldest :2 segments from absolute level :1. See
152151** function sqlite3Fts3Incrmerge() for details.  */
152152/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
152153         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
152154
152155/* SQL_DELETE_SEGDIR_ENTRY
152156**   Delete the %_segdir entry on absolute level :1 with index :2.  */
152157/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
152158
152159/* SQL_SHIFT_SEGDIR_ENTRY
152160**   Modify the idx value for the segment with idx=:3 on absolute level :2
152161**   to :1.  */
152162/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
152163
152164/* SQL_SELECT_SEGDIR
152165**   Read a single entry from the %_segdir table. The entry from absolute
152166**   level :1 with index value :2.  */
152167/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152168            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
152169
152170/* SQL_CHOMP_SEGDIR
152171**   Update the start_block (:1) and root (:2) fields of the %_segdir
152172**   entry located on absolute level :3 with index :4.  */
152173/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
152174            "WHERE level = ? AND idx = ?",
152175
152176/* SQL_SEGMENT_IS_APPENDABLE
152177**   Return a single row if the segment with end_block=? is appendable. Or
152178**   no rows otherwise.  */
152179/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
152180
152181/* SQL_SELECT_INDEXES
152182**   Return the list of valid segment indexes for absolute level ?  */
152183/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
152184
152185/* SQL_SELECT_MXLEVEL
152186**   Return the largest relative level in the FTS index or indexes.  */
152187/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
152188
152189          /* Return segments in order from oldest to newest.*/
152190/* 37 */  "SELECT level, idx, end_block "
152191            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
152192            "ORDER BY level DESC, idx ASC",
152193
152194          /* Update statements used while promoting segments */
152195/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
152196            "WHERE level=? AND idx=?",
152197/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
152198
152199  };
152200  int rc = SQLITE_OK;
152201  sqlite3_stmt *pStmt;
152202
152203  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
152204  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
152205
152206  pStmt = p->aStmt[eStmt];
152207  if( !pStmt ){
152208    char *zSql;
152209    if( eStmt==SQL_CONTENT_INSERT ){
152210      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
152211    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
152212      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
152213    }else{
152214      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
152215    }
152216    if( !zSql ){
152217      rc = SQLITE_NOMEM;
152218    }else{
152219      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
152220      sqlite3_free(zSql);
152221      assert( rc==SQLITE_OK || pStmt==0 );
152222      p->aStmt[eStmt] = pStmt;
152223    }
152224  }
152225  if( apVal ){
152226    int i;
152227    int nParam = sqlite3_bind_parameter_count(pStmt);
152228    for(i=0; rc==SQLITE_OK && i<nParam; i++){
152229      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
152230    }
152231  }
152232  *pp = pStmt;
152233  return rc;
152234}
152235
152236
152237static int fts3SelectDocsize(
152238  Fts3Table *pTab,                /* FTS3 table handle */
152239  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
152240  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152241){
152242  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
152243  int rc;                         /* Return code */
152244
152245  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
152246  if( rc==SQLITE_OK ){
152247    sqlite3_bind_int64(pStmt, 1, iDocid);
152248    rc = sqlite3_step(pStmt);
152249    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
152250      rc = sqlite3_reset(pStmt);
152251      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
152252      pStmt = 0;
152253    }else{
152254      rc = SQLITE_OK;
152255    }
152256  }
152257
152258  *ppStmt = pStmt;
152259  return rc;
152260}
152261
152262SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
152263  Fts3Table *pTab,                /* Fts3 table handle */
152264  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152265){
152266  sqlite3_stmt *pStmt = 0;
152267  int rc;
152268  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
152269  if( rc==SQLITE_OK ){
152270    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
152271    if( sqlite3_step(pStmt)!=SQLITE_ROW
152272     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
152273    ){
152274      rc = sqlite3_reset(pStmt);
152275      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
152276      pStmt = 0;
152277    }
152278  }
152279  *ppStmt = pStmt;
152280  return rc;
152281}
152282
152283SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
152284  Fts3Table *pTab,                /* Fts3 table handle */
152285  sqlite3_int64 iDocid,           /* Docid to read size data for */
152286  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152287){
152288  return fts3SelectDocsize(pTab, iDocid, ppStmt);
152289}
152290
152291/*
152292** Similar to fts3SqlStmt(). Except, after binding the parameters in
152293** array apVal[] to the SQL statement identified by eStmt, the statement
152294** is executed.
152295**
152296** Returns SQLITE_OK if the statement is successfully executed, or an
152297** SQLite error code otherwise.
152298*/
152299static void fts3SqlExec(
152300  int *pRC,                /* Result code */
152301  Fts3Table *p,            /* The FTS3 table */
152302  int eStmt,               /* Index of statement to evaluate */
152303  sqlite3_value **apVal    /* Parameters to bind */
152304){
152305  sqlite3_stmt *pStmt;
152306  int rc;
152307  if( *pRC ) return;
152308  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
152309  if( rc==SQLITE_OK ){
152310    sqlite3_step(pStmt);
152311    rc = sqlite3_reset(pStmt);
152312  }
152313  *pRC = rc;
152314}
152315
152316
152317/*
152318** This function ensures that the caller has obtained an exclusive
152319** shared-cache table-lock on the %_segdir table. This is required before
152320** writing data to the fts3 table. If this lock is not acquired first, then
152321** the caller may end up attempting to take this lock as part of committing
152322** a transaction, causing SQLite to return SQLITE_LOCKED or
152323** LOCKED_SHAREDCACHEto a COMMIT command.
152324**
152325** It is best to avoid this because if FTS3 returns any error when
152326** committing a transaction, the whole transaction will be rolled back.
152327** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
152328** It can still happen if the user locks the underlying tables directly
152329** instead of accessing them via FTS.
152330*/
152331static int fts3Writelock(Fts3Table *p){
152332  int rc = SQLITE_OK;
152333
152334  if( p->nPendingData==0 ){
152335    sqlite3_stmt *pStmt;
152336    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
152337    if( rc==SQLITE_OK ){
152338      sqlite3_bind_null(pStmt, 1);
152339      sqlite3_step(pStmt);
152340      rc = sqlite3_reset(pStmt);
152341    }
152342  }
152343
152344  return rc;
152345}
152346
152347/*
152348** FTS maintains a separate indexes for each language-id (a 32-bit integer).
152349** Within each language id, a separate index is maintained to store the
152350** document terms, and each configured prefix size (configured the FTS
152351** "prefix=" option). And each index consists of multiple levels ("relative
152352** levels").
152353**
152354** All three of these values (the language id, the specific index and the
152355** level within the index) are encoded in 64-bit integer values stored
152356** in the %_segdir table on disk. This function is used to convert three
152357** separate component values into the single 64-bit integer value that
152358** can be used to query the %_segdir table.
152359**
152360** Specifically, each language-id/index combination is allocated 1024
152361** 64-bit integer level values ("absolute levels"). The main terms index
152362** for language-id 0 is allocate values 0-1023. The first prefix index
152363** (if any) for language-id 0 is allocated values 1024-2047. And so on.
152364** Language 1 indexes are allocated immediately following language 0.
152365**
152366** So, for a system with nPrefix prefix indexes configured, the block of
152367** absolute levels that corresponds to language-id iLangid and index
152368** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
152369*/
152370static sqlite3_int64 getAbsoluteLevel(
152371  Fts3Table *p,                   /* FTS3 table handle */
152372  int iLangid,                    /* Language id */
152373  int iIndex,                     /* Index in p->aIndex[] */
152374  int iLevel                      /* Level of segments */
152375){
152376  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
152377  assert( iLangid>=0 );
152378  assert( p->nIndex>0 );
152379  assert( iIndex>=0 && iIndex<p->nIndex );
152380
152381  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
152382  return iBase + iLevel;
152383}
152384
152385/*
152386** Set *ppStmt to a statement handle that may be used to iterate through
152387** all rows in the %_segdir table, from oldest to newest. If successful,
152388** return SQLITE_OK. If an error occurs while preparing the statement,
152389** return an SQLite error code.
152390**
152391** There is only ever one instance of this SQL statement compiled for
152392** each FTS3 table.
152393**
152394** The statement returns the following columns from the %_segdir table:
152395**
152396**   0: idx
152397**   1: start_block
152398**   2: leaves_end_block
152399**   3: end_block
152400**   4: root
152401*/
152402SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
152403  Fts3Table *p,                   /* FTS3 table */
152404  int iLangid,                    /* Language being queried */
152405  int iIndex,                     /* Index for p->aIndex[] */
152406  int iLevel,                     /* Level to select (relative level) */
152407  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
152408){
152409  int rc;
152410  sqlite3_stmt *pStmt = 0;
152411
152412  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
152413  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
152414  assert( iIndex>=0 && iIndex<p->nIndex );
152415
152416  if( iLevel<0 ){
152417    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
152418    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
152419    if( rc==SQLITE_OK ){
152420      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
152421      sqlite3_bind_int64(pStmt, 2,
152422          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
152423      );
152424    }
152425  }else{
152426    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
152427    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
152428    if( rc==SQLITE_OK ){
152429      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
152430    }
152431  }
152432  *ppStmt = pStmt;
152433  return rc;
152434}
152435
152436
152437/*
152438** Append a single varint to a PendingList buffer. SQLITE_OK is returned
152439** if successful, or an SQLite error code otherwise.
152440**
152441** This function also serves to allocate the PendingList structure itself.
152442** For example, to create a new PendingList structure containing two
152443** varints:
152444**
152445**   PendingList *p = 0;
152446**   fts3PendingListAppendVarint(&p, 1);
152447**   fts3PendingListAppendVarint(&p, 2);
152448*/
152449static int fts3PendingListAppendVarint(
152450  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
152451  sqlite3_int64 i                 /* Value to append to data */
152452){
152453  PendingList *p = *pp;
152454
152455  /* Allocate or grow the PendingList as required. */
152456  if( !p ){
152457    p = sqlite3_malloc(sizeof(*p) + 100);
152458    if( !p ){
152459      return SQLITE_NOMEM;
152460    }
152461    p->nSpace = 100;
152462    p->aData = (char *)&p[1];
152463    p->nData = 0;
152464  }
152465  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
152466    int nNew = p->nSpace * 2;
152467    p = sqlite3_realloc(p, sizeof(*p) + nNew);
152468    if( !p ){
152469      sqlite3_free(*pp);
152470      *pp = 0;
152471      return SQLITE_NOMEM;
152472    }
152473    p->nSpace = nNew;
152474    p->aData = (char *)&p[1];
152475  }
152476
152477  /* Append the new serialized varint to the end of the list. */
152478  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
152479  p->aData[p->nData] = '\0';
152480  *pp = p;
152481  return SQLITE_OK;
152482}
152483
152484/*
152485** Add a docid/column/position entry to a PendingList structure. Non-zero
152486** is returned if the structure is sqlite3_realloced as part of adding
152487** the entry. Otherwise, zero.
152488**
152489** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
152490** Zero is always returned in this case. Otherwise, if no OOM error occurs,
152491** it is set to SQLITE_OK.
152492*/
152493static int fts3PendingListAppend(
152494  PendingList **pp,               /* IN/OUT: PendingList structure */
152495  sqlite3_int64 iDocid,           /* Docid for entry to add */
152496  sqlite3_int64 iCol,             /* Column for entry to add */
152497  sqlite3_int64 iPos,             /* Position of term for entry to add */
152498  int *pRc                        /* OUT: Return code */
152499){
152500  PendingList *p = *pp;
152501  int rc = SQLITE_OK;
152502
152503  assert( !p || p->iLastDocid<=iDocid );
152504
152505  if( !p || p->iLastDocid!=iDocid ){
152506    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
152507    if( p ){
152508      assert( p->nData<p->nSpace );
152509      assert( p->aData[p->nData]==0 );
152510      p->nData++;
152511    }
152512    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
152513      goto pendinglistappend_out;
152514    }
152515    p->iLastCol = -1;
152516    p->iLastPos = 0;
152517    p->iLastDocid = iDocid;
152518  }
152519  if( iCol>0 && p->iLastCol!=iCol ){
152520    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
152521     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
152522    ){
152523      goto pendinglistappend_out;
152524    }
152525    p->iLastCol = iCol;
152526    p->iLastPos = 0;
152527  }
152528  if( iCol>=0 ){
152529    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
152530    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
152531    if( rc==SQLITE_OK ){
152532      p->iLastPos = iPos;
152533    }
152534  }
152535
152536 pendinglistappend_out:
152537  *pRc = rc;
152538  if( p!=*pp ){
152539    *pp = p;
152540    return 1;
152541  }
152542  return 0;
152543}
152544
152545/*
152546** Free a PendingList object allocated by fts3PendingListAppend().
152547*/
152548static void fts3PendingListDelete(PendingList *pList){
152549  sqlite3_free(pList);
152550}
152551
152552/*
152553** Add an entry to one of the pending-terms hash tables.
152554*/
152555static int fts3PendingTermsAddOne(
152556  Fts3Table *p,
152557  int iCol,
152558  int iPos,
152559  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
152560  const char *zToken,
152561  int nToken
152562){
152563  PendingList *pList;
152564  int rc = SQLITE_OK;
152565
152566  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
152567  if( pList ){
152568    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
152569  }
152570  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
152571    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
152572      /* Malloc failed while inserting the new entry. This can only
152573      ** happen if there was no previous entry for this token.
152574      */
152575      assert( 0==fts3HashFind(pHash, zToken, nToken) );
152576      sqlite3_free(pList);
152577      rc = SQLITE_NOMEM;
152578    }
152579  }
152580  if( rc==SQLITE_OK ){
152581    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
152582  }
152583  return rc;
152584}
152585
152586/*
152587** Tokenize the nul-terminated string zText and add all tokens to the
152588** pending-terms hash-table. The docid used is that currently stored in
152589** p->iPrevDocid, and the column is specified by argument iCol.
152590**
152591** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
152592*/
152593static int fts3PendingTermsAdd(
152594  Fts3Table *p,                   /* Table into which text will be inserted */
152595  int iLangid,                    /* Language id to use */
152596  const char *zText,              /* Text of document to be inserted */
152597  int iCol,                       /* Column into which text is being inserted */
152598  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
152599){
152600  int rc;
152601  int iStart = 0;
152602  int iEnd = 0;
152603  int iPos = 0;
152604  int nWord = 0;
152605
152606  char const *zToken;
152607  int nToken = 0;
152608
152609  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
152610  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
152611  sqlite3_tokenizer_cursor *pCsr;
152612  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
152613      const char**,int*,int*,int*,int*);
152614
152615  assert( pTokenizer && pModule );
152616
152617  /* If the user has inserted a NULL value, this function may be called with
152618  ** zText==0. In this case, add zero token entries to the hash table and
152619  ** return early. */
152620  if( zText==0 ){
152621    *pnWord = 0;
152622    return SQLITE_OK;
152623  }
152624
152625  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
152626  if( rc!=SQLITE_OK ){
152627    return rc;
152628  }
152629
152630  xNext = pModule->xNext;
152631  while( SQLITE_OK==rc
152632      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
152633  ){
152634    int i;
152635    if( iPos>=nWord ) nWord = iPos+1;
152636
152637    /* Positions cannot be negative; we use -1 as a terminator internally.
152638    ** Tokens must have a non-zero length.
152639    */
152640    if( iPos<0 || !zToken || nToken<=0 ){
152641      rc = SQLITE_ERROR;
152642      break;
152643    }
152644
152645    /* Add the term to the terms index */
152646    rc = fts3PendingTermsAddOne(
152647        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
152648    );
152649
152650    /* Add the term to each of the prefix indexes that it is not too
152651    ** short for. */
152652    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
152653      struct Fts3Index *pIndex = &p->aIndex[i];
152654      if( nToken<pIndex->nPrefix ) continue;
152655      rc = fts3PendingTermsAddOne(
152656          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
152657      );
152658    }
152659  }
152660
152661  pModule->xClose(pCsr);
152662  *pnWord += nWord;
152663  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
152664}
152665
152666/*
152667** Calling this function indicates that subsequent calls to
152668** fts3PendingTermsAdd() are to add term/position-list pairs for the
152669** contents of the document with docid iDocid.
152670*/
152671static int fts3PendingTermsDocid(
152672  Fts3Table *p,                   /* Full-text table handle */
152673  int bDelete,                    /* True if this op is a delete */
152674  int iLangid,                    /* Language id of row being written */
152675  sqlite_int64 iDocid             /* Docid of row being written */
152676){
152677  assert( iLangid>=0 );
152678  assert( bDelete==1 || bDelete==0 );
152679
152680  /* TODO(shess) Explore whether partially flushing the buffer on
152681  ** forced-flush would provide better performance.  I suspect that if
152682  ** we ordered the doclists by size and flushed the largest until the
152683  ** buffer was half empty, that would let the less frequent terms
152684  ** generate longer doclists.
152685  */
152686  if( iDocid<p->iPrevDocid
152687   || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
152688   || p->iPrevLangid!=iLangid
152689   || p->nPendingData>p->nMaxPendingData
152690  ){
152691    int rc = sqlite3Fts3PendingTermsFlush(p);
152692    if( rc!=SQLITE_OK ) return rc;
152693  }
152694  p->iPrevDocid = iDocid;
152695  p->iPrevLangid = iLangid;
152696  p->bPrevDelete = bDelete;
152697  return SQLITE_OK;
152698}
152699
152700/*
152701** Discard the contents of the pending-terms hash tables.
152702*/
152703SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
152704  int i;
152705  for(i=0; i<p->nIndex; i++){
152706    Fts3HashElem *pElem;
152707    Fts3Hash *pHash = &p->aIndex[i].hPending;
152708    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
152709      PendingList *pList = (PendingList *)fts3HashData(pElem);
152710      fts3PendingListDelete(pList);
152711    }
152712    fts3HashClear(pHash);
152713  }
152714  p->nPendingData = 0;
152715}
152716
152717/*
152718** This function is called by the xUpdate() method as part of an INSERT
152719** operation. It adds entries for each term in the new record to the
152720** pendingTerms hash table.
152721**
152722** Argument apVal is the same as the similarly named argument passed to
152723** fts3InsertData(). Parameter iDocid is the docid of the new row.
152724*/
152725static int fts3InsertTerms(
152726  Fts3Table *p,
152727  int iLangid,
152728  sqlite3_value **apVal,
152729  u32 *aSz
152730){
152731  int i;                          /* Iterator variable */
152732  for(i=2; i<p->nColumn+2; i++){
152733    int iCol = i-2;
152734    if( p->abNotindexed[iCol]==0 ){
152735      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
152736      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
152737      if( rc!=SQLITE_OK ){
152738        return rc;
152739      }
152740      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
152741    }
152742  }
152743  return SQLITE_OK;
152744}
152745
152746/*
152747** This function is called by the xUpdate() method for an INSERT operation.
152748** The apVal parameter is passed a copy of the apVal argument passed by
152749** SQLite to the xUpdate() method. i.e:
152750**
152751**   apVal[0]                Not used for INSERT.
152752**   apVal[1]                rowid
152753**   apVal[2]                Left-most user-defined column
152754**   ...
152755**   apVal[p->nColumn+1]     Right-most user-defined column
152756**   apVal[p->nColumn+2]     Hidden column with same name as table
152757**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
152758**   apVal[p->nColumn+4]     Hidden languageid column
152759*/
152760static int fts3InsertData(
152761  Fts3Table *p,                   /* Full-text table */
152762  sqlite3_value **apVal,          /* Array of values to insert */
152763  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
152764){
152765  int rc;                         /* Return code */
152766  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
152767
152768  if( p->zContentTbl ){
152769    sqlite3_value *pRowid = apVal[p->nColumn+3];
152770    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
152771      pRowid = apVal[1];
152772    }
152773    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
152774      return SQLITE_CONSTRAINT;
152775    }
152776    *piDocid = sqlite3_value_int64(pRowid);
152777    return SQLITE_OK;
152778  }
152779
152780  /* Locate the statement handle used to insert data into the %_content
152781  ** table. The SQL for this statement is:
152782  **
152783  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
152784  **
152785  ** The statement features N '?' variables, where N is the number of user
152786  ** defined columns in the FTS3 table, plus one for the docid field.
152787  */
152788  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
152789  if( rc==SQLITE_OK && p->zLanguageid ){
152790    rc = sqlite3_bind_int(
152791        pContentInsert, p->nColumn+2,
152792        sqlite3_value_int(apVal[p->nColumn+4])
152793    );
152794  }
152795  if( rc!=SQLITE_OK ) return rc;
152796
152797  /* There is a quirk here. The users INSERT statement may have specified
152798  ** a value for the "rowid" field, for the "docid" field, or for both.
152799  ** Which is a problem, since "rowid" and "docid" are aliases for the
152800  ** same value. For example:
152801  **
152802  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
152803  **
152804  ** In FTS3, this is an error. It is an error to specify non-NULL values
152805  ** for both docid and some other rowid alias.
152806  */
152807  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
152808    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
152809     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
152810    ){
152811      /* A rowid/docid conflict. */
152812      return SQLITE_ERROR;
152813    }
152814    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
152815    if( rc!=SQLITE_OK ) return rc;
152816  }
152817
152818  /* Execute the statement to insert the record. Set *piDocid to the
152819  ** new docid value.
152820  */
152821  sqlite3_step(pContentInsert);
152822  rc = sqlite3_reset(pContentInsert);
152823
152824  *piDocid = sqlite3_last_insert_rowid(p->db);
152825  return rc;
152826}
152827
152828
152829
152830/*
152831** Remove all data from the FTS3 table. Clear the hash table containing
152832** pending terms.
152833*/
152834static int fts3DeleteAll(Fts3Table *p, int bContent){
152835  int rc = SQLITE_OK;             /* Return code */
152836
152837  /* Discard the contents of the pending-terms hash table. */
152838  sqlite3Fts3PendingTermsClear(p);
152839
152840  /* Delete everything from the shadow tables. Except, leave %_content as
152841  ** is if bContent is false.  */
152842  assert( p->zContentTbl==0 || bContent==0 );
152843  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
152844  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
152845  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
152846  if( p->bHasDocsize ){
152847    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
152848  }
152849  if( p->bHasStat ){
152850    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
152851  }
152852  return rc;
152853}
152854
152855/*
152856**
152857*/
152858static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
152859  int iLangid = 0;
152860  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
152861  return iLangid;
152862}
152863
152864/*
152865** The first element in the apVal[] array is assumed to contain the docid
152866** (an integer) of a row about to be deleted. Remove all terms from the
152867** full-text index.
152868*/
152869static void fts3DeleteTerms(
152870  int *pRC,               /* Result code */
152871  Fts3Table *p,           /* The FTS table to delete from */
152872  sqlite3_value *pRowid,  /* The docid to be deleted */
152873  u32 *aSz,               /* Sizes of deleted document written here */
152874  int *pbFound            /* OUT: Set to true if row really does exist */
152875){
152876  int rc;
152877  sqlite3_stmt *pSelect;
152878
152879  assert( *pbFound==0 );
152880  if( *pRC ) return;
152881  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
152882  if( rc==SQLITE_OK ){
152883    if( SQLITE_ROW==sqlite3_step(pSelect) ){
152884      int i;
152885      int iLangid = langidFromSelect(p, pSelect);
152886      i64 iDocid = sqlite3_column_int64(pSelect, 0);
152887      rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
152888      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
152889        int iCol = i-1;
152890        if( p->abNotindexed[iCol]==0 ){
152891          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
152892          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
152893          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
152894        }
152895      }
152896      if( rc!=SQLITE_OK ){
152897        sqlite3_reset(pSelect);
152898        *pRC = rc;
152899        return;
152900      }
152901      *pbFound = 1;
152902    }
152903    rc = sqlite3_reset(pSelect);
152904  }else{
152905    sqlite3_reset(pSelect);
152906  }
152907  *pRC = rc;
152908}
152909
152910/*
152911** Forward declaration to account for the circular dependency between
152912** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
152913*/
152914static int fts3SegmentMerge(Fts3Table *, int, int, int);
152915
152916/*
152917** This function allocates a new level iLevel index in the segdir table.
152918** Usually, indexes are allocated within a level sequentially starting
152919** with 0, so the allocated index is one greater than the value returned
152920** by:
152921**
152922**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
152923**
152924** However, if there are already FTS3_MERGE_COUNT indexes at the requested
152925** level, they are merged into a single level (iLevel+1) segment and the
152926** allocated index is 0.
152927**
152928** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
152929** returned. Otherwise, an SQLite error code is returned.
152930*/
152931static int fts3AllocateSegdirIdx(
152932  Fts3Table *p,
152933  int iLangid,                    /* Language id */
152934  int iIndex,                     /* Index for p->aIndex */
152935  int iLevel,
152936  int *piIdx
152937){
152938  int rc;                         /* Return Code */
152939  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
152940  int iNext = 0;                  /* Result of query pNextIdx */
152941
152942  assert( iLangid>=0 );
152943  assert( p->nIndex>=1 );
152944
152945  /* Set variable iNext to the next available segdir index at level iLevel. */
152946  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
152947  if( rc==SQLITE_OK ){
152948    sqlite3_bind_int64(
152949        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
152950    );
152951    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
152952      iNext = sqlite3_column_int(pNextIdx, 0);
152953    }
152954    rc = sqlite3_reset(pNextIdx);
152955  }
152956
152957  if( rc==SQLITE_OK ){
152958    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
152959    ** full, merge all segments in level iLevel into a single iLevel+1
152960    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
152961    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
152962    */
152963    if( iNext>=FTS3_MERGE_COUNT ){
152964      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
152965      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
152966      *piIdx = 0;
152967    }else{
152968      *piIdx = iNext;
152969    }
152970  }
152971
152972  return rc;
152973}
152974
152975/*
152976** The %_segments table is declared as follows:
152977**
152978**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
152979**
152980** This function reads data from a single row of the %_segments table. The
152981** specific row is identified by the iBlockid parameter. If paBlob is not
152982** NULL, then a buffer is allocated using sqlite3_malloc() and populated
152983** with the contents of the blob stored in the "block" column of the
152984** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
152985** to the size of the blob in bytes before returning.
152986**
152987** If an error occurs, or the table does not contain the specified row,
152988** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
152989** paBlob is non-NULL, then it is the responsibility of the caller to
152990** eventually free the returned buffer.
152991**
152992** This function may leave an open sqlite3_blob* handle in the
152993** Fts3Table.pSegments variable. This handle is reused by subsequent calls
152994** to this function. The handle may be closed by calling the
152995** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
152996** performance improvement, but the blob handle should always be closed
152997** before control is returned to the user (to prevent a lock being held
152998** on the database file for longer than necessary). Thus, any virtual table
152999** method (xFilter etc.) that may directly or indirectly call this function
153000** must call sqlite3Fts3SegmentsClose() before returning.
153001*/
153002SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
153003  Fts3Table *p,                   /* FTS3 table handle */
153004  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
153005  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
153006  int *pnBlob,                    /* OUT: Size of blob data */
153007  int *pnLoad                     /* OUT: Bytes actually loaded */
153008){
153009  int rc;                         /* Return code */
153010
153011  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
153012  assert( pnBlob );
153013
153014  if( p->pSegments ){
153015    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
153016  }else{
153017    if( 0==p->zSegmentsTbl ){
153018      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
153019      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
153020    }
153021    rc = sqlite3_blob_open(
153022       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
153023    );
153024  }
153025
153026  if( rc==SQLITE_OK ){
153027    int nByte = sqlite3_blob_bytes(p->pSegments);
153028    *pnBlob = nByte;
153029    if( paBlob ){
153030      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
153031      if( !aByte ){
153032        rc = SQLITE_NOMEM;
153033      }else{
153034        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
153035          nByte = FTS3_NODE_CHUNKSIZE;
153036          *pnLoad = nByte;
153037        }
153038        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
153039        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
153040        if( rc!=SQLITE_OK ){
153041          sqlite3_free(aByte);
153042          aByte = 0;
153043        }
153044      }
153045      *paBlob = aByte;
153046    }
153047  }
153048
153049  return rc;
153050}
153051
153052/*
153053** Close the blob handle at p->pSegments, if it is open. See comments above
153054** the sqlite3Fts3ReadBlock() function for details.
153055*/
153056SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
153057  sqlite3_blob_close(p->pSegments);
153058  p->pSegments = 0;
153059}
153060
153061static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
153062  int nRead;                      /* Number of bytes to read */
153063  int rc;                         /* Return code */
153064
153065  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
153066  rc = sqlite3_blob_read(
153067      pReader->pBlob,
153068      &pReader->aNode[pReader->nPopulate],
153069      nRead,
153070      pReader->nPopulate
153071  );
153072
153073  if( rc==SQLITE_OK ){
153074    pReader->nPopulate += nRead;
153075    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
153076    if( pReader->nPopulate==pReader->nNode ){
153077      sqlite3_blob_close(pReader->pBlob);
153078      pReader->pBlob = 0;
153079      pReader->nPopulate = 0;
153080    }
153081  }
153082  return rc;
153083}
153084
153085static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
153086  int rc = SQLITE_OK;
153087  assert( !pReader->pBlob
153088       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
153089  );
153090  while( pReader->pBlob && rc==SQLITE_OK
153091     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
153092  ){
153093    rc = fts3SegReaderIncrRead(pReader);
153094  }
153095  return rc;
153096}
153097
153098/*
153099** Set an Fts3SegReader cursor to point at EOF.
153100*/
153101static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
153102  if( !fts3SegReaderIsRootOnly(pSeg) ){
153103    sqlite3_free(pSeg->aNode);
153104    sqlite3_blob_close(pSeg->pBlob);
153105    pSeg->pBlob = 0;
153106  }
153107  pSeg->aNode = 0;
153108}
153109
153110/*
153111** Move the iterator passed as the first argument to the next term in the
153112** segment. If successful, SQLITE_OK is returned. If there is no next term,
153113** SQLITE_DONE. Otherwise, an SQLite error code.
153114*/
153115static int fts3SegReaderNext(
153116  Fts3Table *p,
153117  Fts3SegReader *pReader,
153118  int bIncr
153119){
153120  int rc;                         /* Return code of various sub-routines */
153121  char *pNext;                    /* Cursor variable */
153122  int nPrefix;                    /* Number of bytes in term prefix */
153123  int nSuffix;                    /* Number of bytes in term suffix */
153124
153125  if( !pReader->aDoclist ){
153126    pNext = pReader->aNode;
153127  }else{
153128    pNext = &pReader->aDoclist[pReader->nDoclist];
153129  }
153130
153131  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
153132
153133    if( fts3SegReaderIsPending(pReader) ){
153134      Fts3HashElem *pElem = *(pReader->ppNextElem);
153135      sqlite3_free(pReader->aNode);
153136      pReader->aNode = 0;
153137      if( pElem ){
153138        char *aCopy;
153139        PendingList *pList = (PendingList *)fts3HashData(pElem);
153140        int nCopy = pList->nData+1;
153141        pReader->zTerm = (char *)fts3HashKey(pElem);
153142        pReader->nTerm = fts3HashKeysize(pElem);
153143        aCopy = (char*)sqlite3_malloc(nCopy);
153144        if( !aCopy ) return SQLITE_NOMEM;
153145        memcpy(aCopy, pList->aData, nCopy);
153146        pReader->nNode = pReader->nDoclist = nCopy;
153147        pReader->aNode = pReader->aDoclist = aCopy;
153148        pReader->ppNextElem++;
153149        assert( pReader->aNode );
153150      }
153151      return SQLITE_OK;
153152    }
153153
153154    fts3SegReaderSetEof(pReader);
153155
153156    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
153157    ** blocks have already been traversed.  */
153158    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
153159    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
153160      return SQLITE_OK;
153161    }
153162
153163    rc = sqlite3Fts3ReadBlock(
153164        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
153165        (bIncr ? &pReader->nPopulate : 0)
153166    );
153167    if( rc!=SQLITE_OK ) return rc;
153168    assert( pReader->pBlob==0 );
153169    if( bIncr && pReader->nPopulate<pReader->nNode ){
153170      pReader->pBlob = p->pSegments;
153171      p->pSegments = 0;
153172    }
153173    pNext = pReader->aNode;
153174  }
153175
153176  assert( !fts3SegReaderIsPending(pReader) );
153177
153178  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
153179  if( rc!=SQLITE_OK ) return rc;
153180
153181  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
153182  ** safe (no risk of overread) even if the node data is corrupted. */
153183  pNext += fts3GetVarint32(pNext, &nPrefix);
153184  pNext += fts3GetVarint32(pNext, &nSuffix);
153185  if( nPrefix<0 || nSuffix<=0
153186   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
153187  ){
153188    return FTS_CORRUPT_VTAB;
153189  }
153190
153191  if( nPrefix+nSuffix>pReader->nTermAlloc ){
153192    int nNew = (nPrefix+nSuffix)*2;
153193    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
153194    if( !zNew ){
153195      return SQLITE_NOMEM;
153196    }
153197    pReader->zTerm = zNew;
153198    pReader->nTermAlloc = nNew;
153199  }
153200
153201  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
153202  if( rc!=SQLITE_OK ) return rc;
153203
153204  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
153205  pReader->nTerm = nPrefix+nSuffix;
153206  pNext += nSuffix;
153207  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
153208  pReader->aDoclist = pNext;
153209  pReader->pOffsetList = 0;
153210
153211  /* Check that the doclist does not appear to extend past the end of the
153212  ** b-tree node. And that the final byte of the doclist is 0x00. If either
153213  ** of these statements is untrue, then the data structure is corrupt.
153214  */
153215  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
153216   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
153217  ){
153218    return FTS_CORRUPT_VTAB;
153219  }
153220  return SQLITE_OK;
153221}
153222
153223/*
153224** Set the SegReader to point to the first docid in the doclist associated
153225** with the current term.
153226*/
153227static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
153228  int rc = SQLITE_OK;
153229  assert( pReader->aDoclist );
153230  assert( !pReader->pOffsetList );
153231  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
153232    u8 bEof = 0;
153233    pReader->iDocid = 0;
153234    pReader->nOffsetList = 0;
153235    sqlite3Fts3DoclistPrev(0,
153236        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
153237        &pReader->iDocid, &pReader->nOffsetList, &bEof
153238    );
153239  }else{
153240    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
153241    if( rc==SQLITE_OK ){
153242      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
153243      pReader->pOffsetList = &pReader->aDoclist[n];
153244    }
153245  }
153246  return rc;
153247}
153248
153249/*
153250** Advance the SegReader to point to the next docid in the doclist
153251** associated with the current term.
153252**
153253** If arguments ppOffsetList and pnOffsetList are not NULL, then
153254** *ppOffsetList is set to point to the first column-offset list
153255** in the doclist entry (i.e. immediately past the docid varint).
153256** *pnOffsetList is set to the length of the set of column-offset
153257** lists, not including the nul-terminator byte. For example:
153258*/
153259static int fts3SegReaderNextDocid(
153260  Fts3Table *pTab,
153261  Fts3SegReader *pReader,         /* Reader to advance to next docid */
153262  char **ppOffsetList,            /* OUT: Pointer to current position-list */
153263  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
153264){
153265  int rc = SQLITE_OK;
153266  char *p = pReader->pOffsetList;
153267  char c = 0;
153268
153269  assert( p );
153270
153271  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
153272    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
153273    ** Pending-terms doclists are always built up in ascending order, so
153274    ** we have to iterate through them backwards here. */
153275    u8 bEof = 0;
153276    if( ppOffsetList ){
153277      *ppOffsetList = pReader->pOffsetList;
153278      *pnOffsetList = pReader->nOffsetList - 1;
153279    }
153280    sqlite3Fts3DoclistPrev(0,
153281        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
153282        &pReader->nOffsetList, &bEof
153283    );
153284    if( bEof ){
153285      pReader->pOffsetList = 0;
153286    }else{
153287      pReader->pOffsetList = p;
153288    }
153289  }else{
153290    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
153291
153292    /* Pointer p currently points at the first byte of an offset list. The
153293    ** following block advances it to point one byte past the end of
153294    ** the same offset list. */
153295    while( 1 ){
153296
153297      /* The following line of code (and the "p++" below the while() loop) is
153298      ** normally all that is required to move pointer p to the desired
153299      ** position. The exception is if this node is being loaded from disk
153300      ** incrementally and pointer "p" now points to the first byte past
153301      ** the populated part of pReader->aNode[].
153302      */
153303      while( *p | c ) c = *p++ & 0x80;
153304      assert( *p==0 );
153305
153306      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
153307      rc = fts3SegReaderIncrRead(pReader);
153308      if( rc!=SQLITE_OK ) return rc;
153309    }
153310    p++;
153311
153312    /* If required, populate the output variables with a pointer to and the
153313    ** size of the previous offset-list.
153314    */
153315    if( ppOffsetList ){
153316      *ppOffsetList = pReader->pOffsetList;
153317      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
153318    }
153319
153320    /* List may have been edited in place by fts3EvalNearTrim() */
153321    while( p<pEnd && *p==0 ) p++;
153322
153323    /* If there are no more entries in the doclist, set pOffsetList to
153324    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
153325    ** Fts3SegReader.pOffsetList to point to the next offset list before
153326    ** returning.
153327    */
153328    if( p>=pEnd ){
153329      pReader->pOffsetList = 0;
153330    }else{
153331      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
153332      if( rc==SQLITE_OK ){
153333        sqlite3_int64 iDelta;
153334        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
153335        if( pTab->bDescIdx ){
153336          pReader->iDocid -= iDelta;
153337        }else{
153338          pReader->iDocid += iDelta;
153339        }
153340      }
153341    }
153342  }
153343
153344  return SQLITE_OK;
153345}
153346
153347
153348SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
153349  Fts3Cursor *pCsr,
153350  Fts3MultiSegReader *pMsr,
153351  int *pnOvfl
153352){
153353  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
153354  int nOvfl = 0;
153355  int ii;
153356  int rc = SQLITE_OK;
153357  int pgsz = p->nPgsz;
153358
153359  assert( p->bFts4 );
153360  assert( pgsz>0 );
153361
153362  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
153363    Fts3SegReader *pReader = pMsr->apSegment[ii];
153364    if( !fts3SegReaderIsPending(pReader)
153365     && !fts3SegReaderIsRootOnly(pReader)
153366    ){
153367      sqlite3_int64 jj;
153368      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
153369        int nBlob;
153370        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
153371        if( rc!=SQLITE_OK ) break;
153372        if( (nBlob+35)>pgsz ){
153373          nOvfl += (nBlob + 34)/pgsz;
153374        }
153375      }
153376    }
153377  }
153378  *pnOvfl = nOvfl;
153379  return rc;
153380}
153381
153382/*
153383** Free all allocations associated with the iterator passed as the
153384** second argument.
153385*/
153386SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
153387  if( pReader ){
153388    if( !fts3SegReaderIsPending(pReader) ){
153389      sqlite3_free(pReader->zTerm);
153390    }
153391    if( !fts3SegReaderIsRootOnly(pReader) ){
153392      sqlite3_free(pReader->aNode);
153393    }
153394    sqlite3_blob_close(pReader->pBlob);
153395  }
153396  sqlite3_free(pReader);
153397}
153398
153399/*
153400** Allocate a new SegReader object.
153401*/
153402SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
153403  int iAge,                       /* Segment "age". */
153404  int bLookup,                    /* True for a lookup only */
153405  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
153406  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
153407  sqlite3_int64 iEndBlock,        /* Final block of segment */
153408  const char *zRoot,              /* Buffer containing root node */
153409  int nRoot,                      /* Size of buffer containing root node */
153410  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
153411){
153412  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
153413  int nExtra = 0;                 /* Bytes to allocate segment root node */
153414
153415  assert( iStartLeaf<=iEndLeaf );
153416  if( iStartLeaf==0 ){
153417    nExtra = nRoot + FTS3_NODE_PADDING;
153418  }
153419
153420  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
153421  if( !pReader ){
153422    return SQLITE_NOMEM;
153423  }
153424  memset(pReader, 0, sizeof(Fts3SegReader));
153425  pReader->iIdx = iAge;
153426  pReader->bLookup = bLookup!=0;
153427  pReader->iStartBlock = iStartLeaf;
153428  pReader->iLeafEndBlock = iEndLeaf;
153429  pReader->iEndBlock = iEndBlock;
153430
153431  if( nExtra ){
153432    /* The entire segment is stored in the root node. */
153433    pReader->aNode = (char *)&pReader[1];
153434    pReader->rootOnly = 1;
153435    pReader->nNode = nRoot;
153436    memcpy(pReader->aNode, zRoot, nRoot);
153437    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
153438  }else{
153439    pReader->iCurrentBlock = iStartLeaf-1;
153440  }
153441  *ppReader = pReader;
153442  return SQLITE_OK;
153443}
153444
153445/*
153446** This is a comparison function used as a qsort() callback when sorting
153447** an array of pending terms by term. This occurs as part of flushing
153448** the contents of the pending-terms hash table to the database.
153449*/
153450static int SQLITE_CDECL fts3CompareElemByTerm(
153451  const void *lhs,
153452  const void *rhs
153453){
153454  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
153455  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
153456  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
153457  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
153458
153459  int n = (n1<n2 ? n1 : n2);
153460  int c = memcmp(z1, z2, n);
153461  if( c==0 ){
153462    c = n1 - n2;
153463  }
153464  return c;
153465}
153466
153467/*
153468** This function is used to allocate an Fts3SegReader that iterates through
153469** a subset of the terms stored in the Fts3Table.pendingTerms array.
153470**
153471** If the isPrefixIter parameter is zero, then the returned SegReader iterates
153472** through each term in the pending-terms table. Or, if isPrefixIter is
153473** non-zero, it iterates through each term and its prefixes. For example, if
153474** the pending terms hash table contains the terms "sqlite", "mysql" and
153475** "firebird", then the iterator visits the following 'terms' (in the order
153476** shown):
153477**
153478**   f fi fir fire fireb firebi firebir firebird
153479**   m my mys mysq mysql
153480**   s sq sql sqli sqlit sqlite
153481**
153482** Whereas if isPrefixIter is zero, the terms visited are:
153483**
153484**   firebird mysql sqlite
153485*/
153486SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
153487  Fts3Table *p,                   /* Virtual table handle */
153488  int iIndex,                     /* Index for p->aIndex */
153489  const char *zTerm,              /* Term to search for */
153490  int nTerm,                      /* Size of buffer zTerm */
153491  int bPrefix,                    /* True for a prefix iterator */
153492  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
153493){
153494  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
153495  Fts3HashElem *pE;               /* Iterator variable */
153496  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
153497  int nElem = 0;                  /* Size of array at aElem */
153498  int rc = SQLITE_OK;             /* Return Code */
153499  Fts3Hash *pHash;
153500
153501  pHash = &p->aIndex[iIndex].hPending;
153502  if( bPrefix ){
153503    int nAlloc = 0;               /* Size of allocated array at aElem */
153504
153505    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
153506      char *zKey = (char *)fts3HashKey(pE);
153507      int nKey = fts3HashKeysize(pE);
153508      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
153509        if( nElem==nAlloc ){
153510          Fts3HashElem **aElem2;
153511          nAlloc += 16;
153512          aElem2 = (Fts3HashElem **)sqlite3_realloc(
153513              aElem, nAlloc*sizeof(Fts3HashElem *)
153514          );
153515          if( !aElem2 ){
153516            rc = SQLITE_NOMEM;
153517            nElem = 0;
153518            break;
153519          }
153520          aElem = aElem2;
153521        }
153522
153523        aElem[nElem++] = pE;
153524      }
153525    }
153526
153527    /* If more than one term matches the prefix, sort the Fts3HashElem
153528    ** objects in term order using qsort(). This uses the same comparison
153529    ** callback as is used when flushing terms to disk.
153530    */
153531    if( nElem>1 ){
153532      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
153533    }
153534
153535  }else{
153536    /* The query is a simple term lookup that matches at most one term in
153537    ** the index. All that is required is a straight hash-lookup.
153538    **
153539    ** Because the stack address of pE may be accessed via the aElem pointer
153540    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
153541    ** within this entire function, not just this "else{...}" block.
153542    */
153543    pE = fts3HashFindElem(pHash, zTerm, nTerm);
153544    if( pE ){
153545      aElem = &pE;
153546      nElem = 1;
153547    }
153548  }
153549
153550  if( nElem>0 ){
153551    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
153552    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
153553    if( !pReader ){
153554      rc = SQLITE_NOMEM;
153555    }else{
153556      memset(pReader, 0, nByte);
153557      pReader->iIdx = 0x7FFFFFFF;
153558      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
153559      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
153560    }
153561  }
153562
153563  if( bPrefix ){
153564    sqlite3_free(aElem);
153565  }
153566  *ppReader = pReader;
153567  return rc;
153568}
153569
153570/*
153571** Compare the entries pointed to by two Fts3SegReader structures.
153572** Comparison is as follows:
153573**
153574**   1) EOF is greater than not EOF.
153575**
153576**   2) The current terms (if any) are compared using memcmp(). If one
153577**      term is a prefix of another, the longer term is considered the
153578**      larger.
153579**
153580**   3) By segment age. An older segment is considered larger.
153581*/
153582static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153583  int rc;
153584  if( pLhs->aNode && pRhs->aNode ){
153585    int rc2 = pLhs->nTerm - pRhs->nTerm;
153586    if( rc2<0 ){
153587      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
153588    }else{
153589      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
153590    }
153591    if( rc==0 ){
153592      rc = rc2;
153593    }
153594  }else{
153595    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
153596  }
153597  if( rc==0 ){
153598    rc = pRhs->iIdx - pLhs->iIdx;
153599  }
153600  assert( rc!=0 );
153601  return rc;
153602}
153603
153604/*
153605** A different comparison function for SegReader structures. In this
153606** version, it is assumed that each SegReader points to an entry in
153607** a doclist for identical terms. Comparison is made as follows:
153608**
153609**   1) EOF (end of doclist in this case) is greater than not EOF.
153610**
153611**   2) By current docid.
153612**
153613**   3) By segment age. An older segment is considered larger.
153614*/
153615static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153616  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
153617  if( rc==0 ){
153618    if( pLhs->iDocid==pRhs->iDocid ){
153619      rc = pRhs->iIdx - pLhs->iIdx;
153620    }else{
153621      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
153622    }
153623  }
153624  assert( pLhs->aNode && pRhs->aNode );
153625  return rc;
153626}
153627static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153628  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
153629  if( rc==0 ){
153630    if( pLhs->iDocid==pRhs->iDocid ){
153631      rc = pRhs->iIdx - pLhs->iIdx;
153632    }else{
153633      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
153634    }
153635  }
153636  assert( pLhs->aNode && pRhs->aNode );
153637  return rc;
153638}
153639
153640/*
153641** Compare the term that the Fts3SegReader object passed as the first argument
153642** points to with the term specified by arguments zTerm and nTerm.
153643**
153644** If the pSeg iterator is already at EOF, return 0. Otherwise, return
153645** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
153646** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
153647*/
153648static int fts3SegReaderTermCmp(
153649  Fts3SegReader *pSeg,            /* Segment reader object */
153650  const char *zTerm,              /* Term to compare to */
153651  int nTerm                       /* Size of term zTerm in bytes */
153652){
153653  int res = 0;
153654  if( pSeg->aNode ){
153655    if( pSeg->nTerm>nTerm ){
153656      res = memcmp(pSeg->zTerm, zTerm, nTerm);
153657    }else{
153658      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
153659    }
153660    if( res==0 ){
153661      res = pSeg->nTerm-nTerm;
153662    }
153663  }
153664  return res;
153665}
153666
153667/*
153668** Argument apSegment is an array of nSegment elements. It is known that
153669** the final (nSegment-nSuspect) members are already in sorted order
153670** (according to the comparison function provided). This function shuffles
153671** the array around until all entries are in sorted order.
153672*/
153673static void fts3SegReaderSort(
153674  Fts3SegReader **apSegment,                     /* Array to sort entries of */
153675  int nSegment,                                  /* Size of apSegment array */
153676  int nSuspect,                                  /* Unsorted entry count */
153677  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
153678){
153679  int i;                          /* Iterator variable */
153680
153681  assert( nSuspect<=nSegment );
153682
153683  if( nSuspect==nSegment ) nSuspect--;
153684  for(i=nSuspect-1; i>=0; i--){
153685    int j;
153686    for(j=i; j<(nSegment-1); j++){
153687      Fts3SegReader *pTmp;
153688      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
153689      pTmp = apSegment[j+1];
153690      apSegment[j+1] = apSegment[j];
153691      apSegment[j] = pTmp;
153692    }
153693  }
153694
153695#ifndef NDEBUG
153696  /* Check that the list really is sorted now. */
153697  for(i=0; i<(nSuspect-1); i++){
153698    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
153699  }
153700#endif
153701}
153702
153703/*
153704** Insert a record into the %_segments table.
153705*/
153706static int fts3WriteSegment(
153707  Fts3Table *p,                   /* Virtual table handle */
153708  sqlite3_int64 iBlock,           /* Block id for new block */
153709  char *z,                        /* Pointer to buffer containing block data */
153710  int n                           /* Size of buffer z in bytes */
153711){
153712  sqlite3_stmt *pStmt;
153713  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
153714  if( rc==SQLITE_OK ){
153715    sqlite3_bind_int64(pStmt, 1, iBlock);
153716    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
153717    sqlite3_step(pStmt);
153718    rc = sqlite3_reset(pStmt);
153719  }
153720  return rc;
153721}
153722
153723/*
153724** Find the largest relative level number in the table. If successful, set
153725** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
153726** set *pnMax to zero and return an SQLite error code.
153727*/
153728SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
153729  int rc;
153730  int mxLevel = 0;
153731  sqlite3_stmt *pStmt = 0;
153732
153733  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
153734  if( rc==SQLITE_OK ){
153735    if( SQLITE_ROW==sqlite3_step(pStmt) ){
153736      mxLevel = sqlite3_column_int(pStmt, 0);
153737    }
153738    rc = sqlite3_reset(pStmt);
153739  }
153740  *pnMax = mxLevel;
153741  return rc;
153742}
153743
153744/*
153745** Insert a record into the %_segdir table.
153746*/
153747static int fts3WriteSegdir(
153748  Fts3Table *p,                   /* Virtual table handle */
153749  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
153750  int iIdx,                       /* Value for "idx" field */
153751  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
153752  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
153753  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
153754  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
153755  char *zRoot,                    /* Blob value for "root" field */
153756  int nRoot                       /* Number of bytes in buffer zRoot */
153757){
153758  sqlite3_stmt *pStmt;
153759  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
153760  if( rc==SQLITE_OK ){
153761    sqlite3_bind_int64(pStmt, 1, iLevel);
153762    sqlite3_bind_int(pStmt, 2, iIdx);
153763    sqlite3_bind_int64(pStmt, 3, iStartBlock);
153764    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
153765    if( nLeafData==0 ){
153766      sqlite3_bind_int64(pStmt, 5, iEndBlock);
153767    }else{
153768      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
153769      if( !zEnd ) return SQLITE_NOMEM;
153770      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
153771    }
153772    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
153773    sqlite3_step(pStmt);
153774    rc = sqlite3_reset(pStmt);
153775  }
153776  return rc;
153777}
153778
153779/*
153780** Return the size of the common prefix (if any) shared by zPrev and
153781** zNext, in bytes. For example,
153782**
153783**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
153784**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
153785**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
153786*/
153787static int fts3PrefixCompress(
153788  const char *zPrev,              /* Buffer containing previous term */
153789  int nPrev,                      /* Size of buffer zPrev in bytes */
153790  const char *zNext,              /* Buffer containing next term */
153791  int nNext                       /* Size of buffer zNext in bytes */
153792){
153793  int n;
153794  UNUSED_PARAMETER(nNext);
153795  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
153796  return n;
153797}
153798
153799/*
153800** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
153801** (according to memcmp) than the previous term.
153802*/
153803static int fts3NodeAddTerm(
153804  Fts3Table *p,                   /* Virtual table handle */
153805  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
153806  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
153807  const char *zTerm,              /* Pointer to buffer containing term */
153808  int nTerm                       /* Size of term in bytes */
153809){
153810  SegmentNode *pTree = *ppTree;
153811  int rc;
153812  SegmentNode *pNew;
153813
153814  /* First try to append the term to the current node. Return early if
153815  ** this is possible.
153816  */
153817  if( pTree ){
153818    int nData = pTree->nData;     /* Current size of node in bytes */
153819    int nReq = nData;             /* Required space after adding zTerm */
153820    int nPrefix;                  /* Number of bytes of prefix compression */
153821    int nSuffix;                  /* Suffix length */
153822
153823    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
153824    nSuffix = nTerm-nPrefix;
153825
153826    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
153827    if( nReq<=p->nNodeSize || !pTree->zTerm ){
153828
153829      if( nReq>p->nNodeSize ){
153830        /* An unusual case: this is the first term to be added to the node
153831        ** and the static node buffer (p->nNodeSize bytes) is not large
153832        ** enough. Use a separately malloced buffer instead This wastes
153833        ** p->nNodeSize bytes, but since this scenario only comes about when
153834        ** the database contain two terms that share a prefix of almost 2KB,
153835        ** this is not expected to be a serious problem.
153836        */
153837        assert( pTree->aData==(char *)&pTree[1] );
153838        pTree->aData = (char *)sqlite3_malloc(nReq);
153839        if( !pTree->aData ){
153840          return SQLITE_NOMEM;
153841        }
153842      }
153843
153844      if( pTree->zTerm ){
153845        /* There is no prefix-length field for first term in a node */
153846        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
153847      }
153848
153849      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
153850      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
153851      pTree->nData = nData + nSuffix;
153852      pTree->nEntry++;
153853
153854      if( isCopyTerm ){
153855        if( pTree->nMalloc<nTerm ){
153856          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
153857          if( !zNew ){
153858            return SQLITE_NOMEM;
153859          }
153860          pTree->nMalloc = nTerm*2;
153861          pTree->zMalloc = zNew;
153862        }
153863        pTree->zTerm = pTree->zMalloc;
153864        memcpy(pTree->zTerm, zTerm, nTerm);
153865        pTree->nTerm = nTerm;
153866      }else{
153867        pTree->zTerm = (char *)zTerm;
153868        pTree->nTerm = nTerm;
153869      }
153870      return SQLITE_OK;
153871    }
153872  }
153873
153874  /* If control flows to here, it was not possible to append zTerm to the
153875  ** current node. Create a new node (a right-sibling of the current node).
153876  ** If this is the first node in the tree, the term is added to it.
153877  **
153878  ** Otherwise, the term is not added to the new node, it is left empty for
153879  ** now. Instead, the term is inserted into the parent of pTree. If pTree
153880  ** has no parent, one is created here.
153881  */
153882  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
153883  if( !pNew ){
153884    return SQLITE_NOMEM;
153885  }
153886  memset(pNew, 0, sizeof(SegmentNode));
153887  pNew->nData = 1 + FTS3_VARINT_MAX;
153888  pNew->aData = (char *)&pNew[1];
153889
153890  if( pTree ){
153891    SegmentNode *pParent = pTree->pParent;
153892    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
153893    if( pTree->pParent==0 ){
153894      pTree->pParent = pParent;
153895    }
153896    pTree->pRight = pNew;
153897    pNew->pLeftmost = pTree->pLeftmost;
153898    pNew->pParent = pParent;
153899    pNew->zMalloc = pTree->zMalloc;
153900    pNew->nMalloc = pTree->nMalloc;
153901    pTree->zMalloc = 0;
153902  }else{
153903    pNew->pLeftmost = pNew;
153904    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
153905  }
153906
153907  *ppTree = pNew;
153908  return rc;
153909}
153910
153911/*
153912** Helper function for fts3NodeWrite().
153913*/
153914static int fts3TreeFinishNode(
153915  SegmentNode *pTree,
153916  int iHeight,
153917  sqlite3_int64 iLeftChild
153918){
153919  int nStart;
153920  assert( iHeight>=1 && iHeight<128 );
153921  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
153922  pTree->aData[nStart] = (char)iHeight;
153923  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
153924  return nStart;
153925}
153926
153927/*
153928** Write the buffer for the segment node pTree and all of its peers to the
153929** database. Then call this function recursively to write the parent of
153930** pTree and its peers to the database.
153931**
153932** Except, if pTree is a root node, do not write it to the database. Instead,
153933** set output variables *paRoot and *pnRoot to contain the root node.
153934**
153935** If successful, SQLITE_OK is returned and output variable *piLast is
153936** set to the largest blockid written to the database (or zero if no
153937** blocks were written to the db). Otherwise, an SQLite error code is
153938** returned.
153939*/
153940static int fts3NodeWrite(
153941  Fts3Table *p,                   /* Virtual table handle */
153942  SegmentNode *pTree,             /* SegmentNode handle */
153943  int iHeight,                    /* Height of this node in tree */
153944  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
153945  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
153946  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
153947  char **paRoot,                  /* OUT: Data for root node */
153948  int *pnRoot                     /* OUT: Size of root node in bytes */
153949){
153950  int rc = SQLITE_OK;
153951
153952  if( !pTree->pParent ){
153953    /* Root node of the tree. */
153954    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
153955    *piLast = iFree-1;
153956    *pnRoot = pTree->nData - nStart;
153957    *paRoot = &pTree->aData[nStart];
153958  }else{
153959    SegmentNode *pIter;
153960    sqlite3_int64 iNextFree = iFree;
153961    sqlite3_int64 iNextLeaf = iLeaf;
153962    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
153963      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
153964      int nWrite = pIter->nData - nStart;
153965
153966      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
153967      iNextFree++;
153968      iNextLeaf += (pIter->nEntry+1);
153969    }
153970    if( rc==SQLITE_OK ){
153971      assert( iNextLeaf==iFree );
153972      rc = fts3NodeWrite(
153973          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
153974      );
153975    }
153976  }
153977
153978  return rc;
153979}
153980
153981/*
153982** Free all memory allocations associated with the tree pTree.
153983*/
153984static void fts3NodeFree(SegmentNode *pTree){
153985  if( pTree ){
153986    SegmentNode *p = pTree->pLeftmost;
153987    fts3NodeFree(p->pParent);
153988    while( p ){
153989      SegmentNode *pRight = p->pRight;
153990      if( p->aData!=(char *)&p[1] ){
153991        sqlite3_free(p->aData);
153992      }
153993      assert( pRight==0 || p->zMalloc==0 );
153994      sqlite3_free(p->zMalloc);
153995      sqlite3_free(p);
153996      p = pRight;
153997    }
153998  }
153999}
154000
154001/*
154002** Add a term to the segment being constructed by the SegmentWriter object
154003** *ppWriter. When adding the first term to a segment, *ppWriter should
154004** be passed NULL. This function will allocate a new SegmentWriter object
154005** and return it via the input/output variable *ppWriter in this case.
154006**
154007** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
154008*/
154009static int fts3SegWriterAdd(
154010  Fts3Table *p,                   /* Virtual table handle */
154011  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
154012  int isCopyTerm,                 /* True if buffer zTerm must be copied */
154013  const char *zTerm,              /* Pointer to buffer containing term */
154014  int nTerm,                      /* Size of term in bytes */
154015  const char *aDoclist,           /* Pointer to buffer containing doclist */
154016  int nDoclist                    /* Size of doclist in bytes */
154017){
154018  int nPrefix;                    /* Size of term prefix in bytes */
154019  int nSuffix;                    /* Size of term suffix in bytes */
154020  int nReq;                       /* Number of bytes required on leaf page */
154021  int nData;
154022  SegmentWriter *pWriter = *ppWriter;
154023
154024  if( !pWriter ){
154025    int rc;
154026    sqlite3_stmt *pStmt;
154027
154028    /* Allocate the SegmentWriter structure */
154029    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
154030    if( !pWriter ) return SQLITE_NOMEM;
154031    memset(pWriter, 0, sizeof(SegmentWriter));
154032    *ppWriter = pWriter;
154033
154034    /* Allocate a buffer in which to accumulate data */
154035    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
154036    if( !pWriter->aData ) return SQLITE_NOMEM;
154037    pWriter->nSize = p->nNodeSize;
154038
154039    /* Find the next free blockid in the %_segments table */
154040    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
154041    if( rc!=SQLITE_OK ) return rc;
154042    if( SQLITE_ROW==sqlite3_step(pStmt) ){
154043      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
154044      pWriter->iFirst = pWriter->iFree;
154045    }
154046    rc = sqlite3_reset(pStmt);
154047    if( rc!=SQLITE_OK ) return rc;
154048  }
154049  nData = pWriter->nData;
154050
154051  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
154052  nSuffix = nTerm-nPrefix;
154053
154054  /* Figure out how many bytes are required by this new entry */
154055  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
154056    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
154057    nSuffix +                               /* Term suffix */
154058    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
154059    nDoclist;                               /* Doclist data */
154060
154061  if( nData>0 && nData+nReq>p->nNodeSize ){
154062    int rc;
154063
154064    /* The current leaf node is full. Write it out to the database. */
154065    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
154066    if( rc!=SQLITE_OK ) return rc;
154067    p->nLeafAdd++;
154068
154069    /* Add the current term to the interior node tree. The term added to
154070    ** the interior tree must:
154071    **
154072    **   a) be greater than the largest term on the leaf node just written
154073    **      to the database (still available in pWriter->zTerm), and
154074    **
154075    **   b) be less than or equal to the term about to be added to the new
154076    **      leaf node (zTerm/nTerm).
154077    **
154078    ** In other words, it must be the prefix of zTerm 1 byte longer than
154079    ** the common prefix (if any) of zTerm and pWriter->zTerm.
154080    */
154081    assert( nPrefix<nTerm );
154082    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
154083    if( rc!=SQLITE_OK ) return rc;
154084
154085    nData = 0;
154086    pWriter->nTerm = 0;
154087
154088    nPrefix = 0;
154089    nSuffix = nTerm;
154090    nReq = 1 +                              /* varint containing prefix size */
154091      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
154092      nTerm +                               /* Term suffix */
154093      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
154094      nDoclist;                             /* Doclist data */
154095  }
154096
154097  /* Increase the total number of bytes written to account for the new entry. */
154098  pWriter->nLeafData += nReq;
154099
154100  /* If the buffer currently allocated is too small for this entry, realloc
154101  ** the buffer to make it large enough.
154102  */
154103  if( nReq>pWriter->nSize ){
154104    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
154105    if( !aNew ) return SQLITE_NOMEM;
154106    pWriter->aData = aNew;
154107    pWriter->nSize = nReq;
154108  }
154109  assert( nData+nReq<=pWriter->nSize );
154110
154111  /* Append the prefix-compressed term and doclist to the buffer. */
154112  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
154113  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
154114  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
154115  nData += nSuffix;
154116  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
154117  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
154118  pWriter->nData = nData + nDoclist;
154119
154120  /* Save the current term so that it can be used to prefix-compress the next.
154121  ** If the isCopyTerm parameter is true, then the buffer pointed to by
154122  ** zTerm is transient, so take a copy of the term data. Otherwise, just
154123  ** store a copy of the pointer.
154124  */
154125  if( isCopyTerm ){
154126    if( nTerm>pWriter->nMalloc ){
154127      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
154128      if( !zNew ){
154129        return SQLITE_NOMEM;
154130      }
154131      pWriter->nMalloc = nTerm*2;
154132      pWriter->zMalloc = zNew;
154133      pWriter->zTerm = zNew;
154134    }
154135    assert( pWriter->zTerm==pWriter->zMalloc );
154136    memcpy(pWriter->zTerm, zTerm, nTerm);
154137  }else{
154138    pWriter->zTerm = (char *)zTerm;
154139  }
154140  pWriter->nTerm = nTerm;
154141
154142  return SQLITE_OK;
154143}
154144
154145/*
154146** Flush all data associated with the SegmentWriter object pWriter to the
154147** database. This function must be called after all terms have been added
154148** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
154149** returned. Otherwise, an SQLite error code.
154150*/
154151static int fts3SegWriterFlush(
154152  Fts3Table *p,                   /* Virtual table handle */
154153  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
154154  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
154155  int iIdx                        /* Value for 'idx' column of %_segdir */
154156){
154157  int rc;                         /* Return code */
154158  if( pWriter->pTree ){
154159    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
154160    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
154161    char *zRoot = NULL;           /* Pointer to buffer containing root node */
154162    int nRoot = 0;                /* Size of buffer zRoot */
154163
154164    iLastLeaf = pWriter->iFree;
154165    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
154166    if( rc==SQLITE_OK ){
154167      rc = fts3NodeWrite(p, pWriter->pTree, 1,
154168          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
154169    }
154170    if( rc==SQLITE_OK ){
154171      rc = fts3WriteSegdir(p, iLevel, iIdx,
154172          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
154173    }
154174  }else{
154175    /* The entire tree fits on the root node. Write it to the segdir table. */
154176    rc = fts3WriteSegdir(p, iLevel, iIdx,
154177        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
154178  }
154179  p->nLeafAdd++;
154180  return rc;
154181}
154182
154183/*
154184** Release all memory held by the SegmentWriter object passed as the
154185** first argument.
154186*/
154187static void fts3SegWriterFree(SegmentWriter *pWriter){
154188  if( pWriter ){
154189    sqlite3_free(pWriter->aData);
154190    sqlite3_free(pWriter->zMalloc);
154191    fts3NodeFree(pWriter->pTree);
154192    sqlite3_free(pWriter);
154193  }
154194}
154195
154196/*
154197** The first value in the apVal[] array is assumed to contain an integer.
154198** This function tests if there exist any documents with docid values that
154199** are different from that integer. i.e. if deleting the document with docid
154200** pRowid would mean the FTS3 table were empty.
154201**
154202** If successful, *pisEmpty is set to true if the table is empty except for
154203** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
154204** error occurs, an SQLite error code is returned.
154205*/
154206static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
154207  sqlite3_stmt *pStmt;
154208  int rc;
154209  if( p->zContentTbl ){
154210    /* If using the content=xxx option, assume the table is never empty */
154211    *pisEmpty = 0;
154212    rc = SQLITE_OK;
154213  }else{
154214    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
154215    if( rc==SQLITE_OK ){
154216      if( SQLITE_ROW==sqlite3_step(pStmt) ){
154217        *pisEmpty = sqlite3_column_int(pStmt, 0);
154218      }
154219      rc = sqlite3_reset(pStmt);
154220    }
154221  }
154222  return rc;
154223}
154224
154225/*
154226** Set *pnMax to the largest segment level in the database for the index
154227** iIndex.
154228**
154229** Segment levels are stored in the 'level' column of the %_segdir table.
154230**
154231** Return SQLITE_OK if successful, or an SQLite error code if not.
154232*/
154233static int fts3SegmentMaxLevel(
154234  Fts3Table *p,
154235  int iLangid,
154236  int iIndex,
154237  sqlite3_int64 *pnMax
154238){
154239  sqlite3_stmt *pStmt;
154240  int rc;
154241  assert( iIndex>=0 && iIndex<p->nIndex );
154242
154243  /* Set pStmt to the compiled version of:
154244  **
154245  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
154246  **
154247  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
154248  */
154249  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
154250  if( rc!=SQLITE_OK ) return rc;
154251  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
154252  sqlite3_bind_int64(pStmt, 2,
154253      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
154254  );
154255  if( SQLITE_ROW==sqlite3_step(pStmt) ){
154256    *pnMax = sqlite3_column_int64(pStmt, 0);
154257  }
154258  return sqlite3_reset(pStmt);
154259}
154260
154261/*
154262** iAbsLevel is an absolute level that may be assumed to exist within
154263** the database. This function checks if it is the largest level number
154264** within its index. Assuming no error occurs, *pbMax is set to 1 if
154265** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
154266** is returned. If an error occurs, an error code is returned and the
154267** final value of *pbMax is undefined.
154268*/
154269static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
154270
154271  /* Set pStmt to the compiled version of:
154272  **
154273  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
154274  **
154275  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
154276  */
154277  sqlite3_stmt *pStmt;
154278  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
154279  if( rc!=SQLITE_OK ) return rc;
154280  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
154281  sqlite3_bind_int64(pStmt, 2,
154282      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
154283  );
154284
154285  *pbMax = 0;
154286  if( SQLITE_ROW==sqlite3_step(pStmt) ){
154287    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
154288  }
154289  return sqlite3_reset(pStmt);
154290}
154291
154292/*
154293** Delete all entries in the %_segments table associated with the segment
154294** opened with seg-reader pSeg. This function does not affect the contents
154295** of the %_segdir table.
154296*/
154297static int fts3DeleteSegment(
154298  Fts3Table *p,                   /* FTS table handle */
154299  Fts3SegReader *pSeg             /* Segment to delete */
154300){
154301  int rc = SQLITE_OK;             /* Return code */
154302  if( pSeg->iStartBlock ){
154303    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
154304    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
154305    if( rc==SQLITE_OK ){
154306      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
154307      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
154308      sqlite3_step(pDelete);
154309      rc = sqlite3_reset(pDelete);
154310    }
154311  }
154312  return rc;
154313}
154314
154315/*
154316** This function is used after merging multiple segments into a single large
154317** segment to delete the old, now redundant, segment b-trees. Specifically,
154318** it:
154319**
154320**   1) Deletes all %_segments entries for the segments associated with
154321**      each of the SegReader objects in the array passed as the third
154322**      argument, and
154323**
154324**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
154325**      entries regardless of level if (iLevel<0).
154326**
154327** SQLITE_OK is returned if successful, otherwise an SQLite error code.
154328*/
154329static int fts3DeleteSegdir(
154330  Fts3Table *p,                   /* Virtual table handle */
154331  int iLangid,                    /* Language id */
154332  int iIndex,                     /* Index for p->aIndex */
154333  int iLevel,                     /* Level of %_segdir entries to delete */
154334  Fts3SegReader **apSegment,      /* Array of SegReader objects */
154335  int nReader                     /* Size of array apSegment */
154336){
154337  int rc = SQLITE_OK;             /* Return Code */
154338  int i;                          /* Iterator variable */
154339  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
154340
154341  for(i=0; rc==SQLITE_OK && i<nReader; i++){
154342    rc = fts3DeleteSegment(p, apSegment[i]);
154343  }
154344  if( rc!=SQLITE_OK ){
154345    return rc;
154346  }
154347
154348  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
154349  if( iLevel==FTS3_SEGCURSOR_ALL ){
154350    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
154351    if( rc==SQLITE_OK ){
154352      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
154353      sqlite3_bind_int64(pDelete, 2,
154354          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
154355      );
154356    }
154357  }else{
154358    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
154359    if( rc==SQLITE_OK ){
154360      sqlite3_bind_int64(
154361          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
154362      );
154363    }
154364  }
154365
154366  if( rc==SQLITE_OK ){
154367    sqlite3_step(pDelete);
154368    rc = sqlite3_reset(pDelete);
154369  }
154370
154371  return rc;
154372}
154373
154374/*
154375** When this function is called, buffer *ppList (size *pnList bytes) contains
154376** a position list that may (or may not) feature multiple columns. This
154377** function adjusts the pointer *ppList and the length *pnList so that they
154378** identify the subset of the position list that corresponds to column iCol.
154379**
154380** If there are no entries in the input position list for column iCol, then
154381** *pnList is set to zero before returning.
154382**
154383** If parameter bZero is non-zero, then any part of the input list following
154384** the end of the output list is zeroed before returning.
154385*/
154386static void fts3ColumnFilter(
154387  int iCol,                       /* Column to filter on */
154388  int bZero,                      /* Zero out anything following *ppList */
154389  char **ppList,                  /* IN/OUT: Pointer to position list */
154390  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
154391){
154392  char *pList = *ppList;
154393  int nList = *pnList;
154394  char *pEnd = &pList[nList];
154395  int iCurrent = 0;
154396  char *p = pList;
154397
154398  assert( iCol>=0 );
154399  while( 1 ){
154400    char c = 0;
154401    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
154402
154403    if( iCol==iCurrent ){
154404      nList = (int)(p - pList);
154405      break;
154406    }
154407
154408    nList -= (int)(p - pList);
154409    pList = p;
154410    if( nList==0 ){
154411      break;
154412    }
154413    p = &pList[1];
154414    p += fts3GetVarint32(p, &iCurrent);
154415  }
154416
154417  if( bZero && &pList[nList]!=pEnd ){
154418    memset(&pList[nList], 0, pEnd - &pList[nList]);
154419  }
154420  *ppList = pList;
154421  *pnList = nList;
154422}
154423
154424/*
154425** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
154426** existing data). Grow the buffer if required.
154427**
154428** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
154429** trying to resize the buffer, return SQLITE_NOMEM.
154430*/
154431static int fts3MsrBufferData(
154432  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
154433  char *pList,
154434  int nList
154435){
154436  if( nList>pMsr->nBuffer ){
154437    char *pNew;
154438    pMsr->nBuffer = nList*2;
154439    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
154440    if( !pNew ) return SQLITE_NOMEM;
154441    pMsr->aBuffer = pNew;
154442  }
154443
154444  memcpy(pMsr->aBuffer, pList, nList);
154445  return SQLITE_OK;
154446}
154447
154448SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
154449  Fts3Table *p,                   /* Virtual table handle */
154450  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
154451  sqlite3_int64 *piDocid,         /* OUT: Docid value */
154452  char **paPoslist,               /* OUT: Pointer to position list */
154453  int *pnPoslist                  /* OUT: Size of position list in bytes */
154454){
154455  int nMerge = pMsr->nAdvance;
154456  Fts3SegReader **apSegment = pMsr->apSegment;
154457  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154458    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154459  );
154460
154461  if( nMerge==0 ){
154462    *paPoslist = 0;
154463    return SQLITE_OK;
154464  }
154465
154466  while( 1 ){
154467    Fts3SegReader *pSeg;
154468    pSeg = pMsr->apSegment[0];
154469
154470    if( pSeg->pOffsetList==0 ){
154471      *paPoslist = 0;
154472      break;
154473    }else{
154474      int rc;
154475      char *pList;
154476      int nList;
154477      int j;
154478      sqlite3_int64 iDocid = apSegment[0]->iDocid;
154479
154480      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
154481      j = 1;
154482      while( rc==SQLITE_OK
154483        && j<nMerge
154484        && apSegment[j]->pOffsetList
154485        && apSegment[j]->iDocid==iDocid
154486      ){
154487        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
154488        j++;
154489      }
154490      if( rc!=SQLITE_OK ) return rc;
154491      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
154492
154493      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
154494        rc = fts3MsrBufferData(pMsr, pList, nList+1);
154495        if( rc!=SQLITE_OK ) return rc;
154496        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
154497        pList = pMsr->aBuffer;
154498      }
154499
154500      if( pMsr->iColFilter>=0 ){
154501        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
154502      }
154503
154504      if( nList>0 ){
154505        *paPoslist = pList;
154506        *piDocid = iDocid;
154507        *pnPoslist = nList;
154508        break;
154509      }
154510    }
154511  }
154512
154513  return SQLITE_OK;
154514}
154515
154516static int fts3SegReaderStart(
154517  Fts3Table *p,                   /* Virtual table handle */
154518  Fts3MultiSegReader *pCsr,       /* Cursor object */
154519  const char *zTerm,              /* Term searched for (or NULL) */
154520  int nTerm                       /* Length of zTerm in bytes */
154521){
154522  int i;
154523  int nSeg = pCsr->nSegment;
154524
154525  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
154526  ** for, then advance each segment iterator until it points to a term of
154527  ** equal or greater value than the specified term. This prevents many
154528  ** unnecessary merge/sort operations for the case where single segment
154529  ** b-tree leaf nodes contain more than one term.
154530  */
154531  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
154532    int res = 0;
154533    Fts3SegReader *pSeg = pCsr->apSegment[i];
154534    do {
154535      int rc = fts3SegReaderNext(p, pSeg, 0);
154536      if( rc!=SQLITE_OK ) return rc;
154537    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
154538
154539    if( pSeg->bLookup && res!=0 ){
154540      fts3SegReaderSetEof(pSeg);
154541    }
154542  }
154543  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
154544
154545  return SQLITE_OK;
154546}
154547
154548SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
154549  Fts3Table *p,                   /* Virtual table handle */
154550  Fts3MultiSegReader *pCsr,       /* Cursor object */
154551  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
154552){
154553  pCsr->pFilter = pFilter;
154554  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
154555}
154556
154557SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
154558  Fts3Table *p,                   /* Virtual table handle */
154559  Fts3MultiSegReader *pCsr,       /* Cursor object */
154560  int iCol,                       /* Column to match on. */
154561  const char *zTerm,              /* Term to iterate through a doclist for */
154562  int nTerm                       /* Number of bytes in zTerm */
154563){
154564  int i;
154565  int rc;
154566  int nSegment = pCsr->nSegment;
154567  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154568    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154569  );
154570
154571  assert( pCsr->pFilter==0 );
154572  assert( zTerm && nTerm>0 );
154573
154574  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
154575  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
154576  if( rc!=SQLITE_OK ) return rc;
154577
154578  /* Determine how many of the segments actually point to zTerm/nTerm. */
154579  for(i=0; i<nSegment; i++){
154580    Fts3SegReader *pSeg = pCsr->apSegment[i];
154581    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
154582      break;
154583    }
154584  }
154585  pCsr->nAdvance = i;
154586
154587  /* Advance each of the segments to point to the first docid. */
154588  for(i=0; i<pCsr->nAdvance; i++){
154589    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
154590    if( rc!=SQLITE_OK ) return rc;
154591  }
154592  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
154593
154594  assert( iCol<0 || iCol<p->nColumn );
154595  pCsr->iColFilter = iCol;
154596
154597  return SQLITE_OK;
154598}
154599
154600/*
154601** This function is called on a MultiSegReader that has been started using
154602** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
154603** have been made. Calling this function puts the MultiSegReader in such
154604** a state that if the next two calls are:
154605**
154606**   sqlite3Fts3SegReaderStart()
154607**   sqlite3Fts3SegReaderStep()
154608**
154609** then the entire doclist for the term is available in
154610** MultiSegReader.aDoclist/nDoclist.
154611*/
154612SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
154613  int i;                          /* Used to iterate through segment-readers */
154614
154615  assert( pCsr->zTerm==0 );
154616  assert( pCsr->nTerm==0 );
154617  assert( pCsr->aDoclist==0 );
154618  assert( pCsr->nDoclist==0 );
154619
154620  pCsr->nAdvance = 0;
154621  pCsr->bRestart = 1;
154622  for(i=0; i<pCsr->nSegment; i++){
154623    pCsr->apSegment[i]->pOffsetList = 0;
154624    pCsr->apSegment[i]->nOffsetList = 0;
154625    pCsr->apSegment[i]->iDocid = 0;
154626  }
154627
154628  return SQLITE_OK;
154629}
154630
154631
154632SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
154633  Fts3Table *p,                   /* Virtual table handle */
154634  Fts3MultiSegReader *pCsr        /* Cursor object */
154635){
154636  int rc = SQLITE_OK;
154637
154638  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
154639  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
154640  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
154641  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
154642  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
154643  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
154644
154645  Fts3SegReader **apSegment = pCsr->apSegment;
154646  int nSegment = pCsr->nSegment;
154647  Fts3SegFilter *pFilter = pCsr->pFilter;
154648  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154649    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154650  );
154651
154652  if( pCsr->nSegment==0 ) return SQLITE_OK;
154653
154654  do {
154655    int nMerge;
154656    int i;
154657
154658    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
154659    ** forward. Then sort the list in order of current term again.
154660    */
154661    for(i=0; i<pCsr->nAdvance; i++){
154662      Fts3SegReader *pSeg = apSegment[i];
154663      if( pSeg->bLookup ){
154664        fts3SegReaderSetEof(pSeg);
154665      }else{
154666        rc = fts3SegReaderNext(p, pSeg, 0);
154667      }
154668      if( rc!=SQLITE_OK ) return rc;
154669    }
154670    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
154671    pCsr->nAdvance = 0;
154672
154673    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
154674    assert( rc==SQLITE_OK );
154675    if( apSegment[0]->aNode==0 ) break;
154676
154677    pCsr->nTerm = apSegment[0]->nTerm;
154678    pCsr->zTerm = apSegment[0]->zTerm;
154679
154680    /* If this is a prefix-search, and if the term that apSegment[0] points
154681    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
154682    ** required callbacks have been made. In this case exit early.
154683    **
154684    ** Similarly, if this is a search for an exact match, and the first term
154685    ** of segment apSegment[0] is not a match, exit early.
154686    */
154687    if( pFilter->zTerm && !isScan ){
154688      if( pCsr->nTerm<pFilter->nTerm
154689       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
154690       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
154691      ){
154692        break;
154693      }
154694    }
154695
154696    nMerge = 1;
154697    while( nMerge<nSegment
154698        && apSegment[nMerge]->aNode
154699        && apSegment[nMerge]->nTerm==pCsr->nTerm
154700        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
154701    ){
154702      nMerge++;
154703    }
154704
154705    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
154706    if( nMerge==1
154707     && !isIgnoreEmpty
154708     && !isFirst
154709     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
154710    ){
154711      pCsr->nDoclist = apSegment[0]->nDoclist;
154712      if( fts3SegReaderIsPending(apSegment[0]) ){
154713        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
154714        pCsr->aDoclist = pCsr->aBuffer;
154715      }else{
154716        pCsr->aDoclist = apSegment[0]->aDoclist;
154717      }
154718      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
154719    }else{
154720      int nDoclist = 0;           /* Size of doclist */
154721      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
154722
154723      /* The current term of the first nMerge entries in the array
154724      ** of Fts3SegReader objects is the same. The doclists must be merged
154725      ** and a single term returned with the merged doclist.
154726      */
154727      for(i=0; i<nMerge; i++){
154728        fts3SegReaderFirstDocid(p, apSegment[i]);
154729      }
154730      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
154731      while( apSegment[0]->pOffsetList ){
154732        int j;                    /* Number of segments that share a docid */
154733        char *pList = 0;
154734        int nList = 0;
154735        int nByte;
154736        sqlite3_int64 iDocid = apSegment[0]->iDocid;
154737        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
154738        j = 1;
154739        while( j<nMerge
154740            && apSegment[j]->pOffsetList
154741            && apSegment[j]->iDocid==iDocid
154742        ){
154743          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
154744          j++;
154745        }
154746
154747        if( isColFilter ){
154748          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
154749        }
154750
154751        if( !isIgnoreEmpty || nList>0 ){
154752
154753          /* Calculate the 'docid' delta value to write into the merged
154754          ** doclist. */
154755          sqlite3_int64 iDelta;
154756          if( p->bDescIdx && nDoclist>0 ){
154757            iDelta = iPrev - iDocid;
154758          }else{
154759            iDelta = iDocid - iPrev;
154760          }
154761          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
154762          assert( nDoclist>0 || iDelta==iDocid );
154763
154764          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
154765          if( nDoclist+nByte>pCsr->nBuffer ){
154766            char *aNew;
154767            pCsr->nBuffer = (nDoclist+nByte)*2;
154768            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
154769            if( !aNew ){
154770              return SQLITE_NOMEM;
154771            }
154772            pCsr->aBuffer = aNew;
154773          }
154774
154775          if( isFirst ){
154776            char *a = &pCsr->aBuffer[nDoclist];
154777            int nWrite;
154778
154779            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
154780            if( nWrite ){
154781              iPrev = iDocid;
154782              nDoclist += nWrite;
154783            }
154784          }else{
154785            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
154786            iPrev = iDocid;
154787            if( isRequirePos ){
154788              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
154789              nDoclist += nList;
154790              pCsr->aBuffer[nDoclist++] = '\0';
154791            }
154792          }
154793        }
154794
154795        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
154796      }
154797      if( nDoclist>0 ){
154798        pCsr->aDoclist = pCsr->aBuffer;
154799        pCsr->nDoclist = nDoclist;
154800        rc = SQLITE_ROW;
154801      }
154802    }
154803    pCsr->nAdvance = nMerge;
154804  }while( rc==SQLITE_OK );
154805
154806  return rc;
154807}
154808
154809
154810SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
154811  Fts3MultiSegReader *pCsr       /* Cursor object */
154812){
154813  if( pCsr ){
154814    int i;
154815    for(i=0; i<pCsr->nSegment; i++){
154816      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
154817    }
154818    sqlite3_free(pCsr->apSegment);
154819    sqlite3_free(pCsr->aBuffer);
154820
154821    pCsr->nSegment = 0;
154822    pCsr->apSegment = 0;
154823    pCsr->aBuffer = 0;
154824  }
154825}
154826
154827/*
154828** Decode the "end_block" field, selected by column iCol of the SELECT
154829** statement passed as the first argument.
154830**
154831** The "end_block" field may contain either an integer, or a text field
154832** containing the text representation of two non-negative integers separated
154833** by one or more space (0x20) characters. In the first case, set *piEndBlock
154834** to the integer value and *pnByte to zero before returning. In the second,
154835** set *piEndBlock to the first value and *pnByte to the second.
154836*/
154837static void fts3ReadEndBlockField(
154838  sqlite3_stmt *pStmt,
154839  int iCol,
154840  i64 *piEndBlock,
154841  i64 *pnByte
154842){
154843  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
154844  if( zText ){
154845    int i;
154846    int iMul = 1;
154847    i64 iVal = 0;
154848    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
154849      iVal = iVal*10 + (zText[i] - '0');
154850    }
154851    *piEndBlock = iVal;
154852    while( zText[i]==' ' ) i++;
154853    iVal = 0;
154854    if( zText[i]=='-' ){
154855      i++;
154856      iMul = -1;
154857    }
154858    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
154859      iVal = iVal*10 + (zText[i] - '0');
154860    }
154861    *pnByte = (iVal * (i64)iMul);
154862  }
154863}
154864
154865
154866/*
154867** A segment of size nByte bytes has just been written to absolute level
154868** iAbsLevel. Promote any segments that should be promoted as a result.
154869*/
154870static int fts3PromoteSegments(
154871  Fts3Table *p,                   /* FTS table handle */
154872  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
154873  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
154874){
154875  int rc = SQLITE_OK;
154876  sqlite3_stmt *pRange;
154877
154878  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
154879
154880  if( rc==SQLITE_OK ){
154881    int bOk = 0;
154882    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
154883    i64 nLimit = (nByte*3)/2;
154884
154885    /* Loop through all entries in the %_segdir table corresponding to
154886    ** segments in this index on levels greater than iAbsLevel. If there is
154887    ** at least one such segment, and it is possible to determine that all
154888    ** such segments are smaller than nLimit bytes in size, they will be
154889    ** promoted to level iAbsLevel.  */
154890    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
154891    sqlite3_bind_int64(pRange, 2, iLast);
154892    while( SQLITE_ROW==sqlite3_step(pRange) ){
154893      i64 nSize = 0, dummy;
154894      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
154895      if( nSize<=0 || nSize>nLimit ){
154896        /* If nSize==0, then the %_segdir.end_block field does not not
154897        ** contain a size value. This happens if it was written by an
154898        ** old version of FTS. In this case it is not possible to determine
154899        ** the size of the segment, and so segment promotion does not
154900        ** take place.  */
154901        bOk = 0;
154902        break;
154903      }
154904      bOk = 1;
154905    }
154906    rc = sqlite3_reset(pRange);
154907
154908    if( bOk ){
154909      int iIdx = 0;
154910      sqlite3_stmt *pUpdate1 = 0;
154911      sqlite3_stmt *pUpdate2 = 0;
154912
154913      if( rc==SQLITE_OK ){
154914        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
154915      }
154916      if( rc==SQLITE_OK ){
154917        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
154918      }
154919
154920      if( rc==SQLITE_OK ){
154921
154922        /* Loop through all %_segdir entries for segments in this index with
154923        ** levels equal to or greater than iAbsLevel. As each entry is visited,
154924        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
154925        ** oldest segment in the range, 1 for the next oldest, and so on.
154926        **
154927        ** In other words, move all segments being promoted to level -1,
154928        ** setting the "idx" fields as appropriate to keep them in the same
154929        ** order. The contents of level -1 (which is never used, except
154930        ** transiently here), will be moved back to level iAbsLevel below.  */
154931        sqlite3_bind_int64(pRange, 1, iAbsLevel);
154932        while( SQLITE_ROW==sqlite3_step(pRange) ){
154933          sqlite3_bind_int(pUpdate1, 1, iIdx++);
154934          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
154935          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
154936          sqlite3_step(pUpdate1);
154937          rc = sqlite3_reset(pUpdate1);
154938          if( rc!=SQLITE_OK ){
154939            sqlite3_reset(pRange);
154940            break;
154941          }
154942        }
154943      }
154944      if( rc==SQLITE_OK ){
154945        rc = sqlite3_reset(pRange);
154946      }
154947
154948      /* Move level -1 to level iAbsLevel */
154949      if( rc==SQLITE_OK ){
154950        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
154951        sqlite3_step(pUpdate2);
154952        rc = sqlite3_reset(pUpdate2);
154953      }
154954    }
154955  }
154956
154957
154958  return rc;
154959}
154960
154961/*
154962** Merge all level iLevel segments in the database into a single
154963** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
154964** single segment with a level equal to the numerically largest level
154965** currently present in the database.
154966**
154967** If this function is called with iLevel<0, but there is only one
154968** segment in the database, SQLITE_DONE is returned immediately.
154969** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
154970** an SQLite error code is returned.
154971*/
154972static int fts3SegmentMerge(
154973  Fts3Table *p,
154974  int iLangid,                    /* Language id to merge */
154975  int iIndex,                     /* Index in p->aIndex[] to merge */
154976  int iLevel                      /* Level to merge */
154977){
154978  int rc;                         /* Return code */
154979  int iIdx = 0;                   /* Index of new segment */
154980  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
154981  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
154982  Fts3SegFilter filter;           /* Segment term filter condition */
154983  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
154984  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
154985  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
154986
154987  assert( iLevel==FTS3_SEGCURSOR_ALL
154988       || iLevel==FTS3_SEGCURSOR_PENDING
154989       || iLevel>=0
154990  );
154991  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
154992  assert( iIndex>=0 && iIndex<p->nIndex );
154993
154994  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
154995  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
154996
154997  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
154998    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
154999    if( rc!=SQLITE_OK ) goto finished;
155000  }
155001
155002  if( iLevel==FTS3_SEGCURSOR_ALL ){
155003    /* This call is to merge all segments in the database to a single
155004    ** segment. The level of the new segment is equal to the numerically
155005    ** greatest segment level currently present in the database for this
155006    ** index. The idx of the new segment is always 0.  */
155007    if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
155008      rc = SQLITE_DONE;
155009      goto finished;
155010    }
155011    iNewLevel = iMaxLevel;
155012    bIgnoreEmpty = 1;
155013
155014  }else{
155015    /* This call is to merge all segments at level iLevel. find the next
155016    ** available segment index at level iLevel+1. The call to
155017    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
155018    ** a single iLevel+2 segment if necessary.  */
155019    assert( FTS3_SEGCURSOR_PENDING==-1 );
155020    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
155021    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
155022    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
155023  }
155024  if( rc!=SQLITE_OK ) goto finished;
155025
155026  assert( csr.nSegment>0 );
155027  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
155028  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
155029
155030  memset(&filter, 0, sizeof(Fts3SegFilter));
155031  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
155032  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
155033
155034  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
155035  while( SQLITE_OK==rc ){
155036    rc = sqlite3Fts3SegReaderStep(p, &csr);
155037    if( rc!=SQLITE_ROW ) break;
155038    rc = fts3SegWriterAdd(p, &pWriter, 1,
155039        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
155040  }
155041  if( rc!=SQLITE_OK ) goto finished;
155042  assert( pWriter || bIgnoreEmpty );
155043
155044  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
155045    rc = fts3DeleteSegdir(
155046        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
155047    );
155048    if( rc!=SQLITE_OK ) goto finished;
155049  }
155050  if( pWriter ){
155051    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
155052    if( rc==SQLITE_OK ){
155053      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
155054        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
155055      }
155056    }
155057  }
155058
155059 finished:
155060  fts3SegWriterFree(pWriter);
155061  sqlite3Fts3SegReaderFinish(&csr);
155062  return rc;
155063}
155064
155065
155066/*
155067** Flush the contents of pendingTerms to level 0 segments.
155068*/
155069SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
155070  int rc = SQLITE_OK;
155071  int i;
155072
155073  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
155074    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
155075    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
155076  }
155077  sqlite3Fts3PendingTermsClear(p);
155078
155079  /* Determine the auto-incr-merge setting if unknown.  If enabled,
155080  ** estimate the number of leaf blocks of content to be written
155081  */
155082  if( rc==SQLITE_OK && p->bHasStat
155083   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
155084  ){
155085    sqlite3_stmt *pStmt = 0;
155086    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
155087    if( rc==SQLITE_OK ){
155088      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
155089      rc = sqlite3_step(pStmt);
155090      if( rc==SQLITE_ROW ){
155091        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
155092        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
155093      }else if( rc==SQLITE_DONE ){
155094        p->nAutoincrmerge = 0;
155095      }
155096      rc = sqlite3_reset(pStmt);
155097    }
155098  }
155099  return rc;
155100}
155101
155102/*
155103** Encode N integers as varints into a blob.
155104*/
155105static void fts3EncodeIntArray(
155106  int N,             /* The number of integers to encode */
155107  u32 *a,            /* The integer values */
155108  char *zBuf,        /* Write the BLOB here */
155109  int *pNBuf         /* Write number of bytes if zBuf[] used here */
155110){
155111  int i, j;
155112  for(i=j=0; i<N; i++){
155113    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
155114  }
155115  *pNBuf = j;
155116}
155117
155118/*
155119** Decode a blob of varints into N integers
155120*/
155121static void fts3DecodeIntArray(
155122  int N,             /* The number of integers to decode */
155123  u32 *a,            /* Write the integer values */
155124  const char *zBuf,  /* The BLOB containing the varints */
155125  int nBuf           /* size of the BLOB */
155126){
155127  int i, j;
155128  UNUSED_PARAMETER(nBuf);
155129  for(i=j=0; i<N; i++){
155130    sqlite3_int64 x;
155131    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
155132    assert(j<=nBuf);
155133    a[i] = (u32)(x & 0xffffffff);
155134  }
155135}
155136
155137/*
155138** Insert the sizes (in tokens) for each column of the document
155139** with docid equal to p->iPrevDocid.  The sizes are encoded as
155140** a blob of varints.
155141*/
155142static void fts3InsertDocsize(
155143  int *pRC,                       /* Result code */
155144  Fts3Table *p,                   /* Table into which to insert */
155145  u32 *aSz                        /* Sizes of each column, in tokens */
155146){
155147  char *pBlob;             /* The BLOB encoding of the document size */
155148  int nBlob;               /* Number of bytes in the BLOB */
155149  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
155150  int rc;                  /* Result code from subfunctions */
155151
155152  if( *pRC ) return;
155153  pBlob = sqlite3_malloc( 10*p->nColumn );
155154  if( pBlob==0 ){
155155    *pRC = SQLITE_NOMEM;
155156    return;
155157  }
155158  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
155159  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
155160  if( rc ){
155161    sqlite3_free(pBlob);
155162    *pRC = rc;
155163    return;
155164  }
155165  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
155166  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
155167  sqlite3_step(pStmt);
155168  *pRC = sqlite3_reset(pStmt);
155169}
155170
155171/*
155172** Record 0 of the %_stat table contains a blob consisting of N varints,
155173** where N is the number of user defined columns in the fts3 table plus
155174** two. If nCol is the number of user defined columns, then values of the
155175** varints are set as follows:
155176**
155177**   Varint 0:       Total number of rows in the table.
155178**
155179**   Varint 1..nCol: For each column, the total number of tokens stored in
155180**                   the column for all rows of the table.
155181**
155182**   Varint 1+nCol:  The total size, in bytes, of all text values in all
155183**                   columns of all rows of the table.
155184**
155185*/
155186static void fts3UpdateDocTotals(
155187  int *pRC,                       /* The result code */
155188  Fts3Table *p,                   /* Table being updated */
155189  u32 *aSzIns,                    /* Size increases */
155190  u32 *aSzDel,                    /* Size decreases */
155191  int nChng                       /* Change in the number of documents */
155192){
155193  char *pBlob;             /* Storage for BLOB written into %_stat */
155194  int nBlob;               /* Size of BLOB written into %_stat */
155195  u32 *a;                  /* Array of integers that becomes the BLOB */
155196  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
155197  int i;                   /* Loop counter */
155198  int rc;                  /* Result code from subfunctions */
155199
155200  const int nStat = p->nColumn+2;
155201
155202  if( *pRC ) return;
155203  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
155204  if( a==0 ){
155205    *pRC = SQLITE_NOMEM;
155206    return;
155207  }
155208  pBlob = (char*)&a[nStat];
155209  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
155210  if( rc ){
155211    sqlite3_free(a);
155212    *pRC = rc;
155213    return;
155214  }
155215  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155216  if( sqlite3_step(pStmt)==SQLITE_ROW ){
155217    fts3DecodeIntArray(nStat, a,
155218         sqlite3_column_blob(pStmt, 0),
155219         sqlite3_column_bytes(pStmt, 0));
155220  }else{
155221    memset(a, 0, sizeof(u32)*(nStat) );
155222  }
155223  rc = sqlite3_reset(pStmt);
155224  if( rc!=SQLITE_OK ){
155225    sqlite3_free(a);
155226    *pRC = rc;
155227    return;
155228  }
155229  if( nChng<0 && a[0]<(u32)(-nChng) ){
155230    a[0] = 0;
155231  }else{
155232    a[0] += nChng;
155233  }
155234  for(i=0; i<p->nColumn+1; i++){
155235    u32 x = a[i+1];
155236    if( x+aSzIns[i] < aSzDel[i] ){
155237      x = 0;
155238    }else{
155239      x = x + aSzIns[i] - aSzDel[i];
155240    }
155241    a[i+1] = x;
155242  }
155243  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
155244  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
155245  if( rc ){
155246    sqlite3_free(a);
155247    *pRC = rc;
155248    return;
155249  }
155250  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155251  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
155252  sqlite3_step(pStmt);
155253  *pRC = sqlite3_reset(pStmt);
155254  sqlite3_free(a);
155255}
155256
155257/*
155258** Merge the entire database so that there is one segment for each
155259** iIndex/iLangid combination.
155260*/
155261static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
155262  int bSeenDone = 0;
155263  int rc;
155264  sqlite3_stmt *pAllLangid = 0;
155265
155266  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
155267  if( rc==SQLITE_OK ){
155268    int rc2;
155269    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
155270    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
155271    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
155272      int i;
155273      int iLangid = sqlite3_column_int(pAllLangid, 0);
155274      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
155275        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
155276        if( rc==SQLITE_DONE ){
155277          bSeenDone = 1;
155278          rc = SQLITE_OK;
155279        }
155280      }
155281    }
155282    rc2 = sqlite3_reset(pAllLangid);
155283    if( rc==SQLITE_OK ) rc = rc2;
155284  }
155285
155286  sqlite3Fts3SegmentsClose(p);
155287  sqlite3Fts3PendingTermsClear(p);
155288
155289  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
155290}
155291
155292/*
155293** This function is called when the user executes the following statement:
155294**
155295**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
155296**
155297** The entire FTS index is discarded and rebuilt. If the table is one
155298** created using the content=xxx option, then the new index is based on
155299** the current contents of the xxx table. Otherwise, it is rebuilt based
155300** on the contents of the %_content table.
155301*/
155302static int fts3DoRebuild(Fts3Table *p){
155303  int rc;                         /* Return Code */
155304
155305  rc = fts3DeleteAll(p, 0);
155306  if( rc==SQLITE_OK ){
155307    u32 *aSz = 0;
155308    u32 *aSzIns = 0;
155309    u32 *aSzDel = 0;
155310    sqlite3_stmt *pStmt = 0;
155311    int nEntry = 0;
155312
155313    /* Compose and prepare an SQL statement to loop through the content table */
155314    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
155315    if( !zSql ){
155316      rc = SQLITE_NOMEM;
155317    }else{
155318      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
155319      sqlite3_free(zSql);
155320    }
155321
155322    if( rc==SQLITE_OK ){
155323      int nByte = sizeof(u32) * (p->nColumn+1)*3;
155324      aSz = (u32 *)sqlite3_malloc(nByte);
155325      if( aSz==0 ){
155326        rc = SQLITE_NOMEM;
155327      }else{
155328        memset(aSz, 0, nByte);
155329        aSzIns = &aSz[p->nColumn+1];
155330        aSzDel = &aSzIns[p->nColumn+1];
155331      }
155332    }
155333
155334    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
155335      int iCol;
155336      int iLangid = langidFromSelect(p, pStmt);
155337      rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
155338      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
155339      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
155340        if( p->abNotindexed[iCol]==0 ){
155341          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
155342          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
155343          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
155344        }
155345      }
155346      if( p->bHasDocsize ){
155347        fts3InsertDocsize(&rc, p, aSz);
155348      }
155349      if( rc!=SQLITE_OK ){
155350        sqlite3_finalize(pStmt);
155351        pStmt = 0;
155352      }else{
155353        nEntry++;
155354        for(iCol=0; iCol<=p->nColumn; iCol++){
155355          aSzIns[iCol] += aSz[iCol];
155356        }
155357      }
155358    }
155359    if( p->bFts4 ){
155360      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
155361    }
155362    sqlite3_free(aSz);
155363
155364    if( pStmt ){
155365      int rc2 = sqlite3_finalize(pStmt);
155366      if( rc==SQLITE_OK ){
155367        rc = rc2;
155368      }
155369    }
155370  }
155371
155372  return rc;
155373}
155374
155375
155376/*
155377** This function opens a cursor used to read the input data for an
155378** incremental merge operation. Specifically, it opens a cursor to scan
155379** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
155380** level iAbsLevel.
155381*/
155382static int fts3IncrmergeCsr(
155383  Fts3Table *p,                   /* FTS3 table handle */
155384  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
155385  int nSeg,                       /* Number of segments to merge */
155386  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
155387){
155388  int rc;                         /* Return Code */
155389  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
155390  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
155391
155392  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
155393  memset(pCsr, 0, sizeof(*pCsr));
155394  nByte = sizeof(Fts3SegReader *) * nSeg;
155395  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
155396
155397  if( pCsr->apSegment==0 ){
155398    rc = SQLITE_NOMEM;
155399  }else{
155400    memset(pCsr->apSegment, 0, nByte);
155401    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
155402  }
155403  if( rc==SQLITE_OK ){
155404    int i;
155405    int rc2;
155406    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
155407    assert( pCsr->nSegment==0 );
155408    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
155409      rc = sqlite3Fts3SegReaderNew(i, 0,
155410          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
155411          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
155412          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
155413          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
155414          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
155415          &pCsr->apSegment[i]
155416      );
155417      pCsr->nSegment++;
155418    }
155419    rc2 = sqlite3_reset(pStmt);
155420    if( rc==SQLITE_OK ) rc = rc2;
155421  }
155422
155423  return rc;
155424}
155425
155426typedef struct IncrmergeWriter IncrmergeWriter;
155427typedef struct NodeWriter NodeWriter;
155428typedef struct Blob Blob;
155429typedef struct NodeReader NodeReader;
155430
155431/*
155432** An instance of the following structure is used as a dynamic buffer
155433** to build up nodes or other blobs of data in.
155434**
155435** The function blobGrowBuffer() is used to extend the allocation.
155436*/
155437struct Blob {
155438  char *a;                        /* Pointer to allocation */
155439  int n;                          /* Number of valid bytes of data in a[] */
155440  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
155441};
155442
155443/*
155444** This structure is used to build up buffers containing segment b-tree
155445** nodes (blocks).
155446*/
155447struct NodeWriter {
155448  sqlite3_int64 iBlock;           /* Current block id */
155449  Blob key;                       /* Last key written to the current block */
155450  Blob block;                     /* Current block image */
155451};
155452
155453/*
155454** An object of this type contains the state required to create or append
155455** to an appendable b-tree segment.
155456*/
155457struct IncrmergeWriter {
155458  int nLeafEst;                   /* Space allocated for leaf blocks */
155459  int nWork;                      /* Number of leaf pages flushed */
155460  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
155461  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
155462  sqlite3_int64 iStart;           /* Block number of first allocated block */
155463  sqlite3_int64 iEnd;             /* Block number of last allocated block */
155464  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
155465  u8 bNoLeafData;                 /* If true, store 0 for segment size */
155466  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
155467};
155468
155469/*
155470** An object of the following type is used to read data from a single
155471** FTS segment node. See the following functions:
155472**
155473**     nodeReaderInit()
155474**     nodeReaderNext()
155475**     nodeReaderRelease()
155476*/
155477struct NodeReader {
155478  const char *aNode;
155479  int nNode;
155480  int iOff;                       /* Current offset within aNode[] */
155481
155482  /* Output variables. Containing the current node entry. */
155483  sqlite3_int64 iChild;           /* Pointer to child node */
155484  Blob term;                      /* Current term */
155485  const char *aDoclist;           /* Pointer to doclist */
155486  int nDoclist;                   /* Size of doclist in bytes */
155487};
155488
155489/*
155490** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
155491** Otherwise, if the allocation at pBlob->a is not already at least nMin
155492** bytes in size, extend (realloc) it to be so.
155493**
155494** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
155495** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
155496** to reflect the new size of the pBlob->a[] buffer.
155497*/
155498static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
155499  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
155500    int nAlloc = nMin;
155501    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
155502    if( a ){
155503      pBlob->nAlloc = nAlloc;
155504      pBlob->a = a;
155505    }else{
155506      *pRc = SQLITE_NOMEM;
155507    }
155508  }
155509}
155510
155511/*
155512** Attempt to advance the node-reader object passed as the first argument to
155513** the next entry on the node.
155514**
155515** Return an error code if an error occurs (SQLITE_NOMEM is possible).
155516** Otherwise return SQLITE_OK. If there is no next entry on the node
155517** (e.g. because the current entry is the last) set NodeReader->aNode to
155518** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
155519** variables for the new entry.
155520*/
155521static int nodeReaderNext(NodeReader *p){
155522  int bFirst = (p->term.n==0);    /* True for first term on the node */
155523  int nPrefix = 0;                /* Bytes to copy from previous term */
155524  int nSuffix = 0;                /* Bytes to append to the prefix */
155525  int rc = SQLITE_OK;             /* Return code */
155526
155527  assert( p->aNode );
155528  if( p->iChild && bFirst==0 ) p->iChild++;
155529  if( p->iOff>=p->nNode ){
155530    /* EOF */
155531    p->aNode = 0;
155532  }else{
155533    if( bFirst==0 ){
155534      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
155535    }
155536    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
155537
155538    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
155539    if( rc==SQLITE_OK ){
155540      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
155541      p->term.n = nPrefix+nSuffix;
155542      p->iOff += nSuffix;
155543      if( p->iChild==0 ){
155544        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
155545        p->aDoclist = &p->aNode[p->iOff];
155546        p->iOff += p->nDoclist;
155547      }
155548    }
155549  }
155550
155551  assert( p->iOff<=p->nNode );
155552
155553  return rc;
155554}
155555
155556/*
155557** Release all dynamic resources held by node-reader object *p.
155558*/
155559static void nodeReaderRelease(NodeReader *p){
155560  sqlite3_free(p->term.a);
155561}
155562
155563/*
155564** Initialize a node-reader object to read the node in buffer aNode/nNode.
155565**
155566** If successful, SQLITE_OK is returned and the NodeReader object set to
155567** point to the first entry on the node (if any). Otherwise, an SQLite
155568** error code is returned.
155569*/
155570static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
155571  memset(p, 0, sizeof(NodeReader));
155572  p->aNode = aNode;
155573  p->nNode = nNode;
155574
155575  /* Figure out if this is a leaf or an internal node. */
155576  if( p->aNode[0] ){
155577    /* An internal node. */
155578    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
155579  }else{
155580    p->iOff = 1;
155581  }
155582
155583  return nodeReaderNext(p);
155584}
155585
155586/*
155587** This function is called while writing an FTS segment each time a leaf o
155588** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
155589** to be greater than the largest key on the node just written, but smaller
155590** than or equal to the first key that will be written to the next leaf
155591** node.
155592**
155593** The block id of the leaf node just written to disk may be found in
155594** (pWriter->aNodeWriter[0].iBlock) when this function is called.
155595*/
155596static int fts3IncrmergePush(
155597  Fts3Table *p,                   /* Fts3 table handle */
155598  IncrmergeWriter *pWriter,       /* Writer object */
155599  const char *zTerm,              /* Term to write to internal node */
155600  int nTerm                       /* Bytes at zTerm */
155601){
155602  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
155603  int iLayer;
155604
155605  assert( nTerm>0 );
155606  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
155607    sqlite3_int64 iNextPtr = 0;
155608    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
155609    int rc = SQLITE_OK;
155610    int nPrefix;
155611    int nSuffix;
155612    int nSpace;
155613
155614    /* Figure out how much space the key will consume if it is written to
155615    ** the current node of layer iLayer. Due to the prefix compression,
155616    ** the space required changes depending on which node the key is to
155617    ** be added to.  */
155618    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
155619    nSuffix = nTerm - nPrefix;
155620    nSpace  = sqlite3Fts3VarintLen(nPrefix);
155621    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155622
155623    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
155624      /* If the current node of layer iLayer contains zero keys, or if adding
155625      ** the key to it will not cause it to grow to larger than nNodeSize
155626      ** bytes in size, write the key here.  */
155627
155628      Blob *pBlk = &pNode->block;
155629      if( pBlk->n==0 ){
155630        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
155631        if( rc==SQLITE_OK ){
155632          pBlk->a[0] = (char)iLayer;
155633          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
155634        }
155635      }
155636      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
155637      blobGrowBuffer(&pNode->key, nTerm, &rc);
155638
155639      if( rc==SQLITE_OK ){
155640        if( pNode->key.n ){
155641          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
155642        }
155643        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
155644        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
155645        pBlk->n += nSuffix;
155646
155647        memcpy(pNode->key.a, zTerm, nTerm);
155648        pNode->key.n = nTerm;
155649      }
155650    }else{
155651      /* Otherwise, flush the current node of layer iLayer to disk.
155652      ** Then allocate a new, empty sibling node. The key will be written
155653      ** into the parent of this node. */
155654      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
155655
155656      assert( pNode->block.nAlloc>=p->nNodeSize );
155657      pNode->block.a[0] = (char)iLayer;
155658      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
155659
155660      iNextPtr = pNode->iBlock;
155661      pNode->iBlock++;
155662      pNode->key.n = 0;
155663    }
155664
155665    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
155666    iPtr = iNextPtr;
155667  }
155668
155669  assert( 0 );
155670  return 0;
155671}
155672
155673/*
155674** Append a term and (optionally) doclist to the FTS segment node currently
155675** stored in blob *pNode. The node need not contain any terms, but the
155676** header must be written before this function is called.
155677**
155678** A node header is a single 0x00 byte for a leaf node, or a height varint
155679** followed by the left-hand-child varint for an internal node.
155680**
155681** The term to be appended is passed via arguments zTerm/nTerm. For a
155682** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
155683** node, both aDoclist and nDoclist must be passed 0.
155684**
155685** If the size of the value in blob pPrev is zero, then this is the first
155686** term written to the node. Otherwise, pPrev contains a copy of the
155687** previous term. Before this function returns, it is updated to contain a
155688** copy of zTerm/nTerm.
155689**
155690** It is assumed that the buffer associated with pNode is already large
155691** enough to accommodate the new entry. The buffer associated with pPrev
155692** is extended by this function if requrired.
155693**
155694** If an error (i.e. OOM condition) occurs, an SQLite error code is
155695** returned. Otherwise, SQLITE_OK.
155696*/
155697static int fts3AppendToNode(
155698  Blob *pNode,                    /* Current node image to append to */
155699  Blob *pPrev,                    /* Buffer containing previous term written */
155700  const char *zTerm,              /* New term to write */
155701  int nTerm,                      /* Size of zTerm in bytes */
155702  const char *aDoclist,           /* Doclist (or NULL) to write */
155703  int nDoclist                    /* Size of aDoclist in bytes */
155704){
155705  int rc = SQLITE_OK;             /* Return code */
155706  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
155707  int nPrefix;                    /* Size of term prefix in bytes */
155708  int nSuffix;                    /* Size of term suffix in bytes */
155709
155710  /* Node must have already been started. There must be a doclist for a
155711  ** leaf node, and there must not be a doclist for an internal node.  */
155712  assert( pNode->n>0 );
155713  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
155714
155715  blobGrowBuffer(pPrev, nTerm, &rc);
155716  if( rc!=SQLITE_OK ) return rc;
155717
155718  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
155719  nSuffix = nTerm - nPrefix;
155720  memcpy(pPrev->a, zTerm, nTerm);
155721  pPrev->n = nTerm;
155722
155723  if( bFirst==0 ){
155724    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
155725  }
155726  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
155727  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
155728  pNode->n += nSuffix;
155729
155730  if( aDoclist ){
155731    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
155732    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
155733    pNode->n += nDoclist;
155734  }
155735
155736  assert( pNode->n<=pNode->nAlloc );
155737
155738  return SQLITE_OK;
155739}
155740
155741/*
155742** Append the current term and doclist pointed to by cursor pCsr to the
155743** appendable b-tree segment opened for writing by pWriter.
155744**
155745** Return SQLITE_OK if successful, or an SQLite error code otherwise.
155746*/
155747static int fts3IncrmergeAppend(
155748  Fts3Table *p,                   /* Fts3 table handle */
155749  IncrmergeWriter *pWriter,       /* Writer object */
155750  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
155751){
155752  const char *zTerm = pCsr->zTerm;
155753  int nTerm = pCsr->nTerm;
155754  const char *aDoclist = pCsr->aDoclist;
155755  int nDoclist = pCsr->nDoclist;
155756  int rc = SQLITE_OK;           /* Return code */
155757  int nSpace;                   /* Total space in bytes required on leaf */
155758  int nPrefix;                  /* Size of prefix shared with previous term */
155759  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
155760  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
155761
155762  pLeaf = &pWriter->aNodeWriter[0];
155763  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
155764  nSuffix = nTerm - nPrefix;
155765
155766  nSpace  = sqlite3Fts3VarintLen(nPrefix);
155767  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155768  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
155769
155770  /* If the current block is not empty, and if adding this term/doclist
155771  ** to the current block would make it larger than Fts3Table.nNodeSize
155772  ** bytes, write this block out to the database. */
155773  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
155774    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
155775    pWriter->nWork++;
155776
155777    /* Add the current term to the parent node. The term added to the
155778    ** parent must:
155779    **
155780    **   a) be greater than the largest term on the leaf node just written
155781    **      to the database (still available in pLeaf->key), and
155782    **
155783    **   b) be less than or equal to the term about to be added to the new
155784    **      leaf node (zTerm/nTerm).
155785    **
155786    ** In other words, it must be the prefix of zTerm 1 byte longer than
155787    ** the common prefix (if any) of zTerm and pWriter->zTerm.
155788    */
155789    if( rc==SQLITE_OK ){
155790      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
155791    }
155792
155793    /* Advance to the next output block */
155794    pLeaf->iBlock++;
155795    pLeaf->key.n = 0;
155796    pLeaf->block.n = 0;
155797
155798    nSuffix = nTerm;
155799    nSpace  = 1;
155800    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155801    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
155802  }
155803
155804  pWriter->nLeafData += nSpace;
155805  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
155806  if( rc==SQLITE_OK ){
155807    if( pLeaf->block.n==0 ){
155808      pLeaf->block.n = 1;
155809      pLeaf->block.a[0] = '\0';
155810    }
155811    rc = fts3AppendToNode(
155812        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
155813    );
155814  }
155815
155816  return rc;
155817}
155818
155819/*
155820** This function is called to release all dynamic resources held by the
155821** merge-writer object pWriter, and if no error has occurred, to flush
155822** all outstanding node buffers held by pWriter to disk.
155823**
155824** If *pRc is not SQLITE_OK when this function is called, then no attempt
155825** is made to write any data to disk. Instead, this function serves only
155826** to release outstanding resources.
155827**
155828** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
155829** flushing buffers to disk, *pRc is set to an SQLite error code before
155830** returning.
155831*/
155832static void fts3IncrmergeRelease(
155833  Fts3Table *p,                   /* FTS3 table handle */
155834  IncrmergeWriter *pWriter,       /* Merge-writer object */
155835  int *pRc                        /* IN/OUT: Error code */
155836){
155837  int i;                          /* Used to iterate through non-root layers */
155838  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
155839  NodeWriter *pRoot;              /* NodeWriter for root node */
155840  int rc = *pRc;                  /* Error code */
155841
155842  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
155843  ** root node. If the segment fits entirely on a single leaf node, iRoot
155844  ** will be set to 0. If the root node is the parent of the leaves, iRoot
155845  ** will be 1. And so on.  */
155846  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
155847    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
155848    if( pNode->block.n>0 ) break;
155849    assert( *pRc || pNode->block.nAlloc==0 );
155850    assert( *pRc || pNode->key.nAlloc==0 );
155851    sqlite3_free(pNode->block.a);
155852    sqlite3_free(pNode->key.a);
155853  }
155854
155855  /* Empty output segment. This is a no-op. */
155856  if( iRoot<0 ) return;
155857
155858  /* The entire output segment fits on a single node. Normally, this means
155859  ** the node would be stored as a blob in the "root" column of the %_segdir
155860  ** table. However, this is not permitted in this case. The problem is that
155861  ** space has already been reserved in the %_segments table, and so the
155862  ** start_block and end_block fields of the %_segdir table must be populated.
155863  ** And, by design or by accident, released versions of FTS cannot handle
155864  ** segments that fit entirely on the root node with start_block!=0.
155865  **
155866  ** Instead, create a synthetic root node that contains nothing but a
155867  ** pointer to the single content node. So that the segment consists of a
155868  ** single leaf and a single interior (root) node.
155869  **
155870  ** Todo: Better might be to defer allocating space in the %_segments
155871  ** table until we are sure it is needed.
155872  */
155873  if( iRoot==0 ){
155874    Blob *pBlock = &pWriter->aNodeWriter[1].block;
155875    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
155876    if( rc==SQLITE_OK ){
155877      pBlock->a[0] = 0x01;
155878      pBlock->n = 1 + sqlite3Fts3PutVarint(
155879          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
155880      );
155881    }
155882    iRoot = 1;
155883  }
155884  pRoot = &pWriter->aNodeWriter[iRoot];
155885
155886  /* Flush all currently outstanding nodes to disk. */
155887  for(i=0; i<iRoot; i++){
155888    NodeWriter *pNode = &pWriter->aNodeWriter[i];
155889    if( pNode->block.n>0 && rc==SQLITE_OK ){
155890      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
155891    }
155892    sqlite3_free(pNode->block.a);
155893    sqlite3_free(pNode->key.a);
155894  }
155895
155896  /* Write the %_segdir record. */
155897  if( rc==SQLITE_OK ){
155898    rc = fts3WriteSegdir(p,
155899        pWriter->iAbsLevel+1,               /* level */
155900        pWriter->iIdx,                      /* idx */
155901        pWriter->iStart,                    /* start_block */
155902        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
155903        pWriter->iEnd,                      /* end_block */
155904        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
155905        pRoot->block.a, pRoot->block.n      /* root */
155906    );
155907  }
155908  sqlite3_free(pRoot->block.a);
155909  sqlite3_free(pRoot->key.a);
155910
155911  *pRc = rc;
155912}
155913
155914/*
155915** Compare the term in buffer zLhs (size in bytes nLhs) with that in
155916** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
155917** the other, it is considered to be smaller than the other.
155918**
155919** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
155920** if it is greater.
155921*/
155922static int fts3TermCmp(
155923  const char *zLhs, int nLhs,     /* LHS of comparison */
155924  const char *zRhs, int nRhs      /* RHS of comparison */
155925){
155926  int nCmp = MIN(nLhs, nRhs);
155927  int res;
155928
155929  res = memcmp(zLhs, zRhs, nCmp);
155930  if( res==0 ) res = nLhs - nRhs;
155931
155932  return res;
155933}
155934
155935
155936/*
155937** Query to see if the entry in the %_segments table with blockid iEnd is
155938** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
155939** returning. Otherwise, set *pbRes to 0.
155940**
155941** Or, if an error occurs while querying the database, return an SQLite
155942** error code. The final value of *pbRes is undefined in this case.
155943**
155944** This is used to test if a segment is an "appendable" segment. If it
155945** is, then a NULL entry has been inserted into the %_segments table
155946** with blockid %_segdir.end_block.
155947*/
155948static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
155949  int bRes = 0;                   /* Result to set *pbRes to */
155950  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
155951  int rc;                         /* Return code */
155952
155953  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
155954  if( rc==SQLITE_OK ){
155955    sqlite3_bind_int64(pCheck, 1, iEnd);
155956    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
155957    rc = sqlite3_reset(pCheck);
155958  }
155959
155960  *pbRes = bRes;
155961  return rc;
155962}
155963
155964/*
155965** This function is called when initializing an incremental-merge operation.
155966** It checks if the existing segment with index value iIdx at absolute level
155967** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
155968** merge-writer object *pWriter is initialized to write to it.
155969**
155970** An existing segment can be appended to by an incremental merge if:
155971**
155972**   * It was initially created as an appendable segment (with all required
155973**     space pre-allocated), and
155974**
155975**   * The first key read from the input (arguments zKey and nKey) is
155976**     greater than the largest key currently stored in the potential
155977**     output segment.
155978*/
155979static int fts3IncrmergeLoad(
155980  Fts3Table *p,                   /* Fts3 table handle */
155981  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
155982  int iIdx,                       /* Index of candidate output segment */
155983  const char *zKey,               /* First key to write */
155984  int nKey,                       /* Number of bytes in nKey */
155985  IncrmergeWriter *pWriter        /* Populate this object */
155986){
155987  int rc;                         /* Return code */
155988  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
155989
155990  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
155991  if( rc==SQLITE_OK ){
155992    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
155993    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
155994    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
155995    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
155996    int nRoot = 0;                /* Size of aRoot[] in bytes */
155997    int rc2;                      /* Return code from sqlite3_reset() */
155998    int bAppendable = 0;          /* Set to true if segment is appendable */
155999
156000    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
156001    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
156002    sqlite3_bind_int(pSelect, 2, iIdx);
156003    if( sqlite3_step(pSelect)==SQLITE_ROW ){
156004      iStart = sqlite3_column_int64(pSelect, 1);
156005      iLeafEnd = sqlite3_column_int64(pSelect, 2);
156006      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
156007      if( pWriter->nLeafData<0 ){
156008        pWriter->nLeafData = pWriter->nLeafData * -1;
156009      }
156010      pWriter->bNoLeafData = (pWriter->nLeafData==0);
156011      nRoot = sqlite3_column_bytes(pSelect, 4);
156012      aRoot = sqlite3_column_blob(pSelect, 4);
156013    }else{
156014      return sqlite3_reset(pSelect);
156015    }
156016
156017    /* Check for the zero-length marker in the %_segments table */
156018    rc = fts3IsAppendable(p, iEnd, &bAppendable);
156019
156020    /* Check that zKey/nKey is larger than the largest key the candidate */
156021    if( rc==SQLITE_OK && bAppendable ){
156022      char *aLeaf = 0;
156023      int nLeaf = 0;
156024
156025      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
156026      if( rc==SQLITE_OK ){
156027        NodeReader reader;
156028        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
156029            rc==SQLITE_OK && reader.aNode;
156030            rc = nodeReaderNext(&reader)
156031        ){
156032          assert( reader.aNode );
156033        }
156034        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
156035          bAppendable = 0;
156036        }
156037        nodeReaderRelease(&reader);
156038      }
156039      sqlite3_free(aLeaf);
156040    }
156041
156042    if( rc==SQLITE_OK && bAppendable ){
156043      /* It is possible to append to this segment. Set up the IncrmergeWriter
156044      ** object to do so.  */
156045      int i;
156046      int nHeight = (int)aRoot[0];
156047      NodeWriter *pNode;
156048
156049      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
156050      pWriter->iStart = iStart;
156051      pWriter->iEnd = iEnd;
156052      pWriter->iAbsLevel = iAbsLevel;
156053      pWriter->iIdx = iIdx;
156054
156055      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
156056        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
156057      }
156058
156059      pNode = &pWriter->aNodeWriter[nHeight];
156060      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
156061      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
156062      if( rc==SQLITE_OK ){
156063        memcpy(pNode->block.a, aRoot, nRoot);
156064        pNode->block.n = nRoot;
156065      }
156066
156067      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
156068        NodeReader reader;
156069        pNode = &pWriter->aNodeWriter[i];
156070
156071        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
156072        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
156073        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
156074        if( rc==SQLITE_OK ){
156075          memcpy(pNode->key.a, reader.term.a, reader.term.n);
156076          pNode->key.n = reader.term.n;
156077          if( i>0 ){
156078            char *aBlock = 0;
156079            int nBlock = 0;
156080            pNode = &pWriter->aNodeWriter[i-1];
156081            pNode->iBlock = reader.iChild;
156082            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
156083            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
156084            if( rc==SQLITE_OK ){
156085              memcpy(pNode->block.a, aBlock, nBlock);
156086              pNode->block.n = nBlock;
156087            }
156088            sqlite3_free(aBlock);
156089          }
156090        }
156091        nodeReaderRelease(&reader);
156092      }
156093    }
156094
156095    rc2 = sqlite3_reset(pSelect);
156096    if( rc==SQLITE_OK ) rc = rc2;
156097  }
156098
156099  return rc;
156100}
156101
156102/*
156103** Determine the largest segment index value that exists within absolute
156104** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
156105** one before returning SQLITE_OK. Or, if there are no segments at all
156106** within level iAbsLevel, set *piIdx to zero.
156107**
156108** If an error occurs, return an SQLite error code. The final value of
156109** *piIdx is undefined in this case.
156110*/
156111static int fts3IncrmergeOutputIdx(
156112  Fts3Table *p,                   /* FTS Table handle */
156113  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
156114  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
156115){
156116  int rc;
156117  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
156118
156119  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
156120  if( rc==SQLITE_OK ){
156121    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
156122    sqlite3_step(pOutputIdx);
156123    *piIdx = sqlite3_column_int(pOutputIdx, 0);
156124    rc = sqlite3_reset(pOutputIdx);
156125  }
156126
156127  return rc;
156128}
156129
156130/*
156131** Allocate an appendable output segment on absolute level iAbsLevel+1
156132** with idx value iIdx.
156133**
156134** In the %_segdir table, a segment is defined by the values in three
156135** columns:
156136**
156137**     start_block
156138**     leaves_end_block
156139**     end_block
156140**
156141** When an appendable segment is allocated, it is estimated that the
156142** maximum number of leaf blocks that may be required is the sum of the
156143** number of leaf blocks consumed by the input segments, plus the number
156144** of input segments, multiplied by two. This value is stored in stack
156145** variable nLeafEst.
156146**
156147** A total of 16*nLeafEst blocks are allocated when an appendable segment
156148** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
156149** array of leaf nodes starts at the first block allocated. The array
156150** of interior nodes that are parents of the leaf nodes start at block
156151** (start_block + (1 + end_block - start_block) / 16). And so on.
156152**
156153** In the actual code below, the value "16" is replaced with the
156154** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
156155*/
156156static int fts3IncrmergeWriter(
156157  Fts3Table *p,                   /* Fts3 table handle */
156158  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
156159  int iIdx,                       /* Index of new output segment */
156160  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
156161  IncrmergeWriter *pWriter        /* Populate this object */
156162){
156163  int rc;                         /* Return Code */
156164  int i;                          /* Iterator variable */
156165  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
156166  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
156167  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
156168
156169  /* Calculate nLeafEst. */
156170  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
156171  if( rc==SQLITE_OK ){
156172    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
156173    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
156174    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
156175      nLeafEst = sqlite3_column_int(pLeafEst, 0);
156176    }
156177    rc = sqlite3_reset(pLeafEst);
156178  }
156179  if( rc!=SQLITE_OK ) return rc;
156180
156181  /* Calculate the first block to use in the output segment */
156182  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
156183  if( rc==SQLITE_OK ){
156184    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
156185      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
156186      pWriter->iEnd = pWriter->iStart - 1;
156187      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
156188    }
156189    rc = sqlite3_reset(pFirstBlock);
156190  }
156191  if( rc!=SQLITE_OK ) return rc;
156192
156193  /* Insert the marker in the %_segments table to make sure nobody tries
156194  ** to steal the space just allocated. This is also used to identify
156195  ** appendable segments.  */
156196  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
156197  if( rc!=SQLITE_OK ) return rc;
156198
156199  pWriter->iAbsLevel = iAbsLevel;
156200  pWriter->nLeafEst = nLeafEst;
156201  pWriter->iIdx = iIdx;
156202
156203  /* Set up the array of NodeWriter objects */
156204  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
156205    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
156206  }
156207  return SQLITE_OK;
156208}
156209
156210/*
156211** Remove an entry from the %_segdir table. This involves running the
156212** following two statements:
156213**
156214**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
156215**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
156216**
156217** The DELETE statement removes the specific %_segdir level. The UPDATE
156218** statement ensures that the remaining segments have contiguously allocated
156219** idx values.
156220*/
156221static int fts3RemoveSegdirEntry(
156222  Fts3Table *p,                   /* FTS3 table handle */
156223  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
156224  int iIdx                        /* Index of %_segdir entry to delete */
156225){
156226  int rc;                         /* Return code */
156227  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
156228
156229  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
156230  if( rc==SQLITE_OK ){
156231    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
156232    sqlite3_bind_int(pDelete, 2, iIdx);
156233    sqlite3_step(pDelete);
156234    rc = sqlite3_reset(pDelete);
156235  }
156236
156237  return rc;
156238}
156239
156240/*
156241** One or more segments have just been removed from absolute level iAbsLevel.
156242** Update the 'idx' values of the remaining segments in the level so that
156243** the idx values are a contiguous sequence starting from 0.
156244*/
156245static int fts3RepackSegdirLevel(
156246  Fts3Table *p,                   /* FTS3 table handle */
156247  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
156248){
156249  int rc;                         /* Return code */
156250  int *aIdx = 0;                  /* Array of remaining idx values */
156251  int nIdx = 0;                   /* Valid entries in aIdx[] */
156252  int nAlloc = 0;                 /* Allocated size of aIdx[] */
156253  int i;                          /* Iterator variable */
156254  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
156255  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
156256
156257  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
156258  if( rc==SQLITE_OK ){
156259    int rc2;
156260    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
156261    while( SQLITE_ROW==sqlite3_step(pSelect) ){
156262      if( nIdx>=nAlloc ){
156263        int *aNew;
156264        nAlloc += 16;
156265        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
156266        if( !aNew ){
156267          rc = SQLITE_NOMEM;
156268          break;
156269        }
156270        aIdx = aNew;
156271      }
156272      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
156273    }
156274    rc2 = sqlite3_reset(pSelect);
156275    if( rc==SQLITE_OK ) rc = rc2;
156276  }
156277
156278  if( rc==SQLITE_OK ){
156279    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
156280  }
156281  if( rc==SQLITE_OK ){
156282    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
156283  }
156284
156285  assert( p->bIgnoreSavepoint==0 );
156286  p->bIgnoreSavepoint = 1;
156287  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
156288    if( aIdx[i]!=i ){
156289      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
156290      sqlite3_bind_int(pUpdate, 1, i);
156291      sqlite3_step(pUpdate);
156292      rc = sqlite3_reset(pUpdate);
156293    }
156294  }
156295  p->bIgnoreSavepoint = 0;
156296
156297  sqlite3_free(aIdx);
156298  return rc;
156299}
156300
156301static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
156302  pNode->a[0] = (char)iHeight;
156303  if( iChild ){
156304    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
156305    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
156306  }else{
156307    assert( pNode->nAlloc>=1 );
156308    pNode->n = 1;
156309  }
156310}
156311
156312/*
156313** The first two arguments are a pointer to and the size of a segment b-tree
156314** node. The node may be a leaf or an internal node.
156315**
156316** This function creates a new node image in blob object *pNew by copying
156317** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
156318** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
156319*/
156320static int fts3TruncateNode(
156321  const char *aNode,              /* Current node image */
156322  int nNode,                      /* Size of aNode in bytes */
156323  Blob *pNew,                     /* OUT: Write new node image here */
156324  const char *zTerm,              /* Omit all terms smaller than this */
156325  int nTerm,                      /* Size of zTerm in bytes */
156326  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
156327){
156328  NodeReader reader;              /* Reader object */
156329  Blob prev = {0, 0, 0};          /* Previous term written to new node */
156330  int rc = SQLITE_OK;             /* Return code */
156331  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
156332
156333  /* Allocate required output space */
156334  blobGrowBuffer(pNew, nNode, &rc);
156335  if( rc!=SQLITE_OK ) return rc;
156336  pNew->n = 0;
156337
156338  /* Populate new node buffer */
156339  for(rc = nodeReaderInit(&reader, aNode, nNode);
156340      rc==SQLITE_OK && reader.aNode;
156341      rc = nodeReaderNext(&reader)
156342  ){
156343    if( pNew->n==0 ){
156344      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
156345      if( res<0 || (bLeaf==0 && res==0) ) continue;
156346      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
156347      *piBlock = reader.iChild;
156348    }
156349    rc = fts3AppendToNode(
156350        pNew, &prev, reader.term.a, reader.term.n,
156351        reader.aDoclist, reader.nDoclist
156352    );
156353    if( rc!=SQLITE_OK ) break;
156354  }
156355  if( pNew->n==0 ){
156356    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
156357    *piBlock = reader.iChild;
156358  }
156359  assert( pNew->n<=pNew->nAlloc );
156360
156361  nodeReaderRelease(&reader);
156362  sqlite3_free(prev.a);
156363  return rc;
156364}
156365
156366/*
156367** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
156368** level iAbsLevel. This may involve deleting entries from the %_segments
156369** table, and modifying existing entries in both the %_segments and %_segdir
156370** tables.
156371**
156372** SQLITE_OK is returned if the segment is updated successfully. Or an
156373** SQLite error code otherwise.
156374*/
156375static int fts3TruncateSegment(
156376  Fts3Table *p,                   /* FTS3 table handle */
156377  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
156378  int iIdx,                       /* Index within level of segment to modify */
156379  const char *zTerm,              /* Remove terms smaller than this */
156380  int nTerm                      /* Number of bytes in buffer zTerm */
156381){
156382  int rc = SQLITE_OK;             /* Return code */
156383  Blob root = {0,0,0};            /* New root page image */
156384  Blob block = {0,0,0};           /* Buffer used for any other block */
156385  sqlite3_int64 iBlock = 0;       /* Block id */
156386  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
156387  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
156388  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
156389
156390  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
156391  if( rc==SQLITE_OK ){
156392    int rc2;                      /* sqlite3_reset() return code */
156393    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
156394    sqlite3_bind_int(pFetch, 2, iIdx);
156395    if( SQLITE_ROW==sqlite3_step(pFetch) ){
156396      const char *aRoot = sqlite3_column_blob(pFetch, 4);
156397      int nRoot = sqlite3_column_bytes(pFetch, 4);
156398      iOldStart = sqlite3_column_int64(pFetch, 1);
156399      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
156400    }
156401    rc2 = sqlite3_reset(pFetch);
156402    if( rc==SQLITE_OK ) rc = rc2;
156403  }
156404
156405  while( rc==SQLITE_OK && iBlock ){
156406    char *aBlock = 0;
156407    int nBlock = 0;
156408    iNewStart = iBlock;
156409
156410    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
156411    if( rc==SQLITE_OK ){
156412      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
156413    }
156414    if( rc==SQLITE_OK ){
156415      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
156416    }
156417    sqlite3_free(aBlock);
156418  }
156419
156420  /* Variable iNewStart now contains the first valid leaf node. */
156421  if( rc==SQLITE_OK && iNewStart ){
156422    sqlite3_stmt *pDel = 0;
156423    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
156424    if( rc==SQLITE_OK ){
156425      sqlite3_bind_int64(pDel, 1, iOldStart);
156426      sqlite3_bind_int64(pDel, 2, iNewStart-1);
156427      sqlite3_step(pDel);
156428      rc = sqlite3_reset(pDel);
156429    }
156430  }
156431
156432  if( rc==SQLITE_OK ){
156433    sqlite3_stmt *pChomp = 0;
156434    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
156435    if( rc==SQLITE_OK ){
156436      sqlite3_bind_int64(pChomp, 1, iNewStart);
156437      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
156438      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
156439      sqlite3_bind_int(pChomp, 4, iIdx);
156440      sqlite3_step(pChomp);
156441      rc = sqlite3_reset(pChomp);
156442    }
156443  }
156444
156445  sqlite3_free(root.a);
156446  sqlite3_free(block.a);
156447  return rc;
156448}
156449
156450/*
156451** This function is called after an incrmental-merge operation has run to
156452** merge (or partially merge) two or more segments from absolute level
156453** iAbsLevel.
156454**
156455** Each input segment is either removed from the db completely (if all of
156456** its data was copied to the output segment by the incrmerge operation)
156457** or modified in place so that it no longer contains those entries that
156458** have been duplicated in the output segment.
156459*/
156460static int fts3IncrmergeChomp(
156461  Fts3Table *p,                   /* FTS table handle */
156462  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
156463  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
156464  int *pnRem                      /* Number of segments not deleted */
156465){
156466  int i;
156467  int nRem = 0;
156468  int rc = SQLITE_OK;
156469
156470  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
156471    Fts3SegReader *pSeg = 0;
156472    int j;
156473
156474    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
156475    ** somewhere in the pCsr->apSegment[] array.  */
156476    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
156477      pSeg = pCsr->apSegment[j];
156478      if( pSeg->iIdx==i ) break;
156479    }
156480    assert( j<pCsr->nSegment && pSeg->iIdx==i );
156481
156482    if( pSeg->aNode==0 ){
156483      /* Seg-reader is at EOF. Remove the entire input segment. */
156484      rc = fts3DeleteSegment(p, pSeg);
156485      if( rc==SQLITE_OK ){
156486        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
156487      }
156488      *pnRem = 0;
156489    }else{
156490      /* The incremental merge did not copy all the data from this
156491      ** segment to the upper level. The segment is modified in place
156492      ** so that it contains no keys smaller than zTerm/nTerm. */
156493      const char *zTerm = pSeg->zTerm;
156494      int nTerm = pSeg->nTerm;
156495      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
156496      nRem++;
156497    }
156498  }
156499
156500  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
156501    rc = fts3RepackSegdirLevel(p, iAbsLevel);
156502  }
156503
156504  *pnRem = nRem;
156505  return rc;
156506}
156507
156508/*
156509** Store an incr-merge hint in the database.
156510*/
156511static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
156512  sqlite3_stmt *pReplace = 0;
156513  int rc;                         /* Return code */
156514
156515  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
156516  if( rc==SQLITE_OK ){
156517    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
156518    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
156519    sqlite3_step(pReplace);
156520    rc = sqlite3_reset(pReplace);
156521  }
156522
156523  return rc;
156524}
156525
156526/*
156527** Load an incr-merge hint from the database. The incr-merge hint, if one
156528** exists, is stored in the rowid==1 row of the %_stat table.
156529**
156530** If successful, populate blob *pHint with the value read from the %_stat
156531** table and return SQLITE_OK. Otherwise, if an error occurs, return an
156532** SQLite error code.
156533*/
156534static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
156535  sqlite3_stmt *pSelect = 0;
156536  int rc;
156537
156538  pHint->n = 0;
156539  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
156540  if( rc==SQLITE_OK ){
156541    int rc2;
156542    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
156543    if( SQLITE_ROW==sqlite3_step(pSelect) ){
156544      const char *aHint = sqlite3_column_blob(pSelect, 0);
156545      int nHint = sqlite3_column_bytes(pSelect, 0);
156546      if( aHint ){
156547        blobGrowBuffer(pHint, nHint, &rc);
156548        if( rc==SQLITE_OK ){
156549          memcpy(pHint->a, aHint, nHint);
156550          pHint->n = nHint;
156551        }
156552      }
156553    }
156554    rc2 = sqlite3_reset(pSelect);
156555    if( rc==SQLITE_OK ) rc = rc2;
156556  }
156557
156558  return rc;
156559}
156560
156561/*
156562** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
156563** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
156564** consists of two varints, the absolute level number of the input segments
156565** and the number of input segments.
156566**
156567** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
156568** set *pRc to an SQLite error code before returning.
156569*/
156570static void fts3IncrmergeHintPush(
156571  Blob *pHint,                    /* Hint blob to append to */
156572  i64 iAbsLevel,                  /* First varint to store in hint */
156573  int nInput,                     /* Second varint to store in hint */
156574  int *pRc                        /* IN/OUT: Error code */
156575){
156576  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
156577  if( *pRc==SQLITE_OK ){
156578    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
156579    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
156580  }
156581}
156582
156583/*
156584** Read the last entry (most recently pushed) from the hint blob *pHint
156585** and then remove the entry. Write the two values read to *piAbsLevel and
156586** *pnInput before returning.
156587**
156588** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
156589** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
156590*/
156591static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
156592  const int nHint = pHint->n;
156593  int i;
156594
156595  i = pHint->n-2;
156596  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
156597  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
156598
156599  pHint->n = i;
156600  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
156601  i += fts3GetVarint32(&pHint->a[i], pnInput);
156602  if( i!=nHint ) return FTS_CORRUPT_VTAB;
156603
156604  return SQLITE_OK;
156605}
156606
156607
156608/*
156609** Attempt an incremental merge that writes nMerge leaf blocks.
156610**
156611** Incremental merges happen nMin segments at a time. The segments
156612** to be merged are the nMin oldest segments (the ones with the smallest
156613** values for the _segdir.idx field) in the highest level that contains
156614** at least nMin segments. Multiple merges might occur in an attempt to
156615** write the quota of nMerge leaf blocks.
156616*/
156617SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
156618  int rc;                         /* Return code */
156619  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
156620  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
156621  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
156622  IncrmergeWriter *pWriter;       /* Writer object */
156623  int nSeg = 0;                   /* Number of input segments */
156624  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
156625  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
156626  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
156627
156628  /* Allocate space for the cursor, filter and writer objects */
156629  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
156630  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
156631  if( !pWriter ) return SQLITE_NOMEM;
156632  pFilter = (Fts3SegFilter *)&pWriter[1];
156633  pCsr = (Fts3MultiSegReader *)&pFilter[1];
156634
156635  rc = fts3IncrmergeHintLoad(p, &hint);
156636  while( rc==SQLITE_OK && nRem>0 ){
156637    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
156638    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
156639    int bUseHint = 0;             /* True if attempting to append */
156640    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
156641
156642    /* Search the %_segdir table for the absolute level with the smallest
156643    ** relative level number that contains at least nMin segments, if any.
156644    ** If one is found, set iAbsLevel to the absolute level number and
156645    ** nSeg to nMin. If no level with at least nMin segments can be found,
156646    ** set nSeg to -1.
156647    */
156648    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
156649    sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
156650    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
156651      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
156652      nSeg = sqlite3_column_int(pFindLevel, 1);
156653      assert( nSeg>=2 );
156654    }else{
156655      nSeg = -1;
156656    }
156657    rc = sqlite3_reset(pFindLevel);
156658
156659    /* If the hint read from the %_stat table is not empty, check if the
156660    ** last entry in it specifies a relative level smaller than or equal
156661    ** to the level identified by the block above (if any). If so, this
156662    ** iteration of the loop will work on merging at the hinted level.
156663    */
156664    if( rc==SQLITE_OK && hint.n ){
156665      int nHint = hint.n;
156666      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
156667      int nHintSeg = 0;                     /* Hint number of segments */
156668
156669      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
156670      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
156671        iAbsLevel = iHintAbsLevel;
156672        nSeg = nHintSeg;
156673        bUseHint = 1;
156674        bDirtyHint = 1;
156675      }else{
156676        /* This undoes the effect of the HintPop() above - so that no entry
156677        ** is removed from the hint blob.  */
156678        hint.n = nHint;
156679      }
156680    }
156681
156682    /* If nSeg is less that zero, then there is no level with at least
156683    ** nMin segments and no hint in the %_stat table. No work to do.
156684    ** Exit early in this case.  */
156685    if( nSeg<0 ) break;
156686
156687    /* Open a cursor to iterate through the contents of the oldest nSeg
156688    ** indexes of absolute level iAbsLevel. If this cursor is opened using
156689    ** the 'hint' parameters, it is possible that there are less than nSeg
156690    ** segments available in level iAbsLevel. In this case, no work is
156691    ** done on iAbsLevel - fall through to the next iteration of the loop
156692    ** to start work on some other level.  */
156693    memset(pWriter, 0, nAlloc);
156694    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
156695
156696    if( rc==SQLITE_OK ){
156697      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
156698      assert( bUseHint==1 || bUseHint==0 );
156699      if( iIdx==0 || (bUseHint && iIdx==1) ){
156700        int bIgnore = 0;
156701        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
156702        if( bIgnore ){
156703          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
156704        }
156705      }
156706    }
156707
156708    if( rc==SQLITE_OK ){
156709      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
156710    }
156711    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
156712     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
156713     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
156714    ){
156715      if( bUseHint && iIdx>0 ){
156716        const char *zKey = pCsr->zTerm;
156717        int nKey = pCsr->nTerm;
156718        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
156719      }else{
156720        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
156721      }
156722
156723      if( rc==SQLITE_OK && pWriter->nLeafEst ){
156724        fts3LogMerge(nSeg, iAbsLevel);
156725        do {
156726          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
156727          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
156728          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
156729        }while( rc==SQLITE_ROW );
156730
156731        /* Update or delete the input segments */
156732        if( rc==SQLITE_OK ){
156733          nRem -= (1 + pWriter->nWork);
156734          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
156735          if( nSeg!=0 ){
156736            bDirtyHint = 1;
156737            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
156738          }
156739        }
156740      }
156741
156742      if( nSeg!=0 ){
156743        pWriter->nLeafData = pWriter->nLeafData * -1;
156744      }
156745      fts3IncrmergeRelease(p, pWriter, &rc);
156746      if( nSeg==0 && pWriter->bNoLeafData==0 ){
156747        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
156748      }
156749    }
156750
156751    sqlite3Fts3SegReaderFinish(pCsr);
156752  }
156753
156754  /* Write the hint values into the %_stat table for the next incr-merger */
156755  if( bDirtyHint && rc==SQLITE_OK ){
156756    rc = fts3IncrmergeHintStore(p, &hint);
156757  }
156758
156759  sqlite3_free(pWriter);
156760  sqlite3_free(hint.a);
156761  return rc;
156762}
156763
156764/*
156765** Convert the text beginning at *pz into an integer and return
156766** its value.  Advance *pz to point to the first character past
156767** the integer.
156768*/
156769static int fts3Getint(const char **pz){
156770  const char *z = *pz;
156771  int i = 0;
156772  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
156773  *pz = z;
156774  return i;
156775}
156776
156777/*
156778** Process statements of the form:
156779**
156780**    INSERT INTO table(table) VALUES('merge=A,B');
156781**
156782** A and B are integers that decode to be the number of leaf pages
156783** written for the merge, and the minimum number of segments on a level
156784** before it will be selected for a merge, respectively.
156785*/
156786static int fts3DoIncrmerge(
156787  Fts3Table *p,                   /* FTS3 table handle */
156788  const char *zParam              /* Nul-terminated string containing "A,B" */
156789){
156790  int rc;
156791  int nMin = (FTS3_MERGE_COUNT / 2);
156792  int nMerge = 0;
156793  const char *z = zParam;
156794
156795  /* Read the first integer value */
156796  nMerge = fts3Getint(&z);
156797
156798  /* If the first integer value is followed by a ',',  read the second
156799  ** integer value. */
156800  if( z[0]==',' && z[1]!='\0' ){
156801    z++;
156802    nMin = fts3Getint(&z);
156803  }
156804
156805  if( z[0]!='\0' || nMin<2 ){
156806    rc = SQLITE_ERROR;
156807  }else{
156808    rc = SQLITE_OK;
156809    if( !p->bHasStat ){
156810      assert( p->bFts4==0 );
156811      sqlite3Fts3CreateStatTable(&rc, p);
156812    }
156813    if( rc==SQLITE_OK ){
156814      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
156815    }
156816    sqlite3Fts3SegmentsClose(p);
156817  }
156818  return rc;
156819}
156820
156821/*
156822** Process statements of the form:
156823**
156824**    INSERT INTO table(table) VALUES('automerge=X');
156825**
156826** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
156827** turn it on.  The setting is persistent.
156828*/
156829static int fts3DoAutoincrmerge(
156830  Fts3Table *p,                   /* FTS3 table handle */
156831  const char *zParam              /* Nul-terminated string containing boolean */
156832){
156833  int rc = SQLITE_OK;
156834  sqlite3_stmt *pStmt = 0;
156835  p->nAutoincrmerge = fts3Getint(&zParam);
156836  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
156837    p->nAutoincrmerge = 8;
156838  }
156839  if( !p->bHasStat ){
156840    assert( p->bFts4==0 );
156841    sqlite3Fts3CreateStatTable(&rc, p);
156842    if( rc ) return rc;
156843  }
156844  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
156845  if( rc ) return rc;
156846  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
156847  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
156848  sqlite3_step(pStmt);
156849  rc = sqlite3_reset(pStmt);
156850  return rc;
156851}
156852
156853/*
156854** Return a 64-bit checksum for the FTS index entry specified by the
156855** arguments to this function.
156856*/
156857static u64 fts3ChecksumEntry(
156858  const char *zTerm,              /* Pointer to buffer containing term */
156859  int nTerm,                      /* Size of zTerm in bytes */
156860  int iLangid,                    /* Language id for current row */
156861  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
156862  i64 iDocid,                     /* Docid for current row. */
156863  int iCol,                       /* Column number */
156864  int iPos                        /* Position */
156865){
156866  int i;
156867  u64 ret = (u64)iDocid;
156868
156869  ret += (ret<<3) + iLangid;
156870  ret += (ret<<3) + iIndex;
156871  ret += (ret<<3) + iCol;
156872  ret += (ret<<3) + iPos;
156873  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
156874
156875  return ret;
156876}
156877
156878/*
156879** Return a checksum of all entries in the FTS index that correspond to
156880** language id iLangid. The checksum is calculated by XORing the checksums
156881** of each individual entry (see fts3ChecksumEntry()) together.
156882**
156883** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
156884** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
156885** return value is undefined in this case.
156886*/
156887static u64 fts3ChecksumIndex(
156888  Fts3Table *p,                   /* FTS3 table handle */
156889  int iLangid,                    /* Language id to return cksum for */
156890  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
156891  int *pRc                        /* OUT: Return code */
156892){
156893  Fts3SegFilter filter;
156894  Fts3MultiSegReader csr;
156895  int rc;
156896  u64 cksum = 0;
156897
156898  assert( *pRc==SQLITE_OK );
156899
156900  memset(&filter, 0, sizeof(filter));
156901  memset(&csr, 0, sizeof(csr));
156902  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
156903  filter.flags |= FTS3_SEGMENT_SCAN;
156904
156905  rc = sqlite3Fts3SegReaderCursor(
156906      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
156907  );
156908  if( rc==SQLITE_OK ){
156909    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
156910  }
156911
156912  if( rc==SQLITE_OK ){
156913    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
156914      char *pCsr = csr.aDoclist;
156915      char *pEnd = &pCsr[csr.nDoclist];
156916
156917      i64 iDocid = 0;
156918      i64 iCol = 0;
156919      i64 iPos = 0;
156920
156921      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
156922      while( pCsr<pEnd ){
156923        i64 iVal = 0;
156924        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
156925        if( pCsr<pEnd ){
156926          if( iVal==0 || iVal==1 ){
156927            iCol = 0;
156928            iPos = 0;
156929            if( iVal ){
156930              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
156931            }else{
156932              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
156933              iDocid += iVal;
156934            }
156935          }else{
156936            iPos += (iVal - 2);
156937            cksum = cksum ^ fts3ChecksumEntry(
156938                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
156939                (int)iCol, (int)iPos
156940            );
156941          }
156942        }
156943      }
156944    }
156945  }
156946  sqlite3Fts3SegReaderFinish(&csr);
156947
156948  *pRc = rc;
156949  return cksum;
156950}
156951
156952/*
156953** Check if the contents of the FTS index match the current contents of the
156954** content table. If no error occurs and the contents do match, set *pbOk
156955** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
156956** to false before returning.
156957**
156958** If an error occurs (e.g. an OOM or IO error), return an SQLite error
156959** code. The final value of *pbOk is undefined in this case.
156960*/
156961static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
156962  int rc = SQLITE_OK;             /* Return code */
156963  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
156964  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
156965  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
156966
156967  /* This block calculates the checksum according to the FTS index. */
156968  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
156969  if( rc==SQLITE_OK ){
156970    int rc2;
156971    sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
156972    sqlite3_bind_int(pAllLangid, 2, p->nIndex);
156973    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
156974      int iLangid = sqlite3_column_int(pAllLangid, 0);
156975      int i;
156976      for(i=0; i<p->nIndex; i++){
156977        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
156978      }
156979    }
156980    rc2 = sqlite3_reset(pAllLangid);
156981    if( rc==SQLITE_OK ) rc = rc2;
156982  }
156983
156984  /* This block calculates the checksum according to the %_content table */
156985  if( rc==SQLITE_OK ){
156986    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
156987    sqlite3_stmt *pStmt = 0;
156988    char *zSql;
156989
156990    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
156991    if( !zSql ){
156992      rc = SQLITE_NOMEM;
156993    }else{
156994      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
156995      sqlite3_free(zSql);
156996    }
156997
156998    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
156999      i64 iDocid = sqlite3_column_int64(pStmt, 0);
157000      int iLang = langidFromSelect(p, pStmt);
157001      int iCol;
157002
157003      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
157004        if( p->abNotindexed[iCol]==0 ){
157005          const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
157006          int nText = sqlite3_column_bytes(pStmt, iCol+1);
157007          sqlite3_tokenizer_cursor *pT = 0;
157008
157009          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
157010          while( rc==SQLITE_OK ){
157011            char const *zToken;       /* Buffer containing token */
157012            int nToken = 0;           /* Number of bytes in token */
157013            int iDum1 = 0, iDum2 = 0; /* Dummy variables */
157014            int iPos = 0;             /* Position of token in zText */
157015
157016            rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
157017            if( rc==SQLITE_OK ){
157018              int i;
157019              cksum2 = cksum2 ^ fts3ChecksumEntry(
157020                  zToken, nToken, iLang, 0, iDocid, iCol, iPos
157021              );
157022              for(i=1; i<p->nIndex; i++){
157023                if( p->aIndex[i].nPrefix<=nToken ){
157024                  cksum2 = cksum2 ^ fts3ChecksumEntry(
157025                      zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
157026                  );
157027                }
157028              }
157029            }
157030          }
157031          if( pT ) pModule->xClose(pT);
157032          if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157033        }
157034      }
157035    }
157036
157037    sqlite3_finalize(pStmt);
157038  }
157039
157040  *pbOk = (cksum1==cksum2);
157041  return rc;
157042}
157043
157044/*
157045** Run the integrity-check. If no error occurs and the current contents of
157046** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
157047** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
157048**
157049** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
157050** error code.
157051**
157052** The integrity-check works as follows. For each token and indexed token
157053** prefix in the document set, a 64-bit checksum is calculated (by code
157054** in fts3ChecksumEntry()) based on the following:
157055**
157056**     + The index number (0 for the main index, 1 for the first prefix
157057**       index etc.),
157058**     + The token (or token prefix) text itself,
157059**     + The language-id of the row it appears in,
157060**     + The docid of the row it appears in,
157061**     + The column it appears in, and
157062**     + The tokens position within that column.
157063**
157064** The checksums for all entries in the index are XORed together to create
157065** a single checksum for the entire index.
157066**
157067** The integrity-check code calculates the same checksum in two ways:
157068**
157069**     1. By scanning the contents of the FTS index, and
157070**     2. By scanning and tokenizing the content table.
157071**
157072** If the two checksums are identical, the integrity-check is deemed to have
157073** passed.
157074*/
157075static int fts3DoIntegrityCheck(
157076  Fts3Table *p                    /* FTS3 table handle */
157077){
157078  int rc;
157079  int bOk = 0;
157080  rc = fts3IntegrityCheck(p, &bOk);
157081  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
157082  return rc;
157083}
157084
157085/*
157086** Handle a 'special' INSERT of the form:
157087**
157088**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
157089**
157090** Argument pVal contains the result of <expr>. Currently the only
157091** meaningful value to insert is the text 'optimize'.
157092*/
157093static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
157094  int rc;                         /* Return Code */
157095  const char *zVal = (const char *)sqlite3_value_text(pVal);
157096  int nVal = sqlite3_value_bytes(pVal);
157097
157098  if( !zVal ){
157099    return SQLITE_NOMEM;
157100  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
157101    rc = fts3DoOptimize(p, 0);
157102  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
157103    rc = fts3DoRebuild(p);
157104  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
157105    rc = fts3DoIntegrityCheck(p);
157106  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
157107    rc = fts3DoIncrmerge(p, &zVal[6]);
157108  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
157109    rc = fts3DoAutoincrmerge(p, &zVal[10]);
157110#ifdef SQLITE_TEST
157111  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
157112    p->nNodeSize = atoi(&zVal[9]);
157113    rc = SQLITE_OK;
157114  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
157115    p->nMaxPendingData = atoi(&zVal[11]);
157116    rc = SQLITE_OK;
157117  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
157118    p->bNoIncrDoclist = atoi(&zVal[21]);
157119    rc = SQLITE_OK;
157120#endif
157121  }else{
157122    rc = SQLITE_ERROR;
157123  }
157124
157125  return rc;
157126}
157127
157128#ifndef SQLITE_DISABLE_FTS4_DEFERRED
157129/*
157130** Delete all cached deferred doclists. Deferred doclists are cached
157131** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
157132*/
157133SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
157134  Fts3DeferredToken *pDef;
157135  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
157136    fts3PendingListDelete(pDef->pList);
157137    pDef->pList = 0;
157138  }
157139}
157140
157141/*
157142** Free all entries in the pCsr->pDeffered list. Entries are added to
157143** this list using sqlite3Fts3DeferToken().
157144*/
157145SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
157146  Fts3DeferredToken *pDef;
157147  Fts3DeferredToken *pNext;
157148  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
157149    pNext = pDef->pNext;
157150    fts3PendingListDelete(pDef->pList);
157151    sqlite3_free(pDef);
157152  }
157153  pCsr->pDeferred = 0;
157154}
157155
157156/*
157157** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
157158** based on the row that pCsr currently points to.
157159**
157160** A deferred-doclist is like any other doclist with position information
157161** included, except that it only contains entries for a single row of the
157162** table, not for all rows.
157163*/
157164SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
157165  int rc = SQLITE_OK;             /* Return code */
157166  if( pCsr->pDeferred ){
157167    int i;                        /* Used to iterate through table columns */
157168    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
157169    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
157170
157171    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
157172    sqlite3_tokenizer *pT = p->pTokenizer;
157173    sqlite3_tokenizer_module const *pModule = pT->pModule;
157174
157175    assert( pCsr->isRequireSeek==0 );
157176    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
157177
157178    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
157179      if( p->abNotindexed[i]==0 ){
157180        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
157181        sqlite3_tokenizer_cursor *pTC = 0;
157182
157183        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
157184        while( rc==SQLITE_OK ){
157185          char const *zToken;       /* Buffer containing token */
157186          int nToken = 0;           /* Number of bytes in token */
157187          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
157188          int iPos = 0;             /* Position of token in zText */
157189
157190          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
157191          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
157192            Fts3PhraseToken *pPT = pDef->pToken;
157193            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
157194                && (pPT->bFirst==0 || iPos==0)
157195                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
157196                && (0==memcmp(zToken, pPT->z, pPT->n))
157197              ){
157198              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
157199            }
157200          }
157201        }
157202        if( pTC ) pModule->xClose(pTC);
157203        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157204      }
157205    }
157206
157207    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
157208      if( pDef->pList ){
157209        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
157210      }
157211    }
157212  }
157213
157214  return rc;
157215}
157216
157217SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
157218  Fts3DeferredToken *p,
157219  char **ppData,
157220  int *pnData
157221){
157222  char *pRet;
157223  int nSkip;
157224  sqlite3_int64 dummy;
157225
157226  *ppData = 0;
157227  *pnData = 0;
157228
157229  if( p->pList==0 ){
157230    return SQLITE_OK;
157231  }
157232
157233  pRet = (char *)sqlite3_malloc(p->pList->nData);
157234  if( !pRet ) return SQLITE_NOMEM;
157235
157236  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
157237  *pnData = p->pList->nData - nSkip;
157238  *ppData = pRet;
157239
157240  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
157241  return SQLITE_OK;
157242}
157243
157244/*
157245** Add an entry for token pToken to the pCsr->pDeferred list.
157246*/
157247SQLITE_PRIVATE int sqlite3Fts3DeferToken(
157248  Fts3Cursor *pCsr,               /* Fts3 table cursor */
157249  Fts3PhraseToken *pToken,        /* Token to defer */
157250  int iCol                        /* Column that token must appear in (or -1) */
157251){
157252  Fts3DeferredToken *pDeferred;
157253  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
157254  if( !pDeferred ){
157255    return SQLITE_NOMEM;
157256  }
157257  memset(pDeferred, 0, sizeof(*pDeferred));
157258  pDeferred->pToken = pToken;
157259  pDeferred->pNext = pCsr->pDeferred;
157260  pDeferred->iCol = iCol;
157261  pCsr->pDeferred = pDeferred;
157262
157263  assert( pToken->pDeferred==0 );
157264  pToken->pDeferred = pDeferred;
157265
157266  return SQLITE_OK;
157267}
157268#endif
157269
157270/*
157271** SQLite value pRowid contains the rowid of a row that may or may not be
157272** present in the FTS3 table. If it is, delete it and adjust the contents
157273** of subsiduary data structures accordingly.
157274*/
157275static int fts3DeleteByRowid(
157276  Fts3Table *p,
157277  sqlite3_value *pRowid,
157278  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
157279  u32 *aSzDel
157280){
157281  int rc = SQLITE_OK;             /* Return code */
157282  int bFound = 0;                 /* True if *pRowid really is in the table */
157283
157284  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
157285  if( bFound && rc==SQLITE_OK ){
157286    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
157287    rc = fts3IsEmpty(p, pRowid, &isEmpty);
157288    if( rc==SQLITE_OK ){
157289      if( isEmpty ){
157290        /* Deleting this row means the whole table is empty. In this case
157291        ** delete the contents of all three tables and throw away any
157292        ** data in the pendingTerms hash table.  */
157293        rc = fts3DeleteAll(p, 1);
157294        *pnChng = 0;
157295        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
157296      }else{
157297        *pnChng = *pnChng - 1;
157298        if( p->zContentTbl==0 ){
157299          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
157300        }
157301        if( p->bHasDocsize ){
157302          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
157303        }
157304      }
157305    }
157306  }
157307
157308  return rc;
157309}
157310
157311/*
157312** This function does the work for the xUpdate method of FTS3 virtual
157313** tables. The schema of the virtual table being:
157314**
157315**     CREATE TABLE <table name>(
157316**       <user columns>,
157317**       <table name> HIDDEN,
157318**       docid HIDDEN,
157319**       <langid> HIDDEN
157320**     );
157321**
157322**
157323*/
157324SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
157325  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
157326  int nArg,                       /* Size of argument array */
157327  sqlite3_value **apVal,          /* Array of arguments */
157328  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
157329){
157330  Fts3Table *p = (Fts3Table *)pVtab;
157331  int rc = SQLITE_OK;             /* Return Code */
157332  int isRemove = 0;               /* True for an UPDATE or DELETE */
157333  u32 *aSzIns = 0;                /* Sizes of inserted documents */
157334  u32 *aSzDel = 0;                /* Sizes of deleted documents */
157335  int nChng = 0;                  /* Net change in number of documents */
157336  int bInsertDone = 0;
157337
157338  /* At this point it must be known if the %_stat table exists or not.
157339  ** So bHasStat may not be 2.  */
157340  assert( p->bHasStat==0 || p->bHasStat==1 );
157341
157342  assert( p->pSegments==0 );
157343  assert(
157344      nArg==1                     /* DELETE operations */
157345   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
157346  );
157347
157348  /* Check for a "special" INSERT operation. One of the form:
157349  **
157350  **   INSERT INTO xyz(xyz) VALUES('command');
157351  */
157352  if( nArg>1
157353   && sqlite3_value_type(apVal[0])==SQLITE_NULL
157354   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
157355  ){
157356    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
157357    goto update_out;
157358  }
157359
157360  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
157361    rc = SQLITE_CONSTRAINT;
157362    goto update_out;
157363  }
157364
157365  /* Allocate space to hold the change in document sizes */
157366  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
157367  if( aSzDel==0 ){
157368    rc = SQLITE_NOMEM;
157369    goto update_out;
157370  }
157371  aSzIns = &aSzDel[p->nColumn+1];
157372  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
157373
157374  rc = fts3Writelock(p);
157375  if( rc!=SQLITE_OK ) goto update_out;
157376
157377  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
157378  ** value, then this operation requires constraint handling.
157379  **
157380  ** If the on-conflict mode is REPLACE, this means that the existing row
157381  ** should be deleted from the database before inserting the new row. Or,
157382  ** if the on-conflict mode is other than REPLACE, then this method must
157383  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
157384  ** modify the database file.
157385  */
157386  if( nArg>1 && p->zContentTbl==0 ){
157387    /* Find the value object that holds the new rowid value. */
157388    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
157389    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
157390      pNewRowid = apVal[1];
157391    }
157392
157393    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
157394        sqlite3_value_type(apVal[0])==SQLITE_NULL
157395     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
157396    )){
157397      /* The new rowid is not NULL (in this case the rowid will be
157398      ** automatically assigned and there is no chance of a conflict), and
157399      ** the statement is either an INSERT or an UPDATE that modifies the
157400      ** rowid column. So if the conflict mode is REPLACE, then delete any
157401      ** existing row with rowid=pNewRowid.
157402      **
157403      ** Or, if the conflict mode is not REPLACE, insert the new record into
157404      ** the %_content table. If we hit the duplicate rowid constraint (or any
157405      ** other error) while doing so, return immediately.
157406      **
157407      ** This branch may also run if pNewRowid contains a value that cannot
157408      ** be losslessly converted to an integer. In this case, the eventual
157409      ** call to fts3InsertData() (either just below or further on in this
157410      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
157411      ** invoked, it will delete zero rows (since no row will have
157412      ** docid=$pNewRowid if $pNewRowid is not an integer value).
157413      */
157414      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
157415        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
157416      }else{
157417        rc = fts3InsertData(p, apVal, pRowid);
157418        bInsertDone = 1;
157419      }
157420    }
157421  }
157422  if( rc!=SQLITE_OK ){
157423    goto update_out;
157424  }
157425
157426  /* If this is a DELETE or UPDATE operation, remove the old record. */
157427  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
157428    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
157429    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
157430    isRemove = 1;
157431  }
157432
157433  /* If this is an INSERT or UPDATE operation, insert the new record. */
157434  if( nArg>1 && rc==SQLITE_OK ){
157435    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
157436    if( bInsertDone==0 ){
157437      rc = fts3InsertData(p, apVal, pRowid);
157438      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
157439        rc = FTS_CORRUPT_VTAB;
157440      }
157441    }
157442    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
157443      rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
157444    }
157445    if( rc==SQLITE_OK ){
157446      assert( p->iPrevDocid==*pRowid );
157447      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
157448    }
157449    if( p->bHasDocsize ){
157450      fts3InsertDocsize(&rc, p, aSzIns);
157451    }
157452    nChng++;
157453  }
157454
157455  if( p->bFts4 ){
157456    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
157457  }
157458
157459 update_out:
157460  sqlite3_free(aSzDel);
157461  sqlite3Fts3SegmentsClose(p);
157462  return rc;
157463}
157464
157465/*
157466** Flush any data in the pending-terms hash table to disk. If successful,
157467** merge all segments in the database (including the new segment, if
157468** there was any data to flush) into a single segment.
157469*/
157470SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
157471  int rc;
157472  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
157473  if( rc==SQLITE_OK ){
157474    rc = fts3DoOptimize(p, 1);
157475    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
157476      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
157477      if( rc2!=SQLITE_OK ) rc = rc2;
157478    }else{
157479      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
157480      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
157481    }
157482  }
157483  sqlite3Fts3SegmentsClose(p);
157484  return rc;
157485}
157486
157487#endif
157488
157489/************** End of fts3_write.c ******************************************/
157490/************** Begin file fts3_snippet.c ************************************/
157491/*
157492** 2009 Oct 23
157493**
157494** The author disclaims copyright to this source code.  In place of
157495** a legal notice, here is a blessing:
157496**
157497**    May you do good and not evil.
157498**    May you find forgiveness for yourself and forgive others.
157499**    May you share freely, never taking more than you give.
157500**
157501******************************************************************************
157502*/
157503
157504/* #include "fts3Int.h" */
157505#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157506
157507/* #include <string.h> */
157508/* #include <assert.h> */
157509
157510/*
157511** Characters that may appear in the second argument to matchinfo().
157512*/
157513#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
157514#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
157515#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
157516#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
157517#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
157518#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
157519#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
157520#define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
157521#define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
157522
157523/*
157524** The default value for the second argument to matchinfo().
157525*/
157526#define FTS3_MATCHINFO_DEFAULT   "pcx"
157527
157528
157529/*
157530** Used as an fts3ExprIterate() context when loading phrase doclists to
157531** Fts3Expr.aDoclist[]/nDoclist.
157532*/
157533typedef struct LoadDoclistCtx LoadDoclistCtx;
157534struct LoadDoclistCtx {
157535  Fts3Cursor *pCsr;               /* FTS3 Cursor */
157536  int nPhrase;                    /* Number of phrases seen so far */
157537  int nToken;                     /* Number of tokens seen so far */
157538};
157539
157540/*
157541** The following types are used as part of the implementation of the
157542** fts3BestSnippet() routine.
157543*/
157544typedef struct SnippetIter SnippetIter;
157545typedef struct SnippetPhrase SnippetPhrase;
157546typedef struct SnippetFragment SnippetFragment;
157547
157548struct SnippetIter {
157549  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
157550  int iCol;                       /* Extract snippet from this column */
157551  int nSnippet;                   /* Requested snippet length (in tokens) */
157552  int nPhrase;                    /* Number of phrases in query */
157553  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
157554  int iCurrent;                   /* First token of current snippet */
157555};
157556
157557struct SnippetPhrase {
157558  int nToken;                     /* Number of tokens in phrase */
157559  char *pList;                    /* Pointer to start of phrase position list */
157560  int iHead;                      /* Next value in position list */
157561  char *pHead;                    /* Position list data following iHead */
157562  int iTail;                      /* Next value in trailing position list */
157563  char *pTail;                    /* Position list data following iTail */
157564};
157565
157566struct SnippetFragment {
157567  int iCol;                       /* Column snippet is extracted from */
157568  int iPos;                       /* Index of first token in snippet */
157569  u64 covered;                    /* Mask of query phrases covered */
157570  u64 hlmask;                     /* Mask of snippet terms to highlight */
157571};
157572
157573/*
157574** This type is used as an fts3ExprIterate() context object while
157575** accumulating the data returned by the matchinfo() function.
157576*/
157577typedef struct MatchInfo MatchInfo;
157578struct MatchInfo {
157579  Fts3Cursor *pCursor;            /* FTS3 Cursor */
157580  int nCol;                       /* Number of columns in table */
157581  int nPhrase;                    /* Number of matchable phrases in query */
157582  sqlite3_int64 nDoc;             /* Number of docs in database */
157583  char flag;
157584  u32 *aMatchinfo;                /* Pre-allocated buffer */
157585};
157586
157587/*
157588** An instance of this structure is used to manage a pair of buffers, each
157589** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
157590** for details.
157591*/
157592struct MatchinfoBuffer {
157593  u8 aRef[3];
157594  int nElem;
157595  int bGlobal;                    /* Set if global data is loaded */
157596  char *zMatchinfo;
157597  u32 aMatchinfo[1];
157598};
157599
157600
157601/*
157602** The snippet() and offsets() functions both return text values. An instance
157603** of the following structure is used to accumulate those values while the
157604** functions are running. See fts3StringAppend() for details.
157605*/
157606typedef struct StrBuffer StrBuffer;
157607struct StrBuffer {
157608  char *z;                        /* Pointer to buffer containing string */
157609  int n;                          /* Length of z in bytes (excl. nul-term) */
157610  int nAlloc;                     /* Allocated size of buffer z in bytes */
157611};
157612
157613
157614/*************************************************************************
157615** Start of MatchinfoBuffer code.
157616*/
157617
157618/*
157619** Allocate a two-slot MatchinfoBuffer object.
157620*/
157621static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
157622  MatchinfoBuffer *pRet;
157623  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
157624  int nStr = (int)strlen(zMatchinfo);
157625
157626  pRet = sqlite3_malloc(nByte + nStr+1);
157627  if( pRet ){
157628    memset(pRet, 0, nByte);
157629    pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
157630    pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
157631    pRet->nElem = nElem;
157632    pRet->zMatchinfo = ((char*)pRet) + nByte;
157633    memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
157634    pRet->aRef[0] = 1;
157635  }
157636
157637  return pRet;
157638}
157639
157640static void fts3MIBufferFree(void *p){
157641  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
157642
157643  assert( (u32*)p==&pBuf->aMatchinfo[1]
157644       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
157645  );
157646  if( (u32*)p==&pBuf->aMatchinfo[1] ){
157647    pBuf->aRef[1] = 0;
157648  }else{
157649    pBuf->aRef[2] = 0;
157650  }
157651
157652  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
157653    sqlite3_free(pBuf);
157654  }
157655}
157656
157657static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
157658  void (*xRet)(void*) = 0;
157659  u32 *aOut = 0;
157660
157661  if( p->aRef[1]==0 ){
157662    p->aRef[1] = 1;
157663    aOut = &p->aMatchinfo[1];
157664    xRet = fts3MIBufferFree;
157665  }
157666  else if( p->aRef[2]==0 ){
157667    p->aRef[2] = 1;
157668    aOut = &p->aMatchinfo[p->nElem+2];
157669    xRet = fts3MIBufferFree;
157670  }else{
157671    aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
157672    if( aOut ){
157673      xRet = sqlite3_free;
157674      if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
157675    }
157676  }
157677
157678  *paOut = aOut;
157679  return xRet;
157680}
157681
157682static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
157683  p->bGlobal = 1;
157684  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
157685}
157686
157687/*
157688** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
157689*/
157690SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
157691  if( p ){
157692    assert( p->aRef[0]==1 );
157693    p->aRef[0] = 0;
157694    if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
157695      sqlite3_free(p);
157696    }
157697  }
157698}
157699
157700/*
157701** End of MatchinfoBuffer code.
157702*************************************************************************/
157703
157704
157705/*
157706** This function is used to help iterate through a position-list. A position
157707** list is a list of unique integers, sorted from smallest to largest. Each
157708** element of the list is represented by an FTS3 varint that takes the value
157709** of the difference between the current element and the previous one plus
157710** two. For example, to store the position-list:
157711**
157712**     4 9 113
157713**
157714** the three varints:
157715**
157716**     6 7 106
157717**
157718** are encoded.
157719**
157720** When this function is called, *pp points to the start of an element of
157721** the list. *piPos contains the value of the previous entry in the list.
157722** After it returns, *piPos contains the value of the next element of the
157723** list and *pp is advanced to the following varint.
157724*/
157725static void fts3GetDeltaPosition(char **pp, int *piPos){
157726  int iVal;
157727  *pp += fts3GetVarint32(*pp, &iVal);
157728  *piPos += (iVal-2);
157729}
157730
157731/*
157732** Helper function for fts3ExprIterate() (see below).
157733*/
157734static int fts3ExprIterate2(
157735  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
157736  int *piPhrase,                  /* Pointer to phrase counter */
157737  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
157738  void *pCtx                      /* Second argument to pass to callback */
157739){
157740  int rc;                         /* Return code */
157741  int eType = pExpr->eType;     /* Type of expression node pExpr */
157742
157743  if( eType!=FTSQUERY_PHRASE ){
157744    assert( pExpr->pLeft && pExpr->pRight );
157745    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
157746    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
157747      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
157748    }
157749  }else{
157750    rc = x(pExpr, *piPhrase, pCtx);
157751    (*piPhrase)++;
157752  }
157753  return rc;
157754}
157755
157756/*
157757** Iterate through all phrase nodes in an FTS3 query, except those that
157758** are part of a sub-tree that is the right-hand-side of a NOT operator.
157759** For each phrase node found, the supplied callback function is invoked.
157760**
157761** If the callback function returns anything other than SQLITE_OK,
157762** the iteration is abandoned and the error code returned immediately.
157763** Otherwise, SQLITE_OK is returned after a callback has been made for
157764** all eligible phrase nodes.
157765*/
157766static int fts3ExprIterate(
157767  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
157768  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
157769  void *pCtx                      /* Second argument to pass to callback */
157770){
157771  int iPhrase = 0;                /* Variable used as the phrase counter */
157772  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
157773}
157774
157775
157776/*
157777** This is an fts3ExprIterate() callback used while loading the doclists
157778** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
157779** fts3ExprLoadDoclists().
157780*/
157781static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
157782  int rc = SQLITE_OK;
157783  Fts3Phrase *pPhrase = pExpr->pPhrase;
157784  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
157785
157786  UNUSED_PARAMETER(iPhrase);
157787
157788  p->nPhrase++;
157789  p->nToken += pPhrase->nToken;
157790
157791  return rc;
157792}
157793
157794/*
157795** Load the doclists for each phrase in the query associated with FTS3 cursor
157796** pCsr.
157797**
157798** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
157799** phrases in the expression (all phrases except those directly or
157800** indirectly descended from the right-hand-side of a NOT operator). If
157801** pnToken is not NULL, then it is set to the number of tokens in all
157802** matchable phrases of the expression.
157803*/
157804static int fts3ExprLoadDoclists(
157805  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
157806  int *pnPhrase,                  /* OUT: Number of phrases in query */
157807  int *pnToken                    /* OUT: Number of tokens in query */
157808){
157809  int rc;                         /* Return Code */
157810  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
157811  sCtx.pCsr = pCsr;
157812  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
157813  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
157814  if( pnToken ) *pnToken = sCtx.nToken;
157815  return rc;
157816}
157817
157818static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
157819  (*(int *)ctx)++;
157820  pExpr->iPhrase = iPhrase;
157821  return SQLITE_OK;
157822}
157823static int fts3ExprPhraseCount(Fts3Expr *pExpr){
157824  int nPhrase = 0;
157825  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
157826  return nPhrase;
157827}
157828
157829/*
157830** Advance the position list iterator specified by the first two
157831** arguments so that it points to the first element with a value greater
157832** than or equal to parameter iNext.
157833*/
157834static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
157835  char *pIter = *ppIter;
157836  if( pIter ){
157837    int iIter = *piIter;
157838
157839    while( iIter<iNext ){
157840      if( 0==(*pIter & 0xFE) ){
157841        iIter = -1;
157842        pIter = 0;
157843        break;
157844      }
157845      fts3GetDeltaPosition(&pIter, &iIter);
157846    }
157847
157848    *piIter = iIter;
157849    *ppIter = pIter;
157850  }
157851}
157852
157853/*
157854** Advance the snippet iterator to the next candidate snippet.
157855*/
157856static int fts3SnippetNextCandidate(SnippetIter *pIter){
157857  int i;                          /* Loop counter */
157858
157859  if( pIter->iCurrent<0 ){
157860    /* The SnippetIter object has just been initialized. The first snippet
157861    ** candidate always starts at offset 0 (even if this candidate has a
157862    ** score of 0.0).
157863    */
157864    pIter->iCurrent = 0;
157865
157866    /* Advance the 'head' iterator of each phrase to the first offset that
157867    ** is greater than or equal to (iNext+nSnippet).
157868    */
157869    for(i=0; i<pIter->nPhrase; i++){
157870      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157871      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
157872    }
157873  }else{
157874    int iStart;
157875    int iEnd = 0x7FFFFFFF;
157876
157877    for(i=0; i<pIter->nPhrase; i++){
157878      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157879      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
157880        iEnd = pPhrase->iHead;
157881      }
157882    }
157883    if( iEnd==0x7FFFFFFF ){
157884      return 1;
157885    }
157886
157887    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
157888    for(i=0; i<pIter->nPhrase; i++){
157889      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157890      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
157891      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
157892    }
157893  }
157894
157895  return 0;
157896}
157897
157898/*
157899** Retrieve information about the current candidate snippet of snippet
157900** iterator pIter.
157901*/
157902static void fts3SnippetDetails(
157903  SnippetIter *pIter,             /* Snippet iterator */
157904  u64 mCovered,                   /* Bitmask of phrases already covered */
157905  int *piToken,                   /* OUT: First token of proposed snippet */
157906  int *piScore,                   /* OUT: "Score" for this snippet */
157907  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
157908  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
157909){
157910  int iStart = pIter->iCurrent;   /* First token of snippet */
157911  int iScore = 0;                 /* Score of this snippet */
157912  int i;                          /* Loop counter */
157913  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
157914  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
157915
157916  for(i=0; i<pIter->nPhrase; i++){
157917    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157918    if( pPhrase->pTail ){
157919      char *pCsr = pPhrase->pTail;
157920      int iCsr = pPhrase->iTail;
157921
157922      while( iCsr<(iStart+pIter->nSnippet) ){
157923        int j;
157924        u64 mPhrase = (u64)1 << i;
157925        u64 mPos = (u64)1 << (iCsr - iStart);
157926        assert( iCsr>=iStart );
157927        if( (mCover|mCovered)&mPhrase ){
157928          iScore++;
157929        }else{
157930          iScore += 1000;
157931        }
157932        mCover |= mPhrase;
157933
157934        for(j=0; j<pPhrase->nToken; j++){
157935          mHighlight |= (mPos>>j);
157936        }
157937
157938        if( 0==(*pCsr & 0x0FE) ) break;
157939        fts3GetDeltaPosition(&pCsr, &iCsr);
157940      }
157941    }
157942  }
157943
157944  /* Set the output variables before returning. */
157945  *piToken = iStart;
157946  *piScore = iScore;
157947  *pmCover = mCover;
157948  *pmHighlight = mHighlight;
157949}
157950
157951/*
157952** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
157953** Each invocation populates an element of the SnippetIter.aPhrase[] array.
157954*/
157955static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
157956  SnippetIter *p = (SnippetIter *)ctx;
157957  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
157958  char *pCsr;
157959  int rc;
157960
157961  pPhrase->nToken = pExpr->pPhrase->nToken;
157962  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
157963  assert( rc==SQLITE_OK || pCsr==0 );
157964  if( pCsr ){
157965    int iFirst = 0;
157966    pPhrase->pList = pCsr;
157967    fts3GetDeltaPosition(&pCsr, &iFirst);
157968    assert( iFirst>=0 );
157969    pPhrase->pHead = pCsr;
157970    pPhrase->pTail = pCsr;
157971    pPhrase->iHead = iFirst;
157972    pPhrase->iTail = iFirst;
157973  }else{
157974    assert( rc!=SQLITE_OK || (
157975       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
157976    ));
157977  }
157978
157979  return rc;
157980}
157981
157982/*
157983** Select the fragment of text consisting of nFragment contiguous tokens
157984** from column iCol that represent the "best" snippet. The best snippet
157985** is the snippet with the highest score, where scores are calculated
157986** by adding:
157987**
157988**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
157989**
157990**   (b) +1000 points for the first occurrence of each matchable phrase in
157991**       the snippet for which the corresponding mCovered bit is not set.
157992**
157993** The selected snippet parameters are stored in structure *pFragment before
157994** returning. The score of the selected snippet is stored in *piScore
157995** before returning.
157996*/
157997static int fts3BestSnippet(
157998  int nSnippet,                   /* Desired snippet length */
157999  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
158000  int iCol,                       /* Index of column to create snippet from */
158001  u64 mCovered,                   /* Mask of phrases already covered */
158002  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
158003  SnippetFragment *pFragment,     /* OUT: Best snippet found */
158004  int *piScore                    /* OUT: Score of snippet pFragment */
158005){
158006  int rc;                         /* Return Code */
158007  int nList;                      /* Number of phrases in expression */
158008  SnippetIter sIter;              /* Iterates through snippet candidates */
158009  int nByte;                      /* Number of bytes of space to allocate */
158010  int iBestScore = -1;            /* Best snippet score found so far */
158011  int i;                          /* Loop counter */
158012
158013  memset(&sIter, 0, sizeof(sIter));
158014
158015  /* Iterate through the phrases in the expression to count them. The same
158016  ** callback makes sure the doclists are loaded for each phrase.
158017  */
158018  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
158019  if( rc!=SQLITE_OK ){
158020    return rc;
158021  }
158022
158023  /* Now that it is known how many phrases there are, allocate and zero
158024  ** the required space using malloc().
158025  */
158026  nByte = sizeof(SnippetPhrase) * nList;
158027  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
158028  if( !sIter.aPhrase ){
158029    return SQLITE_NOMEM;
158030  }
158031  memset(sIter.aPhrase, 0, nByte);
158032
158033  /* Initialize the contents of the SnippetIter object. Then iterate through
158034  ** the set of phrases in the expression to populate the aPhrase[] array.
158035  */
158036  sIter.pCsr = pCsr;
158037  sIter.iCol = iCol;
158038  sIter.nSnippet = nSnippet;
158039  sIter.nPhrase = nList;
158040  sIter.iCurrent = -1;
158041  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
158042  if( rc==SQLITE_OK ){
158043
158044    /* Set the *pmSeen output variable. */
158045    for(i=0; i<nList; i++){
158046      if( sIter.aPhrase[i].pHead ){
158047        *pmSeen |= (u64)1 << i;
158048      }
158049    }
158050
158051    /* Loop through all candidate snippets. Store the best snippet in
158052     ** *pFragment. Store its associated 'score' in iBestScore.
158053     */
158054    pFragment->iCol = iCol;
158055    while( !fts3SnippetNextCandidate(&sIter) ){
158056      int iPos;
158057      int iScore;
158058      u64 mCover;
158059      u64 mHighlite;
158060      fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
158061      assert( iScore>=0 );
158062      if( iScore>iBestScore ){
158063        pFragment->iPos = iPos;
158064        pFragment->hlmask = mHighlite;
158065        pFragment->covered = mCover;
158066        iBestScore = iScore;
158067      }
158068    }
158069
158070    *piScore = iBestScore;
158071  }
158072  sqlite3_free(sIter.aPhrase);
158073  return rc;
158074}
158075
158076
158077/*
158078** Append a string to the string-buffer passed as the first argument.
158079**
158080** If nAppend is negative, then the length of the string zAppend is
158081** determined using strlen().
158082*/
158083static int fts3StringAppend(
158084  StrBuffer *pStr,                /* Buffer to append to */
158085  const char *zAppend,            /* Pointer to data to append to buffer */
158086  int nAppend                     /* Size of zAppend in bytes (or -1) */
158087){
158088  if( nAppend<0 ){
158089    nAppend = (int)strlen(zAppend);
158090  }
158091
158092  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
158093  ** to grow the buffer until so that it is big enough to accomadate the
158094  ** appended data.
158095  */
158096  if( pStr->n+nAppend+1>=pStr->nAlloc ){
158097    int nAlloc = pStr->nAlloc+nAppend+100;
158098    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
158099    if( !zNew ){
158100      return SQLITE_NOMEM;
158101    }
158102    pStr->z = zNew;
158103    pStr->nAlloc = nAlloc;
158104  }
158105  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
158106
158107  /* Append the data to the string buffer. */
158108  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
158109  pStr->n += nAppend;
158110  pStr->z[pStr->n] = '\0';
158111
158112  return SQLITE_OK;
158113}
158114
158115/*
158116** The fts3BestSnippet() function often selects snippets that end with a
158117** query term. That is, the final term of the snippet is always a term
158118** that requires highlighting. For example, if 'X' is a highlighted term
158119** and '.' is a non-highlighted term, BestSnippet() may select:
158120**
158121**     ........X.....X
158122**
158123** This function "shifts" the beginning of the snippet forward in the
158124** document so that there are approximately the same number of
158125** non-highlighted terms to the right of the final highlighted term as there
158126** are to the left of the first highlighted term. For example, to this:
158127**
158128**     ....X.....X....
158129**
158130** This is done as part of extracting the snippet text, not when selecting
158131** the snippet. Snippet selection is done based on doclists only, so there
158132** is no way for fts3BestSnippet() to know whether or not the document
158133** actually contains terms that follow the final highlighted term.
158134*/
158135static int fts3SnippetShift(
158136  Fts3Table *pTab,                /* FTS3 table snippet comes from */
158137  int iLangid,                    /* Language id to use in tokenizing */
158138  int nSnippet,                   /* Number of tokens desired for snippet */
158139  const char *zDoc,               /* Document text to extract snippet from */
158140  int nDoc,                       /* Size of buffer zDoc in bytes */
158141  int *piPos,                     /* IN/OUT: First token of snippet */
158142  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
158143){
158144  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
158145
158146  if( hlmask ){
158147    int nLeft;                    /* Tokens to the left of first highlight */
158148    int nRight;                   /* Tokens to the right of last highlight */
158149    int nDesired;                 /* Ideal number of tokens to shift forward */
158150
158151    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
158152    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
158153    nDesired = (nLeft-nRight)/2;
158154
158155    /* Ideally, the start of the snippet should be pushed forward in the
158156    ** document nDesired tokens. This block checks if there are actually
158157    ** nDesired tokens to the right of the snippet. If so, *piPos and
158158    ** *pHlMask are updated to shift the snippet nDesired tokens to the
158159    ** right. Otherwise, the snippet is shifted by the number of tokens
158160    ** available.
158161    */
158162    if( nDesired>0 ){
158163      int nShift;                 /* Number of tokens to shift snippet by */
158164      int iCurrent = 0;           /* Token counter */
158165      int rc;                     /* Return Code */
158166      sqlite3_tokenizer_module *pMod;
158167      sqlite3_tokenizer_cursor *pC;
158168      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
158169
158170      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
158171      ** or more tokens in zDoc/nDoc.
158172      */
158173      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
158174      if( rc!=SQLITE_OK ){
158175        return rc;
158176      }
158177      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
158178        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
158179        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
158180      }
158181      pMod->xClose(pC);
158182      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
158183
158184      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
158185      assert( nShift<=nDesired );
158186      if( nShift>0 ){
158187        *piPos += nShift;
158188        *pHlmask = hlmask >> nShift;
158189      }
158190    }
158191  }
158192  return SQLITE_OK;
158193}
158194
158195/*
158196** Extract the snippet text for fragment pFragment from cursor pCsr and
158197** append it to string buffer pOut.
158198*/
158199static int fts3SnippetText(
158200  Fts3Cursor *pCsr,               /* FTS3 Cursor */
158201  SnippetFragment *pFragment,     /* Snippet to extract */
158202  int iFragment,                  /* Fragment number */
158203  int isLast,                     /* True for final fragment in snippet */
158204  int nSnippet,                   /* Number of tokens in extracted snippet */
158205  const char *zOpen,              /* String inserted before highlighted term */
158206  const char *zClose,             /* String inserted after highlighted term */
158207  const char *zEllipsis,          /* String inserted between snippets */
158208  StrBuffer *pOut                 /* Write output here */
158209){
158210  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158211  int rc;                         /* Return code */
158212  const char *zDoc;               /* Document text to extract snippet from */
158213  int nDoc;                       /* Size of zDoc in bytes */
158214  int iCurrent = 0;               /* Current token number of document */
158215  int iEnd = 0;                   /* Byte offset of end of current token */
158216  int isShiftDone = 0;            /* True after snippet is shifted */
158217  int iPos = pFragment->iPos;     /* First token of snippet */
158218  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
158219  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
158220  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
158221  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
158222
158223  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
158224  if( zDoc==0 ){
158225    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
158226      return SQLITE_NOMEM;
158227    }
158228    return SQLITE_OK;
158229  }
158230  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
158231
158232  /* Open a token cursor on the document. */
158233  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
158234  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
158235  if( rc!=SQLITE_OK ){
158236    return rc;
158237  }
158238
158239  while( rc==SQLITE_OK ){
158240    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
158241    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
158242    int iBegin = 0;               /* Offset in zDoc of start of token */
158243    int iFin = 0;                 /* Offset in zDoc of end of token */
158244    int isHighlight = 0;          /* True for highlighted terms */
158245
158246    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
158247    ** in the FTS code the variable that the third argument to xNext points to
158248    ** is initialized to zero before the first (*but not necessarily
158249    ** subsequent*) call to xNext(). This is done for a particular application
158250    ** that needs to know whether or not the tokenizer is being used for
158251    ** snippet generation or for some other purpose.
158252    **
158253    ** Extreme care is required when writing code to depend on this
158254    ** initialization. It is not a documented part of the tokenizer interface.
158255    ** If a tokenizer is used directly by any code outside of FTS, this
158256    ** convention might not be respected.  */
158257    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
158258    if( rc!=SQLITE_OK ){
158259      if( rc==SQLITE_DONE ){
158260        /* Special case - the last token of the snippet is also the last token
158261        ** of the column. Append any punctuation that occurred between the end
158262        ** of the previous token and the end of the document to the output.
158263        ** Then break out of the loop. */
158264        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
158265      }
158266      break;
158267    }
158268    if( iCurrent<iPos ){ continue; }
158269
158270    if( !isShiftDone ){
158271      int n = nDoc - iBegin;
158272      rc = fts3SnippetShift(
158273          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
158274      );
158275      isShiftDone = 1;
158276
158277      /* Now that the shift has been done, check if the initial "..." are
158278      ** required. They are required if (a) this is not the first fragment,
158279      ** or (b) this fragment does not begin at position 0 of its column.
158280      */
158281      if( rc==SQLITE_OK ){
158282        if( iPos>0 || iFragment>0 ){
158283          rc = fts3StringAppend(pOut, zEllipsis, -1);
158284        }else if( iBegin ){
158285          rc = fts3StringAppend(pOut, zDoc, iBegin);
158286        }
158287      }
158288      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
158289    }
158290
158291    if( iCurrent>=(iPos+nSnippet) ){
158292      if( isLast ){
158293        rc = fts3StringAppend(pOut, zEllipsis, -1);
158294      }
158295      break;
158296    }
158297
158298    /* Set isHighlight to true if this term should be highlighted. */
158299    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
158300
158301    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
158302    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
158303    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
158304    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
158305
158306    iEnd = iFin;
158307  }
158308
158309  pMod->xClose(pC);
158310  return rc;
158311}
158312
158313
158314/*
158315** This function is used to count the entries in a column-list (a
158316** delta-encoded list of term offsets within a single column of a single
158317** row). When this function is called, *ppCollist should point to the
158318** beginning of the first varint in the column-list (the varint that
158319** contains the position of the first matching term in the column data).
158320** Before returning, *ppCollist is set to point to the first byte after
158321** the last varint in the column-list (either the 0x00 signifying the end
158322** of the position-list, or the 0x01 that precedes the column number of
158323** the next column in the position-list).
158324**
158325** The number of elements in the column-list is returned.
158326*/
158327static int fts3ColumnlistCount(char **ppCollist){
158328  char *pEnd = *ppCollist;
158329  char c = 0;
158330  int nEntry = 0;
158331
158332  /* A column-list is terminated by either a 0x01 or 0x00. */
158333  while( 0xFE & (*pEnd | c) ){
158334    c = *pEnd++ & 0x80;
158335    if( !c ) nEntry++;
158336  }
158337
158338  *ppCollist = pEnd;
158339  return nEntry;
158340}
158341
158342/*
158343** This function gathers 'y' or 'b' data for a single phrase.
158344*/
158345static void fts3ExprLHits(
158346  Fts3Expr *pExpr,                /* Phrase expression node */
158347  MatchInfo *p                    /* Matchinfo context */
158348){
158349  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
158350  int iStart;
158351  Fts3Phrase *pPhrase = pExpr->pPhrase;
158352  char *pIter = pPhrase->doclist.pList;
158353  int iCol = 0;
158354
158355  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
158356  if( p->flag==FTS3_MATCHINFO_LHITS ){
158357    iStart = pExpr->iPhrase * p->nCol;
158358  }else{
158359    iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
158360  }
158361
158362  while( 1 ){
158363    int nHit = fts3ColumnlistCount(&pIter);
158364    if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
158365      if( p->flag==FTS3_MATCHINFO_LHITS ){
158366        p->aMatchinfo[iStart + iCol] = (u32)nHit;
158367      }else if( nHit ){
158368        p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
158369      }
158370    }
158371    assert( *pIter==0x00 || *pIter==0x01 );
158372    if( *pIter!=0x01 ) break;
158373    pIter++;
158374    pIter += fts3GetVarint32(pIter, &iCol);
158375  }
158376}
158377
158378/*
158379** Gather the results for matchinfo directives 'y' and 'b'.
158380*/
158381static void fts3ExprLHitGather(
158382  Fts3Expr *pExpr,
158383  MatchInfo *p
158384){
158385  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
158386  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
158387    if( pExpr->pLeft ){
158388      fts3ExprLHitGather(pExpr->pLeft, p);
158389      fts3ExprLHitGather(pExpr->pRight, p);
158390    }else{
158391      fts3ExprLHits(pExpr, p);
158392    }
158393  }
158394}
158395
158396/*
158397** fts3ExprIterate() callback used to collect the "global" matchinfo stats
158398** for a single query.
158399**
158400** fts3ExprIterate() callback to load the 'global' elements of a
158401** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
158402** of the matchinfo array that are constant for all rows returned by the
158403** current query.
158404**
158405** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
158406** function populates Matchinfo.aMatchinfo[] as follows:
158407**
158408**   for(iCol=0; iCol<nCol; iCol++){
158409**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
158410**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
158411**   }
158412**
158413** where X is the number of matches for phrase iPhrase is column iCol of all
158414** rows of the table. Y is the number of rows for which column iCol contains
158415** at least one instance of phrase iPhrase.
158416**
158417** If the phrase pExpr consists entirely of deferred tokens, then all X and
158418** Y values are set to nDoc, where nDoc is the number of documents in the
158419** file system. This is done because the full-text index doclist is required
158420** to calculate these values properly, and the full-text index doclist is
158421** not available for deferred tokens.
158422*/
158423static int fts3ExprGlobalHitsCb(
158424  Fts3Expr *pExpr,                /* Phrase expression node */
158425  int iPhrase,                    /* Phrase number (numbered from zero) */
158426  void *pCtx                      /* Pointer to MatchInfo structure */
158427){
158428  MatchInfo *p = (MatchInfo *)pCtx;
158429  return sqlite3Fts3EvalPhraseStats(
158430      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
158431  );
158432}
158433
158434/*
158435** fts3ExprIterate() callback used to collect the "local" part of the
158436** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
158437** array that are different for each row returned by the query.
158438*/
158439static int fts3ExprLocalHitsCb(
158440  Fts3Expr *pExpr,                /* Phrase expression node */
158441  int iPhrase,                    /* Phrase number */
158442  void *pCtx                      /* Pointer to MatchInfo structure */
158443){
158444  int rc = SQLITE_OK;
158445  MatchInfo *p = (MatchInfo *)pCtx;
158446  int iStart = iPhrase * p->nCol * 3;
158447  int i;
158448
158449  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
158450    char *pCsr;
158451    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
158452    if( pCsr ){
158453      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
158454    }else{
158455      p->aMatchinfo[iStart+i*3] = 0;
158456    }
158457  }
158458
158459  return rc;
158460}
158461
158462static int fts3MatchinfoCheck(
158463  Fts3Table *pTab,
158464  char cArg,
158465  char **pzErr
158466){
158467  if( (cArg==FTS3_MATCHINFO_NPHRASE)
158468   || (cArg==FTS3_MATCHINFO_NCOL)
158469   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
158470   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
158471   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
158472   || (cArg==FTS3_MATCHINFO_LCS)
158473   || (cArg==FTS3_MATCHINFO_HITS)
158474   || (cArg==FTS3_MATCHINFO_LHITS)
158475   || (cArg==FTS3_MATCHINFO_LHITS_BM)
158476  ){
158477    return SQLITE_OK;
158478  }
158479  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
158480  return SQLITE_ERROR;
158481}
158482
158483static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
158484  int nVal;                       /* Number of integers output by cArg */
158485
158486  switch( cArg ){
158487    case FTS3_MATCHINFO_NDOC:
158488    case FTS3_MATCHINFO_NPHRASE:
158489    case FTS3_MATCHINFO_NCOL:
158490      nVal = 1;
158491      break;
158492
158493    case FTS3_MATCHINFO_AVGLENGTH:
158494    case FTS3_MATCHINFO_LENGTH:
158495    case FTS3_MATCHINFO_LCS:
158496      nVal = pInfo->nCol;
158497      break;
158498
158499    case FTS3_MATCHINFO_LHITS:
158500      nVal = pInfo->nCol * pInfo->nPhrase;
158501      break;
158502
158503    case FTS3_MATCHINFO_LHITS_BM:
158504      nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
158505      break;
158506
158507    default:
158508      assert( cArg==FTS3_MATCHINFO_HITS );
158509      nVal = pInfo->nCol * pInfo->nPhrase * 3;
158510      break;
158511  }
158512
158513  return nVal;
158514}
158515
158516static int fts3MatchinfoSelectDoctotal(
158517  Fts3Table *pTab,
158518  sqlite3_stmt **ppStmt,
158519  sqlite3_int64 *pnDoc,
158520  const char **paLen
158521){
158522  sqlite3_stmt *pStmt;
158523  const char *a;
158524  sqlite3_int64 nDoc;
158525
158526  if( !*ppStmt ){
158527    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
158528    if( rc!=SQLITE_OK ) return rc;
158529  }
158530  pStmt = *ppStmt;
158531  assert( sqlite3_data_count(pStmt)==1 );
158532
158533  a = sqlite3_column_blob(pStmt, 0);
158534  a += sqlite3Fts3GetVarint(a, &nDoc);
158535  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
158536  *pnDoc = (u32)nDoc;
158537
158538  if( paLen ) *paLen = a;
158539  return SQLITE_OK;
158540}
158541
158542/*
158543** An instance of the following structure is used to store state while
158544** iterating through a multi-column position-list corresponding to the
158545** hits for a single phrase on a single row in order to calculate the
158546** values for a matchinfo() FTS3_MATCHINFO_LCS request.
158547*/
158548typedef struct LcsIterator LcsIterator;
158549struct LcsIterator {
158550  Fts3Expr *pExpr;                /* Pointer to phrase expression */
158551  int iPosOffset;                 /* Tokens count up to end of this phrase */
158552  char *pRead;                    /* Cursor used to iterate through aDoclist */
158553  int iPos;                       /* Current position */
158554};
158555
158556/*
158557** If LcsIterator.iCol is set to the following value, the iterator has
158558** finished iterating through all offsets for all columns.
158559*/
158560#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
158561
158562static int fts3MatchinfoLcsCb(
158563  Fts3Expr *pExpr,                /* Phrase expression node */
158564  int iPhrase,                    /* Phrase number (numbered from zero) */
158565  void *pCtx                      /* Pointer to MatchInfo structure */
158566){
158567  LcsIterator *aIter = (LcsIterator *)pCtx;
158568  aIter[iPhrase].pExpr = pExpr;
158569  return SQLITE_OK;
158570}
158571
158572/*
158573** Advance the iterator passed as an argument to the next position. Return
158574** 1 if the iterator is at EOF or if it now points to the start of the
158575** position list for the next column.
158576*/
158577static int fts3LcsIteratorAdvance(LcsIterator *pIter){
158578  char *pRead = pIter->pRead;
158579  sqlite3_int64 iRead;
158580  int rc = 0;
158581
158582  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
158583  if( iRead==0 || iRead==1 ){
158584    pRead = 0;
158585    rc = 1;
158586  }else{
158587    pIter->iPos += (int)(iRead-2);
158588  }
158589
158590  pIter->pRead = pRead;
158591  return rc;
158592}
158593
158594/*
158595** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
158596**
158597** If the call is successful, the longest-common-substring lengths for each
158598** column are written into the first nCol elements of the pInfo->aMatchinfo[]
158599** array before returning. SQLITE_OK is returned in this case.
158600**
158601** Otherwise, if an error occurs, an SQLite error code is returned and the
158602** data written to the first nCol elements of pInfo->aMatchinfo[] is
158603** undefined.
158604*/
158605static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
158606  LcsIterator *aIter;
158607  int i;
158608  int iCol;
158609  int nToken = 0;
158610
158611  /* Allocate and populate the array of LcsIterator objects. The array
158612  ** contains one element for each matchable phrase in the query.
158613  **/
158614  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
158615  if( !aIter ) return SQLITE_NOMEM;
158616  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
158617  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
158618
158619  for(i=0; i<pInfo->nPhrase; i++){
158620    LcsIterator *pIter = &aIter[i];
158621    nToken -= pIter->pExpr->pPhrase->nToken;
158622    pIter->iPosOffset = nToken;
158623  }
158624
158625  for(iCol=0; iCol<pInfo->nCol; iCol++){
158626    int nLcs = 0;                 /* LCS value for this column */
158627    int nLive = 0;                /* Number of iterators in aIter not at EOF */
158628
158629    for(i=0; i<pInfo->nPhrase; i++){
158630      int rc;
158631      LcsIterator *pIt = &aIter[i];
158632      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
158633      if( rc!=SQLITE_OK ) return rc;
158634      if( pIt->pRead ){
158635        pIt->iPos = pIt->iPosOffset;
158636        fts3LcsIteratorAdvance(&aIter[i]);
158637        nLive++;
158638      }
158639    }
158640
158641    while( nLive>0 ){
158642      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
158643      int nThisLcs = 0;           /* LCS for the current iterator positions */
158644
158645      for(i=0; i<pInfo->nPhrase; i++){
158646        LcsIterator *pIter = &aIter[i];
158647        if( pIter->pRead==0 ){
158648          /* This iterator is already at EOF for this column. */
158649          nThisLcs = 0;
158650        }else{
158651          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
158652            pAdv = pIter;
158653          }
158654          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
158655            nThisLcs++;
158656          }else{
158657            nThisLcs = 1;
158658          }
158659          if( nThisLcs>nLcs ) nLcs = nThisLcs;
158660        }
158661      }
158662      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
158663    }
158664
158665    pInfo->aMatchinfo[iCol] = nLcs;
158666  }
158667
158668  sqlite3_free(aIter);
158669  return SQLITE_OK;
158670}
158671
158672/*
158673** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
158674** be returned by the matchinfo() function. Argument zArg contains the
158675** format string passed as the second argument to matchinfo (or the
158676** default value "pcx" if no second argument was specified). The format
158677** string has already been validated and the pInfo->aMatchinfo[] array
158678** is guaranteed to be large enough for the output.
158679**
158680** If bGlobal is true, then populate all fields of the matchinfo() output.
158681** If it is false, then assume that those fields that do not change between
158682** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
158683** have already been populated.
158684**
158685** Return SQLITE_OK if successful, or an SQLite error code if an error
158686** occurs. If a value other than SQLITE_OK is returned, the state the
158687** pInfo->aMatchinfo[] buffer is left in is undefined.
158688*/
158689static int fts3MatchinfoValues(
158690  Fts3Cursor *pCsr,               /* FTS3 cursor object */
158691  int bGlobal,                    /* True to grab the global stats */
158692  MatchInfo *pInfo,               /* Matchinfo context object */
158693  const char *zArg                /* Matchinfo format string */
158694){
158695  int rc = SQLITE_OK;
158696  int i;
158697  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158698  sqlite3_stmt *pSelect = 0;
158699
158700  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
158701    pInfo->flag = zArg[i];
158702    switch( zArg[i] ){
158703      case FTS3_MATCHINFO_NPHRASE:
158704        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
158705        break;
158706
158707      case FTS3_MATCHINFO_NCOL:
158708        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
158709        break;
158710
158711      case FTS3_MATCHINFO_NDOC:
158712        if( bGlobal ){
158713          sqlite3_int64 nDoc = 0;
158714          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
158715          pInfo->aMatchinfo[0] = (u32)nDoc;
158716        }
158717        break;
158718
158719      case FTS3_MATCHINFO_AVGLENGTH:
158720        if( bGlobal ){
158721          sqlite3_int64 nDoc;     /* Number of rows in table */
158722          const char *a;          /* Aggregate column length array */
158723
158724          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
158725          if( rc==SQLITE_OK ){
158726            int iCol;
158727            for(iCol=0; iCol<pInfo->nCol; iCol++){
158728              u32 iVal;
158729              sqlite3_int64 nToken;
158730              a += sqlite3Fts3GetVarint(a, &nToken);
158731              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
158732              pInfo->aMatchinfo[iCol] = iVal;
158733            }
158734          }
158735        }
158736        break;
158737
158738      case FTS3_MATCHINFO_LENGTH: {
158739        sqlite3_stmt *pSelectDocsize = 0;
158740        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
158741        if( rc==SQLITE_OK ){
158742          int iCol;
158743          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
158744          for(iCol=0; iCol<pInfo->nCol; iCol++){
158745            sqlite3_int64 nToken;
158746            a += sqlite3Fts3GetVarint(a, &nToken);
158747            pInfo->aMatchinfo[iCol] = (u32)nToken;
158748          }
158749        }
158750        sqlite3_reset(pSelectDocsize);
158751        break;
158752      }
158753
158754      case FTS3_MATCHINFO_LCS:
158755        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
158756        if( rc==SQLITE_OK ){
158757          rc = fts3MatchinfoLcs(pCsr, pInfo);
158758        }
158759        break;
158760
158761      case FTS3_MATCHINFO_LHITS_BM:
158762      case FTS3_MATCHINFO_LHITS: {
158763        int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
158764        memset(pInfo->aMatchinfo, 0, nZero);
158765        fts3ExprLHitGather(pCsr->pExpr, pInfo);
158766        break;
158767      }
158768
158769      default: {
158770        Fts3Expr *pExpr;
158771        assert( zArg[i]==FTS3_MATCHINFO_HITS );
158772        pExpr = pCsr->pExpr;
158773        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
158774        if( rc!=SQLITE_OK ) break;
158775        if( bGlobal ){
158776          if( pCsr->pDeferred ){
158777            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
158778            if( rc!=SQLITE_OK ) break;
158779          }
158780          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
158781          sqlite3Fts3EvalTestDeferred(pCsr, &rc);
158782          if( rc!=SQLITE_OK ) break;
158783        }
158784        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
158785        break;
158786      }
158787    }
158788
158789    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
158790  }
158791
158792  sqlite3_reset(pSelect);
158793  return rc;
158794}
158795
158796
158797/*
158798** Populate pCsr->aMatchinfo[] with data for the current row. The
158799** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
158800*/
158801static void fts3GetMatchinfo(
158802  sqlite3_context *pCtx,        /* Return results here */
158803  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
158804  const char *zArg                /* Second argument to matchinfo() function */
158805){
158806  MatchInfo sInfo;
158807  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158808  int rc = SQLITE_OK;
158809  int bGlobal = 0;                /* Collect 'global' stats as well as local */
158810
158811  u32 *aOut = 0;
158812  void (*xDestroyOut)(void*) = 0;
158813
158814  memset(&sInfo, 0, sizeof(MatchInfo));
158815  sInfo.pCursor = pCsr;
158816  sInfo.nCol = pTab->nColumn;
158817
158818  /* If there is cached matchinfo() data, but the format string for the
158819  ** cache does not match the format string for this request, discard
158820  ** the cached data. */
158821  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
158822    sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
158823    pCsr->pMIBuffer = 0;
158824  }
158825
158826  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
158827  ** matchinfo function has been called for this query. In this case
158828  ** allocate the array used to accumulate the matchinfo data and
158829  ** initialize those elements that are constant for every row.
158830  */
158831  if( pCsr->pMIBuffer==0 ){
158832    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
158833    int i;                        /* Used to iterate through zArg */
158834
158835    /* Determine the number of phrases in the query */
158836    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
158837    sInfo.nPhrase = pCsr->nPhrase;
158838
158839    /* Determine the number of integers in the buffer returned by this call. */
158840    for(i=0; zArg[i]; i++){
158841      char *zErr = 0;
158842      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
158843        sqlite3_result_error(pCtx, zErr, -1);
158844        sqlite3_free(zErr);
158845        return;
158846      }
158847      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
158848    }
158849
158850    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
158851    pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
158852    if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
158853
158854    pCsr->isMatchinfoNeeded = 1;
158855    bGlobal = 1;
158856  }
158857
158858  if( rc==SQLITE_OK ){
158859    xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
158860    if( xDestroyOut==0 ){
158861      rc = SQLITE_NOMEM;
158862    }
158863  }
158864
158865  if( rc==SQLITE_OK ){
158866    sInfo.aMatchinfo = aOut;
158867    sInfo.nPhrase = pCsr->nPhrase;
158868    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
158869    if( bGlobal ){
158870      fts3MIBufferSetGlobal(pCsr->pMIBuffer);
158871    }
158872  }
158873
158874  if( rc!=SQLITE_OK ){
158875    sqlite3_result_error_code(pCtx, rc);
158876    if( xDestroyOut ) xDestroyOut(aOut);
158877  }else{
158878    int n = pCsr->pMIBuffer->nElem * sizeof(u32);
158879    sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
158880  }
158881}
158882
158883/*
158884** Implementation of snippet() function.
158885*/
158886SQLITE_PRIVATE void sqlite3Fts3Snippet(
158887  sqlite3_context *pCtx,          /* SQLite function call context */
158888  Fts3Cursor *pCsr,               /* Cursor object */
158889  const char *zStart,             /* Snippet start text - "<b>" */
158890  const char *zEnd,               /* Snippet end text - "</b>" */
158891  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
158892  int iCol,                       /* Extract snippet from this column */
158893  int nToken                      /* Approximate number of tokens in snippet */
158894){
158895  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158896  int rc = SQLITE_OK;
158897  int i;
158898  StrBuffer res = {0, 0, 0};
158899
158900  /* The returned text includes up to four fragments of text extracted from
158901  ** the data in the current row. The first iteration of the for(...) loop
158902  ** below attempts to locate a single fragment of text nToken tokens in
158903  ** size that contains at least one instance of all phrases in the query
158904  ** expression that appear in the current row. If such a fragment of text
158905  ** cannot be found, the second iteration of the loop attempts to locate
158906  ** a pair of fragments, and so on.
158907  */
158908  int nSnippet = 0;               /* Number of fragments in this snippet */
158909  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
158910  int nFToken = -1;               /* Number of tokens in each fragment */
158911
158912  if( !pCsr->pExpr ){
158913    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
158914    return;
158915  }
158916
158917  for(nSnippet=1; 1; nSnippet++){
158918
158919    int iSnip;                    /* Loop counter 0..nSnippet-1 */
158920    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
158921    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
158922
158923    if( nToken>=0 ){
158924      nFToken = (nToken+nSnippet-1) / nSnippet;
158925    }else{
158926      nFToken = -1 * nToken;
158927    }
158928
158929    for(iSnip=0; iSnip<nSnippet; iSnip++){
158930      int iBestScore = -1;        /* Best score of columns checked so far */
158931      int iRead;                  /* Used to iterate through columns */
158932      SnippetFragment *pFragment = &aSnippet[iSnip];
158933
158934      memset(pFragment, 0, sizeof(*pFragment));
158935
158936      /* Loop through all columns of the table being considered for snippets.
158937      ** If the iCol argument to this function was negative, this means all
158938      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
158939      */
158940      for(iRead=0; iRead<pTab->nColumn; iRead++){
158941        SnippetFragment sF = {0, 0, 0, 0};
158942        int iS = 0;
158943        if( iCol>=0 && iRead!=iCol ) continue;
158944
158945        /* Find the best snippet of nFToken tokens in column iRead. */
158946        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
158947        if( rc!=SQLITE_OK ){
158948          goto snippet_out;
158949        }
158950        if( iS>iBestScore ){
158951          *pFragment = sF;
158952          iBestScore = iS;
158953        }
158954      }
158955
158956      mCovered |= pFragment->covered;
158957    }
158958
158959    /* If all query phrases seen by fts3BestSnippet() are present in at least
158960    ** one of the nSnippet snippet fragments, break out of the loop.
158961    */
158962    assert( (mCovered&mSeen)==mCovered );
158963    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
158964  }
158965
158966  assert( nFToken>0 );
158967
158968  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
158969    rc = fts3SnippetText(pCsr, &aSnippet[i],
158970        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
158971    );
158972  }
158973
158974 snippet_out:
158975  sqlite3Fts3SegmentsClose(pTab);
158976  if( rc!=SQLITE_OK ){
158977    sqlite3_result_error_code(pCtx, rc);
158978    sqlite3_free(res.z);
158979  }else{
158980    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
158981  }
158982}
158983
158984
158985typedef struct TermOffset TermOffset;
158986typedef struct TermOffsetCtx TermOffsetCtx;
158987
158988struct TermOffset {
158989  char *pList;                    /* Position-list */
158990  int iPos;                       /* Position just read from pList */
158991  int iOff;                       /* Offset of this term from read positions */
158992};
158993
158994struct TermOffsetCtx {
158995  Fts3Cursor *pCsr;
158996  int iCol;                       /* Column of table to populate aTerm for */
158997  int iTerm;
158998  sqlite3_int64 iDocid;
158999  TermOffset *aTerm;
159000};
159001
159002/*
159003** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
159004*/
159005static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
159006  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
159007  int nTerm;                      /* Number of tokens in phrase */
159008  int iTerm;                      /* For looping through nTerm phrase terms */
159009  char *pList;                    /* Pointer to position list for phrase */
159010  int iPos = 0;                   /* First position in position-list */
159011  int rc;
159012
159013  UNUSED_PARAMETER(iPhrase);
159014  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
159015  nTerm = pExpr->pPhrase->nToken;
159016  if( pList ){
159017    fts3GetDeltaPosition(&pList, &iPos);
159018    assert( iPos>=0 );
159019  }
159020
159021  for(iTerm=0; iTerm<nTerm; iTerm++){
159022    TermOffset *pT = &p->aTerm[p->iTerm++];
159023    pT->iOff = nTerm-iTerm-1;
159024    pT->pList = pList;
159025    pT->iPos = iPos;
159026  }
159027
159028  return rc;
159029}
159030
159031/*
159032** Implementation of offsets() function.
159033*/
159034SQLITE_PRIVATE void sqlite3Fts3Offsets(
159035  sqlite3_context *pCtx,          /* SQLite function call context */
159036  Fts3Cursor *pCsr                /* Cursor object */
159037){
159038  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159039  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
159040  int rc;                         /* Return Code */
159041  int nToken;                     /* Number of tokens in query */
159042  int iCol;                       /* Column currently being processed */
159043  StrBuffer res = {0, 0, 0};      /* Result string */
159044  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
159045
159046  if( !pCsr->pExpr ){
159047    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
159048    return;
159049  }
159050
159051  memset(&sCtx, 0, sizeof(sCtx));
159052  assert( pCsr->isRequireSeek==0 );
159053
159054  /* Count the number of terms in the query */
159055  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
159056  if( rc!=SQLITE_OK ) goto offsets_out;
159057
159058  /* Allocate the array of TermOffset iterators. */
159059  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
159060  if( 0==sCtx.aTerm ){
159061    rc = SQLITE_NOMEM;
159062    goto offsets_out;
159063  }
159064  sCtx.iDocid = pCsr->iPrevId;
159065  sCtx.pCsr = pCsr;
159066
159067  /* Loop through the table columns, appending offset information to
159068  ** string-buffer res for each column.
159069  */
159070  for(iCol=0; iCol<pTab->nColumn; iCol++){
159071    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
159072    const char *ZDUMMY;           /* Dummy argument used with xNext() */
159073    int NDUMMY = 0;               /* Dummy argument used with xNext() */
159074    int iStart = 0;
159075    int iEnd = 0;
159076    int iCurrent = 0;
159077    const char *zDoc;
159078    int nDoc;
159079
159080    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
159081    ** no way that this operation can fail, so the return code from
159082    ** fts3ExprIterate() can be discarded.
159083    */
159084    sCtx.iCol = iCol;
159085    sCtx.iTerm = 0;
159086    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
159087
159088    /* Retreive the text stored in column iCol. If an SQL NULL is stored
159089    ** in column iCol, jump immediately to the next iteration of the loop.
159090    ** If an OOM occurs while retrieving the data (this can happen if SQLite
159091    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
159092    ** to the caller.
159093    */
159094    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
159095    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
159096    if( zDoc==0 ){
159097      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
159098        continue;
159099      }
159100      rc = SQLITE_NOMEM;
159101      goto offsets_out;
159102    }
159103
159104    /* Initialize a tokenizer iterator to iterate through column iCol. */
159105    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
159106        zDoc, nDoc, &pC
159107    );
159108    if( rc!=SQLITE_OK ) goto offsets_out;
159109
159110    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
159111    while( rc==SQLITE_OK ){
159112      int i;                      /* Used to loop through terms */
159113      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
159114      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
159115
159116      for(i=0; i<nToken; i++){
159117        TermOffset *pT = &sCtx.aTerm[i];
159118        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
159119          iMinPos = pT->iPos-pT->iOff;
159120          pTerm = pT;
159121        }
159122      }
159123
159124      if( !pTerm ){
159125        /* All offsets for this column have been gathered. */
159126        rc = SQLITE_DONE;
159127      }else{
159128        assert( iCurrent<=iMinPos );
159129        if( 0==(0xFE&*pTerm->pList) ){
159130          pTerm->pList = 0;
159131        }else{
159132          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
159133        }
159134        while( rc==SQLITE_OK && iCurrent<iMinPos ){
159135          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
159136        }
159137        if( rc==SQLITE_OK ){
159138          char aBuffer[64];
159139          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
159140              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
159141          );
159142          rc = fts3StringAppend(&res, aBuffer, -1);
159143        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
159144          rc = FTS_CORRUPT_VTAB;
159145        }
159146      }
159147    }
159148    if( rc==SQLITE_DONE ){
159149      rc = SQLITE_OK;
159150    }
159151
159152    pMod->xClose(pC);
159153    if( rc!=SQLITE_OK ) goto offsets_out;
159154  }
159155
159156 offsets_out:
159157  sqlite3_free(sCtx.aTerm);
159158  assert( rc!=SQLITE_DONE );
159159  sqlite3Fts3SegmentsClose(pTab);
159160  if( rc!=SQLITE_OK ){
159161    sqlite3_result_error_code(pCtx,  rc);
159162    sqlite3_free(res.z);
159163  }else{
159164    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
159165  }
159166  return;
159167}
159168
159169/*
159170** Implementation of matchinfo() function.
159171*/
159172SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
159173  sqlite3_context *pContext,      /* Function call context */
159174  Fts3Cursor *pCsr,               /* FTS3 table cursor */
159175  const char *zArg                /* Second arg to matchinfo() function */
159176){
159177  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159178  const char *zFormat;
159179
159180  if( zArg ){
159181    zFormat = zArg;
159182  }else{
159183    zFormat = FTS3_MATCHINFO_DEFAULT;
159184  }
159185
159186  if( !pCsr->pExpr ){
159187    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
159188    return;
159189  }else{
159190    /* Retrieve matchinfo() data. */
159191    fts3GetMatchinfo(pContext, pCsr, zFormat);
159192    sqlite3Fts3SegmentsClose(pTab);
159193  }
159194}
159195
159196#endif
159197
159198/************** End of fts3_snippet.c ****************************************/
159199/************** Begin file fts3_unicode.c ************************************/
159200/*
159201** 2012 May 24
159202**
159203** The author disclaims copyright to this source code.  In place of
159204** a legal notice, here is a blessing:
159205**
159206**    May you do good and not evil.
159207**    May you find forgiveness for yourself and forgive others.
159208**    May you share freely, never taking more than you give.
159209**
159210******************************************************************************
159211**
159212** Implementation of the "unicode" full-text-search tokenizer.
159213*/
159214
159215#ifndef SQLITE_DISABLE_FTS3_UNICODE
159216
159217/* #include "fts3Int.h" */
159218#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
159219
159220/* #include <assert.h> */
159221/* #include <stdlib.h> */
159222/* #include <stdio.h> */
159223/* #include <string.h> */
159224
159225/* #include "fts3_tokenizer.h" */
159226
159227/*
159228** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
159229** from the sqlite3 source file utf.c. If this file is compiled as part
159230** of the amalgamation, they are not required.
159231*/
159232#ifndef SQLITE_AMALGAMATION
159233
159234static const unsigned char sqlite3Utf8Trans1[] = {
159235  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159236  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
159237  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
159238  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
159239  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159240  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
159241  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159242  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
159243};
159244
159245#define READ_UTF8(zIn, zTerm, c)                           \
159246  c = *(zIn++);                                            \
159247  if( c>=0xc0 ){                                           \
159248    c = sqlite3Utf8Trans1[c-0xc0];                         \
159249    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
159250      c = (c<<6) + (0x3f & *(zIn++));                      \
159251    }                                                      \
159252    if( c<0x80                                             \
159253        || (c&0xFFFFF800)==0xD800                          \
159254        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
159255  }
159256
159257#define WRITE_UTF8(zOut, c) {                          \
159258  if( c<0x00080 ){                                     \
159259    *zOut++ = (u8)(c&0xFF);                            \
159260  }                                                    \
159261  else if( c<0x00800 ){                                \
159262    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
159263    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159264  }                                                    \
159265  else if( c<0x10000 ){                                \
159266    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
159267    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
159268    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159269  }else{                                               \
159270    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
159271    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
159272    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
159273    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159274  }                                                    \
159275}
159276
159277#endif /* ifndef SQLITE_AMALGAMATION */
159278
159279typedef struct unicode_tokenizer unicode_tokenizer;
159280typedef struct unicode_cursor unicode_cursor;
159281
159282struct unicode_tokenizer {
159283  sqlite3_tokenizer base;
159284  int bRemoveDiacritic;
159285  int nException;
159286  int *aiException;
159287};
159288
159289struct unicode_cursor {
159290  sqlite3_tokenizer_cursor base;
159291  const unsigned char *aInput;    /* Input text being tokenized */
159292  int nInput;                     /* Size of aInput[] in bytes */
159293  int iOff;                       /* Current offset within aInput[] */
159294  int iToken;                     /* Index of next token to be returned */
159295  char *zToken;                   /* storage for current token */
159296  int nAlloc;                     /* space allocated at zToken */
159297};
159298
159299
159300/*
159301** Destroy a tokenizer allocated by unicodeCreate().
159302*/
159303static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
159304  if( pTokenizer ){
159305    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
159306    sqlite3_free(p->aiException);
159307    sqlite3_free(p);
159308  }
159309  return SQLITE_OK;
159310}
159311
159312/*
159313** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
159314** statement has specified that the tokenizer for this table shall consider
159315** all characters in string zIn/nIn to be separators (if bAlnum==0) or
159316** token characters (if bAlnum==1).
159317**
159318** For each codepoint in the zIn/nIn string, this function checks if the
159319** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
159320** If so, no action is taken. Otherwise, the codepoint is added to the
159321** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
159322** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
159323** codepoints in the aiException[] array.
159324**
159325** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
159326** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
159327** It is not possible to change the behavior of the tokenizer with respect
159328** to these codepoints.
159329*/
159330static int unicodeAddExceptions(
159331  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
159332  int bAlnum,                     /* Replace Isalnum() return value with this */
159333  const char *zIn,                /* Array of characters to make exceptions */
159334  int nIn                         /* Length of z in bytes */
159335){
159336  const unsigned char *z = (const unsigned char *)zIn;
159337  const unsigned char *zTerm = &z[nIn];
159338  int iCode;
159339  int nEntry = 0;
159340
159341  assert( bAlnum==0 || bAlnum==1 );
159342
159343  while( z<zTerm ){
159344    READ_UTF8(z, zTerm, iCode);
159345    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
159346    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
159347     && sqlite3FtsUnicodeIsdiacritic(iCode)==0
159348    ){
159349      nEntry++;
159350    }
159351  }
159352
159353  if( nEntry ){
159354    int *aNew;                    /* New aiException[] array */
159355    int nNew;                     /* Number of valid entries in array aNew[] */
159356
159357    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
159358    if( aNew==0 ) return SQLITE_NOMEM;
159359    nNew = p->nException;
159360
159361    z = (const unsigned char *)zIn;
159362    while( z<zTerm ){
159363      READ_UTF8(z, zTerm, iCode);
159364      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
159365       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
159366      ){
159367        int i, j;
159368        for(i=0; i<nNew && aNew[i]<iCode; i++);
159369        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
159370        aNew[i] = iCode;
159371        nNew++;
159372      }
159373    }
159374    p->aiException = aNew;
159375    p->nException = nNew;
159376  }
159377
159378  return SQLITE_OK;
159379}
159380
159381/*
159382** Return true if the p->aiException[] array contains the value iCode.
159383*/
159384static int unicodeIsException(unicode_tokenizer *p, int iCode){
159385  if( p->nException>0 ){
159386    int *a = p->aiException;
159387    int iLo = 0;
159388    int iHi = p->nException-1;
159389
159390    while( iHi>=iLo ){
159391      int iTest = (iHi + iLo) / 2;
159392      if( iCode==a[iTest] ){
159393        return 1;
159394      }else if( iCode>a[iTest] ){
159395        iLo = iTest+1;
159396      }else{
159397        iHi = iTest-1;
159398      }
159399    }
159400  }
159401
159402  return 0;
159403}
159404
159405/*
159406** Return true if, for the purposes of tokenization, codepoint iCode is
159407** considered a token character (not a separator).
159408*/
159409static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
159410  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
159411  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
159412}
159413
159414/*
159415** Create a new tokenizer instance.
159416*/
159417static int unicodeCreate(
159418  int nArg,                       /* Size of array argv[] */
159419  const char * const *azArg,      /* Tokenizer creation arguments */
159420  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
159421){
159422  unicode_tokenizer *pNew;        /* New tokenizer object */
159423  int i;
159424  int rc = SQLITE_OK;
159425
159426  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
159427  if( pNew==NULL ) return SQLITE_NOMEM;
159428  memset(pNew, 0, sizeof(unicode_tokenizer));
159429  pNew->bRemoveDiacritic = 1;
159430
159431  for(i=0; rc==SQLITE_OK && i<nArg; i++){
159432    const char *z = azArg[i];
159433    int n = (int)strlen(z);
159434
159435    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
159436      pNew->bRemoveDiacritic = 1;
159437    }
159438    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
159439      pNew->bRemoveDiacritic = 0;
159440    }
159441    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
159442      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
159443    }
159444    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
159445      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
159446    }
159447    else{
159448      /* Unrecognized argument */
159449      rc  = SQLITE_ERROR;
159450    }
159451  }
159452
159453  if( rc!=SQLITE_OK ){
159454    unicodeDestroy((sqlite3_tokenizer *)pNew);
159455    pNew = 0;
159456  }
159457  *pp = (sqlite3_tokenizer *)pNew;
159458  return rc;
159459}
159460
159461/*
159462** Prepare to begin tokenizing a particular string.  The input
159463** string to be tokenized is pInput[0..nBytes-1].  A cursor
159464** used to incrementally tokenize this string is returned in
159465** *ppCursor.
159466*/
159467static int unicodeOpen(
159468  sqlite3_tokenizer *p,           /* The tokenizer */
159469  const char *aInput,             /* Input string */
159470  int nInput,                     /* Size of string aInput in bytes */
159471  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
159472){
159473  unicode_cursor *pCsr;
159474
159475  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
159476  if( pCsr==0 ){
159477    return SQLITE_NOMEM;
159478  }
159479  memset(pCsr, 0, sizeof(unicode_cursor));
159480
159481  pCsr->aInput = (const unsigned char *)aInput;
159482  if( aInput==0 ){
159483    pCsr->nInput = 0;
159484  }else if( nInput<0 ){
159485    pCsr->nInput = (int)strlen(aInput);
159486  }else{
159487    pCsr->nInput = nInput;
159488  }
159489
159490  *pp = &pCsr->base;
159491  UNUSED_PARAMETER(p);
159492  return SQLITE_OK;
159493}
159494
159495/*
159496** Close a tokenization cursor previously opened by a call to
159497** simpleOpen() above.
159498*/
159499static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
159500  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
159501  sqlite3_free(pCsr->zToken);
159502  sqlite3_free(pCsr);
159503  return SQLITE_OK;
159504}
159505
159506/*
159507** Extract the next token from a tokenization cursor.  The cursor must
159508** have been opened by a prior call to simpleOpen().
159509*/
159510static int unicodeNext(
159511  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
159512  const char **paToken,           /* OUT: Token text */
159513  int *pnToken,                   /* OUT: Number of bytes at *paToken */
159514  int *piStart,                   /* OUT: Starting offset of token */
159515  int *piEnd,                     /* OUT: Ending offset of token */
159516  int *piPos                      /* OUT: Position integer of token */
159517){
159518  unicode_cursor *pCsr = (unicode_cursor *)pC;
159519  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
159520  int iCode = 0;
159521  char *zOut;
159522  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
159523  const unsigned char *zStart = z;
159524  const unsigned char *zEnd;
159525  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
159526
159527  /* Scan past any delimiter characters before the start of the next token.
159528  ** Return SQLITE_DONE early if this takes us all the way to the end of
159529  ** the input.  */
159530  while( z<zTerm ){
159531    READ_UTF8(z, zTerm, iCode);
159532    if( unicodeIsAlnum(p, iCode) ) break;
159533    zStart = z;
159534  }
159535  if( zStart>=zTerm ) return SQLITE_DONE;
159536
159537  zOut = pCsr->zToken;
159538  do {
159539    int iOut;
159540
159541    /* Grow the output buffer if required. */
159542    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
159543      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
159544      if( !zNew ) return SQLITE_NOMEM;
159545      zOut = &zNew[zOut - pCsr->zToken];
159546      pCsr->zToken = zNew;
159547      pCsr->nAlloc += 64;
159548    }
159549
159550    /* Write the folded case of the last character read to the output */
159551    zEnd = z;
159552    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
159553    if( iOut ){
159554      WRITE_UTF8(zOut, iOut);
159555    }
159556
159557    /* If the cursor is not at EOF, read the next character */
159558    if( z>=zTerm ) break;
159559    READ_UTF8(z, zTerm, iCode);
159560  }while( unicodeIsAlnum(p, iCode)
159561       || sqlite3FtsUnicodeIsdiacritic(iCode)
159562  );
159563
159564  /* Set the output variables and return. */
159565  pCsr->iOff = (int)(z - pCsr->aInput);
159566  *paToken = pCsr->zToken;
159567  *pnToken = (int)(zOut - pCsr->zToken);
159568  *piStart = (int)(zStart - pCsr->aInput);
159569  *piEnd = (int)(zEnd - pCsr->aInput);
159570  *piPos = pCsr->iToken++;
159571  return SQLITE_OK;
159572}
159573
159574/*
159575** Set *ppModule to a pointer to the sqlite3_tokenizer_module
159576** structure for the unicode tokenizer.
159577*/
159578SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
159579  static const sqlite3_tokenizer_module module = {
159580    0,
159581    unicodeCreate,
159582    unicodeDestroy,
159583    unicodeOpen,
159584    unicodeClose,
159585    unicodeNext,
159586    0,
159587  };
159588  *ppModule = &module;
159589}
159590
159591#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
159592#endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
159593
159594/************** End of fts3_unicode.c ****************************************/
159595/************** Begin file fts3_unicode2.c ***********************************/
159596/*
159597** 2012 May 25
159598**
159599** The author disclaims copyright to this source code.  In place of
159600** a legal notice, here is a blessing:
159601**
159602**    May you do good and not evil.
159603**    May you find forgiveness for yourself and forgive others.
159604**    May you share freely, never taking more than you give.
159605**
159606******************************************************************************
159607*/
159608
159609/*
159610** DO NOT EDIT THIS MACHINE GENERATED FILE.
159611*/
159612
159613#ifndef SQLITE_DISABLE_FTS3_UNICODE
159614#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
159615
159616/* #include <assert.h> */
159617
159618/*
159619** Return true if the argument corresponds to a unicode codepoint
159620** classified as either a letter or a number. Otherwise false.
159621**
159622** The results are undefined if the value passed to this function
159623** is less than zero.
159624*/
159625SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
159626  /* Each unsigned integer in the following array corresponds to a contiguous
159627  ** range of unicode codepoints that are not either letters or numbers (i.e.
159628  ** codepoints for which this function should return 0).
159629  **
159630  ** The most significant 22 bits in each 32-bit value contain the first
159631  ** codepoint in the range. The least significant 10 bits are used to store
159632  ** the size of the range (always at least 1). In other words, the value
159633  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
159634  ** C. It is not possible to represent a range larger than 1023 codepoints
159635  ** using this format.
159636  */
159637  static const unsigned int aEntry[] = {
159638    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
159639    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
159640    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
159641    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
159642    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
159643    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
159644    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
159645    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
159646    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
159647    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
159648    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
159649    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
159650    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
159651    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
159652    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
159653    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
159654    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
159655    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
159656    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
159657    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
159658    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
159659    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
159660    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
159661    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
159662    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
159663    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
159664    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
159665    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
159666    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
159667    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
159668    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
159669    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
159670    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
159671    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
159672    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
159673    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
159674    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
159675    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
159676    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
159677    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
159678    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
159679    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
159680    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
159681    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
159682    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
159683    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
159684    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
159685    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
159686    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
159687    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
159688    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
159689    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
159690    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
159691    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
159692    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
159693    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
159694    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
159695    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
159696    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
159697    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
159698    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
159699    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
159700    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
159701    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
159702    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
159703    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
159704    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
159705    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
159706    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
159707    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
159708    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
159709    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
159710    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
159711    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
159712    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
159713    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
159714    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
159715    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
159716    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
159717    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
159718    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
159719    0x380400F0,
159720  };
159721  static const unsigned int aAscii[4] = {
159722    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
159723  };
159724
159725  if( c<128 ){
159726    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
159727  }else if( c<(1<<22) ){
159728    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
159729    int iRes = 0;
159730    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
159731    int iLo = 0;
159732    while( iHi>=iLo ){
159733      int iTest = (iHi + iLo) / 2;
159734      if( key >= aEntry[iTest] ){
159735        iRes = iTest;
159736        iLo = iTest+1;
159737      }else{
159738        iHi = iTest-1;
159739      }
159740    }
159741    assert( aEntry[0]<key );
159742    assert( key>=aEntry[iRes] );
159743    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
159744  }
159745  return 1;
159746}
159747
159748
159749/*
159750** If the argument is a codepoint corresponding to a lowercase letter
159751** in the ASCII range with a diacritic added, return the codepoint
159752** of the ASCII letter only. For example, if passed 235 - "LATIN
159753** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
159754** E"). The resuls of passing a codepoint that corresponds to an
159755** uppercase letter are undefined.
159756*/
159757static int remove_diacritic(int c){
159758  unsigned short aDia[] = {
159759        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
159760     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
159761     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
159762     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
159763     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
159764     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
159765     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
159766     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
159767    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
159768    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
159769    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
159770    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
159771    62924, 63050, 63082, 63274, 63390,
159772  };
159773  char aChar[] = {
159774    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
159775    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
159776    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
159777    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
159778    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
159779    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
159780    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
159781    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
159782    'e',  'i',  'o',  'u',  'y',
159783  };
159784
159785  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
159786  int iRes = 0;
159787  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
159788  int iLo = 0;
159789  while( iHi>=iLo ){
159790    int iTest = (iHi + iLo) / 2;
159791    if( key >= aDia[iTest] ){
159792      iRes = iTest;
159793      iLo = iTest+1;
159794    }else{
159795      iHi = iTest-1;
159796    }
159797  }
159798  assert( key>=aDia[iRes] );
159799  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
159800}
159801
159802
159803/*
159804** Return true if the argument interpreted as a unicode codepoint
159805** is a diacritical modifier character.
159806*/
159807SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
159808  unsigned int mask0 = 0x08029FDF;
159809  unsigned int mask1 = 0x000361F8;
159810  if( c<768 || c>817 ) return 0;
159811  return (c < 768+32) ?
159812      (mask0 & (1 << (c-768))) :
159813      (mask1 & (1 << (c-768-32)));
159814}
159815
159816
159817/*
159818** Interpret the argument as a unicode codepoint. If the codepoint
159819** is an upper case character that has a lower case equivalent,
159820** return the codepoint corresponding to the lower case version.
159821** Otherwise, return a copy of the argument.
159822**
159823** The results are undefined if the value passed to this function
159824** is less than zero.
159825*/
159826SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
159827  /* Each entry in the following array defines a rule for folding a range
159828  ** of codepoints to lower case. The rule applies to a range of nRange
159829  ** codepoints starting at codepoint iCode.
159830  **
159831  ** If the least significant bit in flags is clear, then the rule applies
159832  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
159833  ** need to be folded). Or, if it is set, then the rule only applies to
159834  ** every second codepoint in the range, starting with codepoint C.
159835  **
159836  ** The 7 most significant bits in flags are an index into the aiOff[]
159837  ** array. If a specific codepoint C does require folding, then its lower
159838  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
159839  **
159840  ** The contents of this array are generated by parsing the CaseFolding.txt
159841  ** file distributed as part of the "Unicode Character Database". See
159842  ** http://www.unicode.org for details.
159843  */
159844  static const struct TableEntry {
159845    unsigned short iCode;
159846    unsigned char flags;
159847    unsigned char nRange;
159848  } aEntry[] = {
159849    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
159850    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
159851    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
159852    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
159853    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
159854    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
159855    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
159856    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
159857    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
159858    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
159859    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
159860    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
159861    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
159862    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
159863    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
159864    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
159865    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
159866    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
159867    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
159868    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
159869    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
159870    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
159871    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
159872    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
159873    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
159874    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
159875    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
159876    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
159877    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
159878    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
159879    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
159880    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
159881    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
159882    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
159883    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
159884    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
159885    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
159886    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
159887    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
159888    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
159889    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
159890    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
159891    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
159892    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
159893    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
159894    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
159895    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
159896    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
159897    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
159898    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
159899    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
159900    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
159901    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
159902    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
159903    {65313, 14, 26},
159904  };
159905  static const unsigned short aiOff[] = {
159906   1,     2,     8,     15,    16,    26,    28,    32,
159907   37,    38,    40,    48,    63,    64,    69,    71,
159908   79,    80,    116,   202,   203,   205,   206,   207,
159909   209,   210,   211,   213,   214,   217,   218,   219,
159910   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
159911   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
159912   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
159913   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
159914   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
159915   65514, 65521, 65527, 65528, 65529,
159916  };
159917
159918  int ret = c;
159919
159920  assert( c>=0 );
159921  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
159922
159923  if( c<128 ){
159924    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
159925  }else if( c<65536 ){
159926    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
159927    int iLo = 0;
159928    int iRes = -1;
159929
159930    while( iHi>=iLo ){
159931      int iTest = (iHi + iLo) / 2;
159932      int cmp = (c - aEntry[iTest].iCode);
159933      if( cmp>=0 ){
159934        iRes = iTest;
159935        iLo = iTest+1;
159936      }else{
159937        iHi = iTest-1;
159938      }
159939    }
159940    assert( iRes<0 || c>=aEntry[iRes].iCode );
159941
159942    if( iRes>=0 ){
159943      const struct TableEntry *p = &aEntry[iRes];
159944      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
159945        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
159946        assert( ret>0 );
159947      }
159948    }
159949
159950    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
159951  }
159952
159953  else if( c>=66560 && c<66600 ){
159954    ret = c + 40;
159955  }
159956
159957  return ret;
159958}
159959#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
159960#endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
159961
159962/************** End of fts3_unicode2.c ***************************************/
159963/************** Begin file rtree.c *******************************************/
159964/*
159965** 2001 September 15
159966**
159967** The author disclaims copyright to this source code.  In place of
159968** a legal notice, here is a blessing:
159969**
159970**    May you do good and not evil.
159971**    May you find forgiveness for yourself and forgive others.
159972**    May you share freely, never taking more than you give.
159973**
159974*************************************************************************
159975** This file contains code for implementations of the r-tree and r*-tree
159976** algorithms packaged as an SQLite virtual table module.
159977*/
159978
159979/*
159980** Database Format of R-Tree Tables
159981** --------------------------------
159982**
159983** The data structure for a single virtual r-tree table is stored in three
159984** native SQLite tables declared as follows. In each case, the '%' character
159985** in the table name is replaced with the user-supplied name of the r-tree
159986** table.
159987**
159988**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
159989**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
159990**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
159991**
159992** The data for each node of the r-tree structure is stored in the %_node
159993** table. For each node that is not the root node of the r-tree, there is
159994** an entry in the %_parent table associating the node with its parent.
159995** And for each row of data in the table, there is an entry in the %_rowid
159996** table that maps from the entries rowid to the id of the node that it
159997** is stored on.
159998**
159999** The root node of an r-tree always exists, even if the r-tree table is
160000** empty. The nodeno of the root node is always 1. All other nodes in the
160001** table must be the same size as the root node. The content of each node
160002** is formatted as follows:
160003**
160004**   1. If the node is the root node (node 1), then the first 2 bytes
160005**      of the node contain the tree depth as a big-endian integer.
160006**      For non-root nodes, the first 2 bytes are left unused.
160007**
160008**   2. The next 2 bytes contain the number of entries currently
160009**      stored in the node.
160010**
160011**   3. The remainder of the node contains the node entries. Each entry
160012**      consists of a single 8-byte integer followed by an even number
160013**      of 4-byte coordinates. For leaf nodes the integer is the rowid
160014**      of a record. For internal nodes it is the node number of a
160015**      child page.
160016*/
160017
160018#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
160019
160020#ifndef SQLITE_CORE
160021/*   #include "sqlite3ext.h" */
160022  SQLITE_EXTENSION_INIT1
160023#else
160024/*   #include "sqlite3.h" */
160025#endif
160026
160027/* #include <string.h> */
160028/* #include <assert.h> */
160029/* #include <stdio.h> */
160030
160031#ifndef SQLITE_AMALGAMATION
160032#include "sqlite3rtree.h"
160033typedef sqlite3_int64 i64;
160034typedef unsigned char u8;
160035typedef unsigned short u16;
160036typedef unsigned int u32;
160037#endif
160038
160039/*  The following macro is used to suppress compiler warnings.
160040*/
160041#ifndef UNUSED_PARAMETER
160042# define UNUSED_PARAMETER(x) (void)(x)
160043#endif
160044
160045typedef struct Rtree Rtree;
160046typedef struct RtreeCursor RtreeCursor;
160047typedef struct RtreeNode RtreeNode;
160048typedef struct RtreeCell RtreeCell;
160049typedef struct RtreeConstraint RtreeConstraint;
160050typedef struct RtreeMatchArg RtreeMatchArg;
160051typedef struct RtreeGeomCallback RtreeGeomCallback;
160052typedef union RtreeCoord RtreeCoord;
160053typedef struct RtreeSearchPoint RtreeSearchPoint;
160054
160055/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
160056#define RTREE_MAX_DIMENSIONS 5
160057
160058/* Size of hash table Rtree.aHash. This hash table is not expected to
160059** ever contain very many entries, so a fixed number of buckets is
160060** used.
160061*/
160062#define HASHSIZE 97
160063
160064/* The xBestIndex method of this virtual table requires an estimate of
160065** the number of rows in the virtual table to calculate the costs of
160066** various strategies. If possible, this estimate is loaded from the
160067** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
160068** Otherwise, if no sqlite_stat1 entry is available, use
160069** RTREE_DEFAULT_ROWEST.
160070*/
160071#define RTREE_DEFAULT_ROWEST 1048576
160072#define RTREE_MIN_ROWEST         100
160073
160074/*
160075** An rtree virtual-table object.
160076*/
160077struct Rtree {
160078  sqlite3_vtab base;          /* Base class.  Must be first */
160079  sqlite3 *db;                /* Host database connection */
160080  int iNodeSize;              /* Size in bytes of each node in the node table */
160081  u8 nDim;                    /* Number of dimensions */
160082  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
160083  u8 nBytesPerCell;           /* Bytes consumed per cell */
160084  int iDepth;                 /* Current depth of the r-tree structure */
160085  char *zDb;                  /* Name of database containing r-tree table */
160086  char *zName;                /* Name of r-tree table */
160087  int nBusy;                  /* Current number of users of this structure */
160088  i64 nRowEst;                /* Estimated number of rows in this table */
160089
160090  /* List of nodes removed during a CondenseTree operation. List is
160091  ** linked together via the pointer normally used for hash chains -
160092  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
160093  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
160094  */
160095  RtreeNode *pDeleted;
160096  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
160097
160098  /* Statements to read/write/delete a record from xxx_node */
160099  sqlite3_stmt *pReadNode;
160100  sqlite3_stmt *pWriteNode;
160101  sqlite3_stmt *pDeleteNode;
160102
160103  /* Statements to read/write/delete a record from xxx_rowid */
160104  sqlite3_stmt *pReadRowid;
160105  sqlite3_stmt *pWriteRowid;
160106  sqlite3_stmt *pDeleteRowid;
160107
160108  /* Statements to read/write/delete a record from xxx_parent */
160109  sqlite3_stmt *pReadParent;
160110  sqlite3_stmt *pWriteParent;
160111  sqlite3_stmt *pDeleteParent;
160112
160113  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
160114};
160115
160116/* Possible values for Rtree.eCoordType: */
160117#define RTREE_COORD_REAL32 0
160118#define RTREE_COORD_INT32  1
160119
160120/*
160121** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
160122** only deal with integer coordinates.  No floating point operations
160123** will be done.
160124*/
160125#ifdef SQLITE_RTREE_INT_ONLY
160126  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
160127  typedef int RtreeValue;                  /* Low accuracy coordinate */
160128# define RTREE_ZERO 0
160129#else
160130  typedef double RtreeDValue;              /* High accuracy coordinate */
160131  typedef float RtreeValue;                /* Low accuracy coordinate */
160132# define RTREE_ZERO 0.0
160133#endif
160134
160135/*
160136** When doing a search of an r-tree, instances of the following structure
160137** record intermediate results from the tree walk.
160138**
160139** The id is always a node-id.  For iLevel>=1 the id is the node-id of
160140** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
160141** the id is of the parent node and the cell that RtreeSearchPoint
160142** represents is the iCell-th entry in the parent node.
160143*/
160144struct RtreeSearchPoint {
160145  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
160146  sqlite3_int64 id;      /* Node ID */
160147  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
160148  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
160149  u8 iCell;              /* Cell index within the node */
160150};
160151
160152/*
160153** The minimum number of cells allowed for a node is a third of the
160154** maximum. In Gutman's notation:
160155**
160156**     m = M/3
160157**
160158** If an R*-tree "Reinsert" operation is required, the same number of
160159** cells are removed from the overfull node and reinserted into the tree.
160160*/
160161#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
160162#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
160163#define RTREE_MAXCELLS 51
160164
160165/*
160166** The smallest possible node-size is (512-64)==448 bytes. And the largest
160167** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
160168** Therefore all non-root nodes must contain at least 3 entries. Since
160169** 2^40 is greater than 2^64, an r-tree structure always has a depth of
160170** 40 or less.
160171*/
160172#define RTREE_MAX_DEPTH 40
160173
160174
160175/*
160176** Number of entries in the cursor RtreeNode cache.  The first entry is
160177** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
160178** entries cache the RtreeNode for the first elements of the priority queue.
160179*/
160180#define RTREE_CACHE_SZ  5
160181
160182/*
160183** An rtree cursor object.
160184*/
160185struct RtreeCursor {
160186  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
160187  u8 atEOF;                         /* True if at end of search */
160188  u8 bPoint;                        /* True if sPoint is valid */
160189  int iStrategy;                    /* Copy of idxNum search parameter */
160190  int nConstraint;                  /* Number of entries in aConstraint */
160191  RtreeConstraint *aConstraint;     /* Search constraints. */
160192  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
160193  int nPoint;                       /* Number of slots used in aPoint[] */
160194  int mxLevel;                      /* iLevel value for root of the tree */
160195  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
160196  RtreeSearchPoint sPoint;          /* Cached next search point */
160197  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
160198  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
160199};
160200
160201/* Return the Rtree of a RtreeCursor */
160202#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
160203
160204/*
160205** A coordinate can be either a floating point number or a integer.  All
160206** coordinates within a single R-Tree are always of the same time.
160207*/
160208union RtreeCoord {
160209  RtreeValue f;      /* Floating point value */
160210  int i;             /* Integer value */
160211  u32 u;             /* Unsigned for byte-order conversions */
160212};
160213
160214/*
160215** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
160216** formatted as a RtreeDValue (double or int64). This macro assumes that local
160217** variable pRtree points to the Rtree structure associated with the
160218** RtreeCoord.
160219*/
160220#ifdef SQLITE_RTREE_INT_ONLY
160221# define DCOORD(coord) ((RtreeDValue)coord.i)
160222#else
160223# define DCOORD(coord) (                           \
160224    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
160225      ((double)coord.f) :                           \
160226      ((double)coord.i)                             \
160227  )
160228#endif
160229
160230/*
160231** A search constraint.
160232*/
160233struct RtreeConstraint {
160234  int iCoord;                     /* Index of constrained coordinate */
160235  int op;                         /* Constraining operation */
160236  union {
160237    RtreeDValue rValue;             /* Constraint value. */
160238    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
160239    int (*xQueryFunc)(sqlite3_rtree_query_info*);
160240  } u;
160241  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
160242};
160243
160244/* Possible values for RtreeConstraint.op */
160245#define RTREE_EQ    0x41  /* A */
160246#define RTREE_LE    0x42  /* B */
160247#define RTREE_LT    0x43  /* C */
160248#define RTREE_GE    0x44  /* D */
160249#define RTREE_GT    0x45  /* E */
160250#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
160251#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
160252
160253
160254/*
160255** An rtree structure node.
160256*/
160257struct RtreeNode {
160258  RtreeNode *pParent;         /* Parent node */
160259  i64 iNode;                  /* The node number */
160260  int nRef;                   /* Number of references to this node */
160261  int isDirty;                /* True if the node needs to be written to disk */
160262  u8 *zData;                  /* Content of the node, as should be on disk */
160263  RtreeNode *pNext;           /* Next node in this hash collision chain */
160264};
160265
160266/* Return the number of cells in a node  */
160267#define NCELL(pNode) readInt16(&(pNode)->zData[2])
160268
160269/*
160270** A single cell from a node, deserialized
160271*/
160272struct RtreeCell {
160273  i64 iRowid;                                 /* Node or entry ID */
160274  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
160275};
160276
160277
160278/*
160279** This object becomes the sqlite3_user_data() for the SQL functions
160280** that are created by sqlite3_rtree_geometry_callback() and
160281** sqlite3_rtree_query_callback() and which appear on the right of MATCH
160282** operators in order to constrain a search.
160283**
160284** xGeom and xQueryFunc are the callback functions.  Exactly one of
160285** xGeom and xQueryFunc fields is non-NULL, depending on whether the
160286** SQL function was created using sqlite3_rtree_geometry_callback() or
160287** sqlite3_rtree_query_callback().
160288**
160289** This object is deleted automatically by the destructor mechanism in
160290** sqlite3_create_function_v2().
160291*/
160292struct RtreeGeomCallback {
160293  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
160294  int (*xQueryFunc)(sqlite3_rtree_query_info*);
160295  void (*xDestructor)(void*);
160296  void *pContext;
160297};
160298
160299
160300/*
160301** Value for the first field of every RtreeMatchArg object. The MATCH
160302** operator tests that the first field of a blob operand matches this
160303** value to avoid operating on invalid blobs (which could cause a segfault).
160304*/
160305#define RTREE_GEOMETRY_MAGIC 0x891245AB
160306
160307/*
160308** An instance of this structure (in the form of a BLOB) is returned by
160309** the SQL functions that sqlite3_rtree_geometry_callback() and
160310** sqlite3_rtree_query_callback() create, and is read as the right-hand
160311** operand to the MATCH operator of an R-Tree.
160312*/
160313struct RtreeMatchArg {
160314  u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
160315  RtreeGeomCallback cb;       /* Info about the callback functions */
160316  int nParam;                 /* Number of parameters to the SQL function */
160317  sqlite3_value **apSqlParam; /* Original SQL parameter values */
160318  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
160319};
160320
160321#ifndef MAX
160322# define MAX(x,y) ((x) < (y) ? (y) : (x))
160323#endif
160324#ifndef MIN
160325# define MIN(x,y) ((x) > (y) ? (y) : (x))
160326#endif
160327
160328/*
160329** Functions to deserialize a 16 bit integer, 32 bit real number and
160330** 64 bit integer. The deserialized value is returned.
160331*/
160332static int readInt16(u8 *p){
160333  return (p[0]<<8) + p[1];
160334}
160335static void readCoord(u8 *p, RtreeCoord *pCoord){
160336  pCoord->u = (
160337    (((u32)p[0]) << 24) +
160338    (((u32)p[1]) << 16) +
160339    (((u32)p[2]) <<  8) +
160340    (((u32)p[3]) <<  0)
160341  );
160342}
160343static i64 readInt64(u8 *p){
160344  return (
160345    (((i64)p[0]) << 56) +
160346    (((i64)p[1]) << 48) +
160347    (((i64)p[2]) << 40) +
160348    (((i64)p[3]) << 32) +
160349    (((i64)p[4]) << 24) +
160350    (((i64)p[5]) << 16) +
160351    (((i64)p[6]) <<  8) +
160352    (((i64)p[7]) <<  0)
160353  );
160354}
160355
160356/*
160357** Functions to serialize a 16 bit integer, 32 bit real number and
160358** 64 bit integer. The value returned is the number of bytes written
160359** to the argument buffer (always 2, 4 and 8 respectively).
160360*/
160361static int writeInt16(u8 *p, int i){
160362  p[0] = (i>> 8)&0xFF;
160363  p[1] = (i>> 0)&0xFF;
160364  return 2;
160365}
160366static int writeCoord(u8 *p, RtreeCoord *pCoord){
160367  u32 i;
160368  assert( sizeof(RtreeCoord)==4 );
160369  assert( sizeof(u32)==4 );
160370  i = pCoord->u;
160371  p[0] = (i>>24)&0xFF;
160372  p[1] = (i>>16)&0xFF;
160373  p[2] = (i>> 8)&0xFF;
160374  p[3] = (i>> 0)&0xFF;
160375  return 4;
160376}
160377static int writeInt64(u8 *p, i64 i){
160378  p[0] = (i>>56)&0xFF;
160379  p[1] = (i>>48)&0xFF;
160380  p[2] = (i>>40)&0xFF;
160381  p[3] = (i>>32)&0xFF;
160382  p[4] = (i>>24)&0xFF;
160383  p[5] = (i>>16)&0xFF;
160384  p[6] = (i>> 8)&0xFF;
160385  p[7] = (i>> 0)&0xFF;
160386  return 8;
160387}
160388
160389/*
160390** Increment the reference count of node p.
160391*/
160392static void nodeReference(RtreeNode *p){
160393  if( p ){
160394    p->nRef++;
160395  }
160396}
160397
160398/*
160399** Clear the content of node p (set all bytes to 0x00).
160400*/
160401static void nodeZero(Rtree *pRtree, RtreeNode *p){
160402  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
160403  p->isDirty = 1;
160404}
160405
160406/*
160407** Given a node number iNode, return the corresponding key to use
160408** in the Rtree.aHash table.
160409*/
160410static int nodeHash(i64 iNode){
160411  return iNode % HASHSIZE;
160412}
160413
160414/*
160415** Search the node hash table for node iNode. If found, return a pointer
160416** to it. Otherwise, return 0.
160417*/
160418static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
160419  RtreeNode *p;
160420  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
160421  return p;
160422}
160423
160424/*
160425** Add node pNode to the node hash table.
160426*/
160427static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
160428  int iHash;
160429  assert( pNode->pNext==0 );
160430  iHash = nodeHash(pNode->iNode);
160431  pNode->pNext = pRtree->aHash[iHash];
160432  pRtree->aHash[iHash] = pNode;
160433}
160434
160435/*
160436** Remove node pNode from the node hash table.
160437*/
160438static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
160439  RtreeNode **pp;
160440  if( pNode->iNode!=0 ){
160441    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
160442    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
160443    *pp = pNode->pNext;
160444    pNode->pNext = 0;
160445  }
160446}
160447
160448/*
160449** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
160450** indicating that node has not yet been assigned a node number. It is
160451** assigned a node number when nodeWrite() is called to write the
160452** node contents out to the database.
160453*/
160454static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
160455  RtreeNode *pNode;
160456  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
160457  if( pNode ){
160458    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
160459    pNode->zData = (u8 *)&pNode[1];
160460    pNode->nRef = 1;
160461    pNode->pParent = pParent;
160462    pNode->isDirty = 1;
160463    nodeReference(pParent);
160464  }
160465  return pNode;
160466}
160467
160468/*
160469** Obtain a reference to an r-tree node.
160470*/
160471static int nodeAcquire(
160472  Rtree *pRtree,             /* R-tree structure */
160473  i64 iNode,                 /* Node number to load */
160474  RtreeNode *pParent,        /* Either the parent node or NULL */
160475  RtreeNode **ppNode         /* OUT: Acquired node */
160476){
160477  int rc;
160478  int rc2 = SQLITE_OK;
160479  RtreeNode *pNode;
160480
160481  /* Check if the requested node is already in the hash table. If so,
160482  ** increase its reference count and return it.
160483  */
160484  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
160485    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
160486    if( pParent && !pNode->pParent ){
160487      nodeReference(pParent);
160488      pNode->pParent = pParent;
160489    }
160490    pNode->nRef++;
160491    *ppNode = pNode;
160492    return SQLITE_OK;
160493  }
160494
160495  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
160496  rc = sqlite3_step(pRtree->pReadNode);
160497  if( rc==SQLITE_ROW ){
160498    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
160499    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
160500      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
160501      if( !pNode ){
160502        rc2 = SQLITE_NOMEM;
160503      }else{
160504        pNode->pParent = pParent;
160505        pNode->zData = (u8 *)&pNode[1];
160506        pNode->nRef = 1;
160507        pNode->iNode = iNode;
160508        pNode->isDirty = 0;
160509        pNode->pNext = 0;
160510        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
160511        nodeReference(pParent);
160512      }
160513    }
160514  }
160515  rc = sqlite3_reset(pRtree->pReadNode);
160516  if( rc==SQLITE_OK ) rc = rc2;
160517
160518  /* If the root node was just loaded, set pRtree->iDepth to the height
160519  ** of the r-tree structure. A height of zero means all data is stored on
160520  ** the root node. A height of one means the children of the root node
160521  ** are the leaves, and so on. If the depth as specified on the root node
160522  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
160523  */
160524  if( pNode && iNode==1 ){
160525    pRtree->iDepth = readInt16(pNode->zData);
160526    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
160527      rc = SQLITE_CORRUPT_VTAB;
160528    }
160529  }
160530
160531  /* If no error has occurred so far, check if the "number of entries"
160532  ** field on the node is too large. If so, set the return code to
160533  ** SQLITE_CORRUPT_VTAB.
160534  */
160535  if( pNode && rc==SQLITE_OK ){
160536    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
160537      rc = SQLITE_CORRUPT_VTAB;
160538    }
160539  }
160540
160541  if( rc==SQLITE_OK ){
160542    if( pNode!=0 ){
160543      nodeHashInsert(pRtree, pNode);
160544    }else{
160545      rc = SQLITE_CORRUPT_VTAB;
160546    }
160547    *ppNode = pNode;
160548  }else{
160549    sqlite3_free(pNode);
160550    *ppNode = 0;
160551  }
160552
160553  return rc;
160554}
160555
160556/*
160557** Overwrite cell iCell of node pNode with the contents of pCell.
160558*/
160559static void nodeOverwriteCell(
160560  Rtree *pRtree,             /* The overall R-Tree */
160561  RtreeNode *pNode,          /* The node into which the cell is to be written */
160562  RtreeCell *pCell,          /* The cell to write */
160563  int iCell                  /* Index into pNode into which pCell is written */
160564){
160565  int ii;
160566  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
160567  p += writeInt64(p, pCell->iRowid);
160568  for(ii=0; ii<(pRtree->nDim*2); ii++){
160569    p += writeCoord(p, &pCell->aCoord[ii]);
160570  }
160571  pNode->isDirty = 1;
160572}
160573
160574/*
160575** Remove the cell with index iCell from node pNode.
160576*/
160577static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
160578  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
160579  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
160580  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
160581  memmove(pDst, pSrc, nByte);
160582  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
160583  pNode->isDirty = 1;
160584}
160585
160586/*
160587** Insert the contents of cell pCell into node pNode. If the insert
160588** is successful, return SQLITE_OK.
160589**
160590** If there is not enough free space in pNode, return SQLITE_FULL.
160591*/
160592static int nodeInsertCell(
160593  Rtree *pRtree,                /* The overall R-Tree */
160594  RtreeNode *pNode,             /* Write new cell into this node */
160595  RtreeCell *pCell              /* The cell to be inserted */
160596){
160597  int nCell;                    /* Current number of cells in pNode */
160598  int nMaxCell;                 /* Maximum number of cells for pNode */
160599
160600  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
160601  nCell = NCELL(pNode);
160602
160603  assert( nCell<=nMaxCell );
160604  if( nCell<nMaxCell ){
160605    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
160606    writeInt16(&pNode->zData[2], nCell+1);
160607    pNode->isDirty = 1;
160608  }
160609
160610  return (nCell==nMaxCell);
160611}
160612
160613/*
160614** If the node is dirty, write it out to the database.
160615*/
160616static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
160617  int rc = SQLITE_OK;
160618  if( pNode->isDirty ){
160619    sqlite3_stmt *p = pRtree->pWriteNode;
160620    if( pNode->iNode ){
160621      sqlite3_bind_int64(p, 1, pNode->iNode);
160622    }else{
160623      sqlite3_bind_null(p, 1);
160624    }
160625    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
160626    sqlite3_step(p);
160627    pNode->isDirty = 0;
160628    rc = sqlite3_reset(p);
160629    if( pNode->iNode==0 && rc==SQLITE_OK ){
160630      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
160631      nodeHashInsert(pRtree, pNode);
160632    }
160633  }
160634  return rc;
160635}
160636
160637/*
160638** Release a reference to a node. If the node is dirty and the reference
160639** count drops to zero, the node data is written to the database.
160640*/
160641static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
160642  int rc = SQLITE_OK;
160643  if( pNode ){
160644    assert( pNode->nRef>0 );
160645    pNode->nRef--;
160646    if( pNode->nRef==0 ){
160647      if( pNode->iNode==1 ){
160648        pRtree->iDepth = -1;
160649      }
160650      if( pNode->pParent ){
160651        rc = nodeRelease(pRtree, pNode->pParent);
160652      }
160653      if( rc==SQLITE_OK ){
160654        rc = nodeWrite(pRtree, pNode);
160655      }
160656      nodeHashDelete(pRtree, pNode);
160657      sqlite3_free(pNode);
160658    }
160659  }
160660  return rc;
160661}
160662
160663/*
160664** Return the 64-bit integer value associated with cell iCell of
160665** node pNode. If pNode is a leaf node, this is a rowid. If it is
160666** an internal node, then the 64-bit integer is a child page number.
160667*/
160668static i64 nodeGetRowid(
160669  Rtree *pRtree,       /* The overall R-Tree */
160670  RtreeNode *pNode,    /* The node from which to extract the ID */
160671  int iCell            /* The cell index from which to extract the ID */
160672){
160673  assert( iCell<NCELL(pNode) );
160674  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
160675}
160676
160677/*
160678** Return coordinate iCoord from cell iCell in node pNode.
160679*/
160680static void nodeGetCoord(
160681  Rtree *pRtree,               /* The overall R-Tree */
160682  RtreeNode *pNode,            /* The node from which to extract a coordinate */
160683  int iCell,                   /* The index of the cell within the node */
160684  int iCoord,                  /* Which coordinate to extract */
160685  RtreeCoord *pCoord           /* OUT: Space to write result to */
160686){
160687  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
160688}
160689
160690/*
160691** Deserialize cell iCell of node pNode. Populate the structure pointed
160692** to by pCell with the results.
160693*/
160694static void nodeGetCell(
160695  Rtree *pRtree,               /* The overall R-Tree */
160696  RtreeNode *pNode,            /* The node containing the cell to be read */
160697  int iCell,                   /* Index of the cell within the node */
160698  RtreeCell *pCell             /* OUT: Write the cell contents here */
160699){
160700  u8 *pData;
160701  RtreeCoord *pCoord;
160702  int ii;
160703  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
160704  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
160705  pCoord = pCell->aCoord;
160706  for(ii=0; ii<pRtree->nDim*2; ii++){
160707    readCoord(&pData[ii*4], &pCoord[ii]);
160708  }
160709}
160710
160711
160712/* Forward declaration for the function that does the work of
160713** the virtual table module xCreate() and xConnect() methods.
160714*/
160715static int rtreeInit(
160716  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
160717);
160718
160719/*
160720** Rtree virtual table module xCreate method.
160721*/
160722static int rtreeCreate(
160723  sqlite3 *db,
160724  void *pAux,
160725  int argc, const char *const*argv,
160726  sqlite3_vtab **ppVtab,
160727  char **pzErr
160728){
160729  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
160730}
160731
160732/*
160733** Rtree virtual table module xConnect method.
160734*/
160735static int rtreeConnect(
160736  sqlite3 *db,
160737  void *pAux,
160738  int argc, const char *const*argv,
160739  sqlite3_vtab **ppVtab,
160740  char **pzErr
160741){
160742  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
160743}
160744
160745/*
160746** Increment the r-tree reference count.
160747*/
160748static void rtreeReference(Rtree *pRtree){
160749  pRtree->nBusy++;
160750}
160751
160752/*
160753** Decrement the r-tree reference count. When the reference count reaches
160754** zero the structure is deleted.
160755*/
160756static void rtreeRelease(Rtree *pRtree){
160757  pRtree->nBusy--;
160758  if( pRtree->nBusy==0 ){
160759    sqlite3_finalize(pRtree->pReadNode);
160760    sqlite3_finalize(pRtree->pWriteNode);
160761    sqlite3_finalize(pRtree->pDeleteNode);
160762    sqlite3_finalize(pRtree->pReadRowid);
160763    sqlite3_finalize(pRtree->pWriteRowid);
160764    sqlite3_finalize(pRtree->pDeleteRowid);
160765    sqlite3_finalize(pRtree->pReadParent);
160766    sqlite3_finalize(pRtree->pWriteParent);
160767    sqlite3_finalize(pRtree->pDeleteParent);
160768    sqlite3_free(pRtree);
160769  }
160770}
160771
160772/*
160773** Rtree virtual table module xDisconnect method.
160774*/
160775static int rtreeDisconnect(sqlite3_vtab *pVtab){
160776  rtreeRelease((Rtree *)pVtab);
160777  return SQLITE_OK;
160778}
160779
160780/*
160781** Rtree virtual table module xDestroy method.
160782*/
160783static int rtreeDestroy(sqlite3_vtab *pVtab){
160784  Rtree *pRtree = (Rtree *)pVtab;
160785  int rc;
160786  char *zCreate = sqlite3_mprintf(
160787    "DROP TABLE '%q'.'%q_node';"
160788    "DROP TABLE '%q'.'%q_rowid';"
160789    "DROP TABLE '%q'.'%q_parent';",
160790    pRtree->zDb, pRtree->zName,
160791    pRtree->zDb, pRtree->zName,
160792    pRtree->zDb, pRtree->zName
160793  );
160794  if( !zCreate ){
160795    rc = SQLITE_NOMEM;
160796  }else{
160797    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
160798    sqlite3_free(zCreate);
160799  }
160800  if( rc==SQLITE_OK ){
160801    rtreeRelease(pRtree);
160802  }
160803
160804  return rc;
160805}
160806
160807/*
160808** Rtree virtual table module xOpen method.
160809*/
160810static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
160811  int rc = SQLITE_NOMEM;
160812  RtreeCursor *pCsr;
160813
160814  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
160815  if( pCsr ){
160816    memset(pCsr, 0, sizeof(RtreeCursor));
160817    pCsr->base.pVtab = pVTab;
160818    rc = SQLITE_OK;
160819  }
160820  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
160821
160822  return rc;
160823}
160824
160825
160826/*
160827** Free the RtreeCursor.aConstraint[] array and its contents.
160828*/
160829static void freeCursorConstraints(RtreeCursor *pCsr){
160830  if( pCsr->aConstraint ){
160831    int i;                        /* Used to iterate through constraint array */
160832    for(i=0; i<pCsr->nConstraint; i++){
160833      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
160834      if( pInfo ){
160835        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
160836        sqlite3_free(pInfo);
160837      }
160838    }
160839    sqlite3_free(pCsr->aConstraint);
160840    pCsr->aConstraint = 0;
160841  }
160842}
160843
160844/*
160845** Rtree virtual table module xClose method.
160846*/
160847static int rtreeClose(sqlite3_vtab_cursor *cur){
160848  Rtree *pRtree = (Rtree *)(cur->pVtab);
160849  int ii;
160850  RtreeCursor *pCsr = (RtreeCursor *)cur;
160851  freeCursorConstraints(pCsr);
160852  sqlite3_free(pCsr->aPoint);
160853  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
160854  sqlite3_free(pCsr);
160855  return SQLITE_OK;
160856}
160857
160858/*
160859** Rtree virtual table module xEof method.
160860**
160861** Return non-zero if the cursor does not currently point to a valid
160862** record (i.e if the scan has finished), or zero otherwise.
160863*/
160864static int rtreeEof(sqlite3_vtab_cursor *cur){
160865  RtreeCursor *pCsr = (RtreeCursor *)cur;
160866  return pCsr->atEOF;
160867}
160868
160869/*
160870** Convert raw bits from the on-disk RTree record into a coordinate value.
160871** The on-disk format is big-endian and needs to be converted for little-
160872** endian platforms.  The on-disk record stores integer coordinates if
160873** eInt is true and it stores 32-bit floating point records if eInt is
160874** false.  a[] is the four bytes of the on-disk record to be decoded.
160875** Store the results in "r".
160876**
160877** There are three versions of this macro, one each for little-endian and
160878** big-endian processors and a third generic implementation.  The endian-
160879** specific implementations are much faster and are preferred if the
160880** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
160881** macro is part of sqliteInt.h and hence the endian-specific
160882** implementation will only be used if this module is compiled as part
160883** of the amalgamation.
160884*/
160885#if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
160886#define RTREE_DECODE_COORD(eInt, a, r) {                        \
160887    RtreeCoord c;    /* Coordinate decoded */                   \
160888    memcpy(&c.u,a,4);                                           \
160889    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
160890          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
160891    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160892}
160893#elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
160894#define RTREE_DECODE_COORD(eInt, a, r) {                        \
160895    RtreeCoord c;    /* Coordinate decoded */                   \
160896    memcpy(&c.u,a,4);                                           \
160897    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160898}
160899#else
160900#define RTREE_DECODE_COORD(eInt, a, r) {                        \
160901    RtreeCoord c;    /* Coordinate decoded */                   \
160902    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
160903           +((u32)a[2]<<8) + a[3];                              \
160904    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160905}
160906#endif
160907
160908/*
160909** Check the RTree node or entry given by pCellData and p against the MATCH
160910** constraint pConstraint.
160911*/
160912static int rtreeCallbackConstraint(
160913  RtreeConstraint *pConstraint,  /* The constraint to test */
160914  int eInt,                      /* True if RTree holding integer coordinates */
160915  u8 *pCellData,                 /* Raw cell content */
160916  RtreeSearchPoint *pSearch,     /* Container of this cell */
160917  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
160918  int *peWithin                  /* OUT: visibility of the cell */
160919){
160920  int i;                                                /* Loop counter */
160921  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
160922  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
160923  int rc;                                             /* Callback return code */
160924  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
160925
160926  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
160927  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
160928
160929  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
160930    pInfo->iRowid = readInt64(pCellData);
160931  }
160932  pCellData += 8;
160933  for(i=0; i<nCoord; i++, pCellData += 4){
160934    RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
160935  }
160936  if( pConstraint->op==RTREE_MATCH ){
160937    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
160938                              nCoord, aCoord, &i);
160939    if( i==0 ) *peWithin = NOT_WITHIN;
160940    *prScore = RTREE_ZERO;
160941  }else{
160942    pInfo->aCoord = aCoord;
160943    pInfo->iLevel = pSearch->iLevel - 1;
160944    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
160945    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
160946    rc = pConstraint->u.xQueryFunc(pInfo);
160947    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
160948    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
160949      *prScore = pInfo->rScore;
160950    }
160951  }
160952  return rc;
160953}
160954
160955/*
160956** Check the internal RTree node given by pCellData against constraint p.
160957** If this constraint cannot be satisfied by any child within the node,
160958** set *peWithin to NOT_WITHIN.
160959*/
160960static void rtreeNonleafConstraint(
160961  RtreeConstraint *p,        /* The constraint to test */
160962  int eInt,                  /* True if RTree holds integer coordinates */
160963  u8 *pCellData,             /* Raw cell content as appears on disk */
160964  int *peWithin              /* Adjust downward, as appropriate */
160965){
160966  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
160967
160968  /* p->iCoord might point to either a lower or upper bound coordinate
160969  ** in a coordinate pair.  But make pCellData point to the lower bound.
160970  */
160971  pCellData += 8 + 4*(p->iCoord&0xfe);
160972
160973  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
160974      || p->op==RTREE_GT || p->op==RTREE_EQ );
160975  switch( p->op ){
160976    case RTREE_LE:
160977    case RTREE_LT:
160978    case RTREE_EQ:
160979      RTREE_DECODE_COORD(eInt, pCellData, val);
160980      /* val now holds the lower bound of the coordinate pair */
160981      if( p->u.rValue>=val ) return;
160982      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
160983      /* Fall through for the RTREE_EQ case */
160984
160985    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
160986      pCellData += 4;
160987      RTREE_DECODE_COORD(eInt, pCellData, val);
160988      /* val now holds the upper bound of the coordinate pair */
160989      if( p->u.rValue<=val ) return;
160990  }
160991  *peWithin = NOT_WITHIN;
160992}
160993
160994/*
160995** Check the leaf RTree cell given by pCellData against constraint p.
160996** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
160997** If the constraint is satisfied, leave *peWithin unchanged.
160998**
160999** The constraint is of the form:  xN op $val
161000**
161001** The op is given by p->op.  The xN is p->iCoord-th coordinate in
161002** pCellData.  $val is given by p->u.rValue.
161003*/
161004static void rtreeLeafConstraint(
161005  RtreeConstraint *p,        /* The constraint to test */
161006  int eInt,                  /* True if RTree holds integer coordinates */
161007  u8 *pCellData,             /* Raw cell content as appears on disk */
161008  int *peWithin              /* Adjust downward, as appropriate */
161009){
161010  RtreeDValue xN;      /* Coordinate value converted to a double */
161011
161012  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
161013      || p->op==RTREE_GT || p->op==RTREE_EQ );
161014  pCellData += 8 + p->iCoord*4;
161015  RTREE_DECODE_COORD(eInt, pCellData, xN);
161016  switch( p->op ){
161017    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
161018    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
161019    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
161020    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
161021    default:       if( xN == p->u.rValue ) return;  break;
161022  }
161023  *peWithin = NOT_WITHIN;
161024}
161025
161026/*
161027** One of the cells in node pNode is guaranteed to have a 64-bit
161028** integer value equal to iRowid. Return the index of this cell.
161029*/
161030static int nodeRowidIndex(
161031  Rtree *pRtree,
161032  RtreeNode *pNode,
161033  i64 iRowid,
161034  int *piIndex
161035){
161036  int ii;
161037  int nCell = NCELL(pNode);
161038  assert( nCell<200 );
161039  for(ii=0; ii<nCell; ii++){
161040    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
161041      *piIndex = ii;
161042      return SQLITE_OK;
161043    }
161044  }
161045  return SQLITE_CORRUPT_VTAB;
161046}
161047
161048/*
161049** Return the index of the cell containing a pointer to node pNode
161050** in its parent. If pNode is the root node, return -1.
161051*/
161052static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
161053  RtreeNode *pParent = pNode->pParent;
161054  if( pParent ){
161055    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
161056  }
161057  *piIndex = -1;
161058  return SQLITE_OK;
161059}
161060
161061/*
161062** Compare two search points.  Return negative, zero, or positive if the first
161063** is less than, equal to, or greater than the second.
161064**
161065** The rScore is the primary key.  Smaller rScore values come first.
161066** If the rScore is a tie, then use iLevel as the tie breaker with smaller
161067** iLevel values coming first.  In this way, if rScore is the same for all
161068** SearchPoints, then iLevel becomes the deciding factor and the result
161069** is a depth-first search, which is the desired default behavior.
161070*/
161071static int rtreeSearchPointCompare(
161072  const RtreeSearchPoint *pA,
161073  const RtreeSearchPoint *pB
161074){
161075  if( pA->rScore<pB->rScore ) return -1;
161076  if( pA->rScore>pB->rScore ) return +1;
161077  if( pA->iLevel<pB->iLevel ) return -1;
161078  if( pA->iLevel>pB->iLevel ) return +1;
161079  return 0;
161080}
161081
161082/*
161083** Interchange to search points in a cursor.
161084*/
161085static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
161086  RtreeSearchPoint t = p->aPoint[i];
161087  assert( i<j );
161088  p->aPoint[i] = p->aPoint[j];
161089  p->aPoint[j] = t;
161090  i++; j++;
161091  if( i<RTREE_CACHE_SZ ){
161092    if( j>=RTREE_CACHE_SZ ){
161093      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
161094      p->aNode[i] = 0;
161095    }else{
161096      RtreeNode *pTemp = p->aNode[i];
161097      p->aNode[i] = p->aNode[j];
161098      p->aNode[j] = pTemp;
161099    }
161100  }
161101}
161102
161103/*
161104** Return the search point with the lowest current score.
161105*/
161106static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
161107  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
161108}
161109
161110/*
161111** Get the RtreeNode for the search point with the lowest score.
161112*/
161113static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
161114  sqlite3_int64 id;
161115  int ii = 1 - pCur->bPoint;
161116  assert( ii==0 || ii==1 );
161117  assert( pCur->bPoint || pCur->nPoint );
161118  if( pCur->aNode[ii]==0 ){
161119    assert( pRC!=0 );
161120    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
161121    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
161122  }
161123  return pCur->aNode[ii];
161124}
161125
161126/*
161127** Push a new element onto the priority queue
161128*/
161129static RtreeSearchPoint *rtreeEnqueue(
161130  RtreeCursor *pCur,    /* The cursor */
161131  RtreeDValue rScore,   /* Score for the new search point */
161132  u8 iLevel             /* Level for the new search point */
161133){
161134  int i, j;
161135  RtreeSearchPoint *pNew;
161136  if( pCur->nPoint>=pCur->nPointAlloc ){
161137    int nNew = pCur->nPointAlloc*2 + 8;
161138    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
161139    if( pNew==0 ) return 0;
161140    pCur->aPoint = pNew;
161141    pCur->nPointAlloc = nNew;
161142  }
161143  i = pCur->nPoint++;
161144  pNew = pCur->aPoint + i;
161145  pNew->rScore = rScore;
161146  pNew->iLevel = iLevel;
161147  assert( iLevel<=RTREE_MAX_DEPTH );
161148  while( i>0 ){
161149    RtreeSearchPoint *pParent;
161150    j = (i-1)/2;
161151    pParent = pCur->aPoint + j;
161152    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
161153    rtreeSearchPointSwap(pCur, j, i);
161154    i = j;
161155    pNew = pParent;
161156  }
161157  return pNew;
161158}
161159
161160/*
161161** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
161162** NULL if malloc fails.
161163*/
161164static RtreeSearchPoint *rtreeSearchPointNew(
161165  RtreeCursor *pCur,    /* The cursor */
161166  RtreeDValue rScore,   /* Score for the new search point */
161167  u8 iLevel             /* Level for the new search point */
161168){
161169  RtreeSearchPoint *pNew, *pFirst;
161170  pFirst = rtreeSearchPointFirst(pCur);
161171  pCur->anQueue[iLevel]++;
161172  if( pFirst==0
161173   || pFirst->rScore>rScore
161174   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
161175  ){
161176    if( pCur->bPoint ){
161177      int ii;
161178      pNew = rtreeEnqueue(pCur, rScore, iLevel);
161179      if( pNew==0 ) return 0;
161180      ii = (int)(pNew - pCur->aPoint) + 1;
161181      if( ii<RTREE_CACHE_SZ ){
161182        assert( pCur->aNode[ii]==0 );
161183        pCur->aNode[ii] = pCur->aNode[0];
161184       }else{
161185        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
161186      }
161187      pCur->aNode[0] = 0;
161188      *pNew = pCur->sPoint;
161189    }
161190    pCur->sPoint.rScore = rScore;
161191    pCur->sPoint.iLevel = iLevel;
161192    pCur->bPoint = 1;
161193    return &pCur->sPoint;
161194  }else{
161195    return rtreeEnqueue(pCur, rScore, iLevel);
161196  }
161197}
161198
161199#if 0
161200/* Tracing routines for the RtreeSearchPoint queue */
161201static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
161202  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
161203  printf(" %d.%05lld.%02d %g %d",
161204    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
161205  );
161206  idx++;
161207  if( idx<RTREE_CACHE_SZ ){
161208    printf(" %p\n", pCur->aNode[idx]);
161209  }else{
161210    printf("\n");
161211  }
161212}
161213static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
161214  int ii;
161215  printf("=== %9s ", zPrefix);
161216  if( pCur->bPoint ){
161217    tracePoint(&pCur->sPoint, -1, pCur);
161218  }
161219  for(ii=0; ii<pCur->nPoint; ii++){
161220    if( ii>0 || pCur->bPoint ) printf("              ");
161221    tracePoint(&pCur->aPoint[ii], ii, pCur);
161222  }
161223}
161224# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
161225#else
161226# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
161227#endif
161228
161229/* Remove the search point with the lowest current score.
161230*/
161231static void rtreeSearchPointPop(RtreeCursor *p){
161232  int i, j, k, n;
161233  i = 1 - p->bPoint;
161234  assert( i==0 || i==1 );
161235  if( p->aNode[i] ){
161236    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
161237    p->aNode[i] = 0;
161238  }
161239  if( p->bPoint ){
161240    p->anQueue[p->sPoint.iLevel]--;
161241    p->bPoint = 0;
161242  }else if( p->nPoint ){
161243    p->anQueue[p->aPoint[0].iLevel]--;
161244    n = --p->nPoint;
161245    p->aPoint[0] = p->aPoint[n];
161246    if( n<RTREE_CACHE_SZ-1 ){
161247      p->aNode[1] = p->aNode[n+1];
161248      p->aNode[n+1] = 0;
161249    }
161250    i = 0;
161251    while( (j = i*2+1)<n ){
161252      k = j+1;
161253      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
161254        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
161255          rtreeSearchPointSwap(p, i, k);
161256          i = k;
161257        }else{
161258          break;
161259        }
161260      }else{
161261        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
161262          rtreeSearchPointSwap(p, i, j);
161263          i = j;
161264        }else{
161265          break;
161266        }
161267      }
161268    }
161269  }
161270}
161271
161272
161273/*
161274** Continue the search on cursor pCur until the front of the queue
161275** contains an entry suitable for returning as a result-set row,
161276** or until the RtreeSearchPoint queue is empty, indicating that the
161277** query has completed.
161278*/
161279static int rtreeStepToLeaf(RtreeCursor *pCur){
161280  RtreeSearchPoint *p;
161281  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
161282  RtreeNode *pNode;
161283  int eWithin;
161284  int rc = SQLITE_OK;
161285  int nCell;
161286  int nConstraint = pCur->nConstraint;
161287  int ii;
161288  int eInt;
161289  RtreeSearchPoint x;
161290
161291  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
161292  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
161293    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
161294    if( rc ) return rc;
161295    nCell = NCELL(pNode);
161296    assert( nCell<200 );
161297    while( p->iCell<nCell ){
161298      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
161299      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
161300      eWithin = FULLY_WITHIN;
161301      for(ii=0; ii<nConstraint; ii++){
161302        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
161303        if( pConstraint->op>=RTREE_MATCH ){
161304          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
161305                                       &rScore, &eWithin);
161306          if( rc ) return rc;
161307        }else if( p->iLevel==1 ){
161308          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
161309        }else{
161310          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
161311        }
161312        if( eWithin==NOT_WITHIN ) break;
161313      }
161314      p->iCell++;
161315      if( eWithin==NOT_WITHIN ) continue;
161316      x.iLevel = p->iLevel - 1;
161317      if( x.iLevel ){
161318        x.id = readInt64(pCellData);
161319        x.iCell = 0;
161320      }else{
161321        x.id = p->id;
161322        x.iCell = p->iCell - 1;
161323      }
161324      if( p->iCell>=nCell ){
161325        RTREE_QUEUE_TRACE(pCur, "POP-S:");
161326        rtreeSearchPointPop(pCur);
161327      }
161328      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
161329      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
161330      if( p==0 ) return SQLITE_NOMEM;
161331      p->eWithin = eWithin;
161332      p->id = x.id;
161333      p->iCell = x.iCell;
161334      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
161335      break;
161336    }
161337    if( p->iCell>=nCell ){
161338      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
161339      rtreeSearchPointPop(pCur);
161340    }
161341  }
161342  pCur->atEOF = p==0;
161343  return SQLITE_OK;
161344}
161345
161346/*
161347** Rtree virtual table module xNext method.
161348*/
161349static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
161350  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161351  int rc = SQLITE_OK;
161352
161353  /* Move to the next entry that matches the configured constraints. */
161354  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
161355  rtreeSearchPointPop(pCsr);
161356  rc = rtreeStepToLeaf(pCsr);
161357  return rc;
161358}
161359
161360/*
161361** Rtree virtual table module xRowid method.
161362*/
161363static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
161364  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161365  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
161366  int rc = SQLITE_OK;
161367  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
161368  if( rc==SQLITE_OK && p ){
161369    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
161370  }
161371  return rc;
161372}
161373
161374/*
161375** Rtree virtual table module xColumn method.
161376*/
161377static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
161378  Rtree *pRtree = (Rtree *)cur->pVtab;
161379  RtreeCursor *pCsr = (RtreeCursor *)cur;
161380  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
161381  RtreeCoord c;
161382  int rc = SQLITE_OK;
161383  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
161384
161385  if( rc ) return rc;
161386  if( p==0 ) return SQLITE_OK;
161387  if( i==0 ){
161388    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
161389  }else{
161390    if( rc ) return rc;
161391    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
161392#ifndef SQLITE_RTREE_INT_ONLY
161393    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161394      sqlite3_result_double(ctx, c.f);
161395    }else
161396#endif
161397    {
161398      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
161399      sqlite3_result_int(ctx, c.i);
161400    }
161401  }
161402  return SQLITE_OK;
161403}
161404
161405/*
161406** Use nodeAcquire() to obtain the leaf node containing the record with
161407** rowid iRowid. If successful, set *ppLeaf to point to the node and
161408** return SQLITE_OK. If there is no such record in the table, set
161409** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
161410** to zero and return an SQLite error code.
161411*/
161412static int findLeafNode(
161413  Rtree *pRtree,              /* RTree to search */
161414  i64 iRowid,                 /* The rowid searching for */
161415  RtreeNode **ppLeaf,         /* Write the node here */
161416  sqlite3_int64 *piNode       /* Write the node-id here */
161417){
161418  int rc;
161419  *ppLeaf = 0;
161420  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
161421  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
161422    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
161423    if( piNode ) *piNode = iNode;
161424    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
161425    sqlite3_reset(pRtree->pReadRowid);
161426  }else{
161427    rc = sqlite3_reset(pRtree->pReadRowid);
161428  }
161429  return rc;
161430}
161431
161432/*
161433** This function is called to configure the RtreeConstraint object passed
161434** as the second argument for a MATCH constraint. The value passed as the
161435** first argument to this function is the right-hand operand to the MATCH
161436** operator.
161437*/
161438static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
161439  RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
161440  sqlite3_rtree_query_info *pInfo;   /* Callback information */
161441  int nBlob;                         /* Size of the geometry function blob */
161442  int nExpected;                     /* Expected size of the BLOB */
161443
161444  /* Check that value is actually a blob. */
161445  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
161446
161447  /* Check that the blob is roughly the right size. */
161448  nBlob = sqlite3_value_bytes(pValue);
161449  if( nBlob<(int)sizeof(RtreeMatchArg) ){
161450    return SQLITE_ERROR;
161451  }
161452
161453  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
161454  if( !pInfo ) return SQLITE_NOMEM;
161455  memset(pInfo, 0, sizeof(*pInfo));
161456  pBlob = (RtreeMatchArg*)&pInfo[1];
161457
161458  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
161459  nExpected = (int)(sizeof(RtreeMatchArg) +
161460                    pBlob->nParam*sizeof(sqlite3_value*) +
161461                    (pBlob->nParam-1)*sizeof(RtreeDValue));
161462  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
161463    sqlite3_free(pInfo);
161464    return SQLITE_ERROR;
161465  }
161466  pInfo->pContext = pBlob->cb.pContext;
161467  pInfo->nParam = pBlob->nParam;
161468  pInfo->aParam = pBlob->aParam;
161469  pInfo->apSqlParam = pBlob->apSqlParam;
161470
161471  if( pBlob->cb.xGeom ){
161472    pCons->u.xGeom = pBlob->cb.xGeom;
161473  }else{
161474    pCons->op = RTREE_QUERY;
161475    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
161476  }
161477  pCons->pInfo = pInfo;
161478  return SQLITE_OK;
161479}
161480
161481/*
161482** Rtree virtual table module xFilter method.
161483*/
161484static int rtreeFilter(
161485  sqlite3_vtab_cursor *pVtabCursor,
161486  int idxNum, const char *idxStr,
161487  int argc, sqlite3_value **argv
161488){
161489  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
161490  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161491  RtreeNode *pRoot = 0;
161492  int ii;
161493  int rc = SQLITE_OK;
161494  int iCell = 0;
161495
161496  rtreeReference(pRtree);
161497
161498  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
161499  freeCursorConstraints(pCsr);
161500  sqlite3_free(pCsr->aPoint);
161501  memset(pCsr, 0, sizeof(RtreeCursor));
161502  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
161503
161504  pCsr->iStrategy = idxNum;
161505  if( idxNum==1 ){
161506    /* Special case - lookup by rowid. */
161507    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
161508    RtreeSearchPoint *p;     /* Search point for the the leaf */
161509    i64 iRowid = sqlite3_value_int64(argv[0]);
161510    i64 iNode = 0;
161511    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
161512    if( rc==SQLITE_OK && pLeaf!=0 ){
161513      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
161514      assert( p!=0 );  /* Always returns pCsr->sPoint */
161515      pCsr->aNode[0] = pLeaf;
161516      p->id = iNode;
161517      p->eWithin = PARTLY_WITHIN;
161518      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
161519      p->iCell = iCell;
161520      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
161521    }else{
161522      pCsr->atEOF = 1;
161523    }
161524  }else{
161525    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
161526    ** with the configured constraints.
161527    */
161528    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
161529    if( rc==SQLITE_OK && argc>0 ){
161530      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
161531      pCsr->nConstraint = argc;
161532      if( !pCsr->aConstraint ){
161533        rc = SQLITE_NOMEM;
161534      }else{
161535        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
161536        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
161537        assert( (idxStr==0 && argc==0)
161538                || (idxStr && (int)strlen(idxStr)==argc*2) );
161539        for(ii=0; ii<argc; ii++){
161540          RtreeConstraint *p = &pCsr->aConstraint[ii];
161541          p->op = idxStr[ii*2];
161542          p->iCoord = idxStr[ii*2+1]-'0';
161543          if( p->op>=RTREE_MATCH ){
161544            /* A MATCH operator. The right-hand-side must be a blob that
161545            ** can be cast into an RtreeMatchArg object. One created using
161546            ** an sqlite3_rtree_geometry_callback() SQL user function.
161547            */
161548            rc = deserializeGeometry(argv[ii], p);
161549            if( rc!=SQLITE_OK ){
161550              break;
161551            }
161552            p->pInfo->nCoord = pRtree->nDim*2;
161553            p->pInfo->anQueue = pCsr->anQueue;
161554            p->pInfo->mxLevel = pRtree->iDepth + 1;
161555          }else{
161556#ifdef SQLITE_RTREE_INT_ONLY
161557            p->u.rValue = sqlite3_value_int64(argv[ii]);
161558#else
161559            p->u.rValue = sqlite3_value_double(argv[ii]);
161560#endif
161561          }
161562        }
161563      }
161564    }
161565    if( rc==SQLITE_OK ){
161566      RtreeSearchPoint *pNew;
161567      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
161568      if( pNew==0 ) return SQLITE_NOMEM;
161569      pNew->id = 1;
161570      pNew->iCell = 0;
161571      pNew->eWithin = PARTLY_WITHIN;
161572      assert( pCsr->bPoint==1 );
161573      pCsr->aNode[0] = pRoot;
161574      pRoot = 0;
161575      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
161576      rc = rtreeStepToLeaf(pCsr);
161577    }
161578  }
161579
161580  nodeRelease(pRtree, pRoot);
161581  rtreeRelease(pRtree);
161582  return rc;
161583}
161584
161585/*
161586** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
161587** extension is currently being used by a version of SQLite too old to
161588** support estimatedRows. In that case this function is a no-op.
161589*/
161590static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
161591#if SQLITE_VERSION_NUMBER>=3008002
161592  if( sqlite3_libversion_number()>=3008002 ){
161593    pIdxInfo->estimatedRows = nRow;
161594  }
161595#endif
161596}
161597
161598/*
161599** Rtree virtual table module xBestIndex method. There are three
161600** table scan strategies to choose from (in order from most to
161601** least desirable):
161602**
161603**   idxNum     idxStr        Strategy
161604**   ------------------------------------------------
161605**     1        Unused        Direct lookup by rowid.
161606**     2        See below     R-tree query or full-table scan.
161607**   ------------------------------------------------
161608**
161609** If strategy 1 is used, then idxStr is not meaningful. If strategy
161610** 2 is used, idxStr is formatted to contain 2 bytes for each
161611** constraint used. The first two bytes of idxStr correspond to
161612** the constraint in sqlite3_index_info.aConstraintUsage[] with
161613** (argvIndex==1) etc.
161614**
161615** The first of each pair of bytes in idxStr identifies the constraint
161616** operator as follows:
161617**
161618**   Operator    Byte Value
161619**   ----------------------
161620**      =        0x41 ('A')
161621**     <=        0x42 ('B')
161622**      <        0x43 ('C')
161623**     >=        0x44 ('D')
161624**      >        0x45 ('E')
161625**   MATCH       0x46 ('F')
161626**   ----------------------
161627**
161628** The second of each pair of bytes identifies the coordinate column
161629** to which the constraint applies. The leftmost coordinate column
161630** is 'a', the second from the left 'b' etc.
161631*/
161632static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
161633  Rtree *pRtree = (Rtree*)tab;
161634  int rc = SQLITE_OK;
161635  int ii;
161636  int bMatch = 0;                 /* True if there exists a MATCH constraint */
161637  i64 nRow;                       /* Estimated rows returned by this scan */
161638
161639  int iIdx = 0;
161640  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
161641  memset(zIdxStr, 0, sizeof(zIdxStr));
161642
161643  /* Check if there exists a MATCH constraint - even an unusable one. If there
161644  ** is, do not consider the lookup-by-rowid plan as using such a plan would
161645  ** require the VDBE to evaluate the MATCH constraint, which is not currently
161646  ** possible. */
161647  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
161648    if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
161649      bMatch = 1;
161650    }
161651  }
161652
161653  assert( pIdxInfo->idxStr==0 );
161654  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
161655    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
161656
161657    if( bMatch==0 && p->usable
161658     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
161659    ){
161660      /* We have an equality constraint on the rowid. Use strategy 1. */
161661      int jj;
161662      for(jj=0; jj<ii; jj++){
161663        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
161664        pIdxInfo->aConstraintUsage[jj].omit = 0;
161665      }
161666      pIdxInfo->idxNum = 1;
161667      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
161668      pIdxInfo->aConstraintUsage[jj].omit = 1;
161669
161670      /* This strategy involves a two rowid lookups on an B-Tree structures
161671      ** and then a linear search of an R-Tree node. This should be
161672      ** considered almost as quick as a direct rowid lookup (for which
161673      ** sqlite uses an internal cost of 0.0). It is expected to return
161674      ** a single row.
161675      */
161676      pIdxInfo->estimatedCost = 30.0;
161677      setEstimatedRows(pIdxInfo, 1);
161678      return SQLITE_OK;
161679    }
161680
161681    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
161682      u8 op;
161683      switch( p->op ){
161684        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
161685        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
161686        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
161687        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
161688        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
161689        default:
161690          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
161691          op = RTREE_MATCH;
161692          break;
161693      }
161694      zIdxStr[iIdx++] = op;
161695      zIdxStr[iIdx++] = p->iColumn - 1 + '0';
161696      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
161697      pIdxInfo->aConstraintUsage[ii].omit = 1;
161698    }
161699  }
161700
161701  pIdxInfo->idxNum = 2;
161702  pIdxInfo->needToFreeIdxStr = 1;
161703  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
161704    return SQLITE_NOMEM;
161705  }
161706
161707  nRow = pRtree->nRowEst >> (iIdx/2);
161708  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
161709  setEstimatedRows(pIdxInfo, nRow);
161710
161711  return rc;
161712}
161713
161714/*
161715** Return the N-dimensional volumn of the cell stored in *p.
161716*/
161717static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
161718  RtreeDValue area = (RtreeDValue)1;
161719  int ii;
161720  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161721    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
161722  }
161723  return area;
161724}
161725
161726/*
161727** Return the margin length of cell p. The margin length is the sum
161728** of the objects size in each dimension.
161729*/
161730static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
161731  RtreeDValue margin = (RtreeDValue)0;
161732  int ii;
161733  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161734    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
161735  }
161736  return margin;
161737}
161738
161739/*
161740** Store the union of cells p1 and p2 in p1.
161741*/
161742static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
161743  int ii;
161744  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161745    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161746      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
161747      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
161748    }
161749  }else{
161750    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161751      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
161752      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
161753    }
161754  }
161755}
161756
161757/*
161758** Return true if the area covered by p2 is a subset of the area covered
161759** by p1. False otherwise.
161760*/
161761static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
161762  int ii;
161763  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
161764  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161765    RtreeCoord *a1 = &p1->aCoord[ii];
161766    RtreeCoord *a2 = &p2->aCoord[ii];
161767    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
161768     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
161769    ){
161770      return 0;
161771    }
161772  }
161773  return 1;
161774}
161775
161776/*
161777** Return the amount cell p would grow by if it were unioned with pCell.
161778*/
161779static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
161780  RtreeDValue area;
161781  RtreeCell cell;
161782  memcpy(&cell, p, sizeof(RtreeCell));
161783  area = cellArea(pRtree, &cell);
161784  cellUnion(pRtree, &cell, pCell);
161785  return (cellArea(pRtree, &cell)-area);
161786}
161787
161788static RtreeDValue cellOverlap(
161789  Rtree *pRtree,
161790  RtreeCell *p,
161791  RtreeCell *aCell,
161792  int nCell
161793){
161794  int ii;
161795  RtreeDValue overlap = RTREE_ZERO;
161796  for(ii=0; ii<nCell; ii++){
161797    int jj;
161798    RtreeDValue o = (RtreeDValue)1;
161799    for(jj=0; jj<(pRtree->nDim*2); jj+=2){
161800      RtreeDValue x1, x2;
161801      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
161802      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
161803      if( x2<x1 ){
161804        o = (RtreeDValue)0;
161805        break;
161806      }else{
161807        o = o * (x2-x1);
161808      }
161809    }
161810    overlap += o;
161811  }
161812  return overlap;
161813}
161814
161815
161816/*
161817** This function implements the ChooseLeaf algorithm from Gutman[84].
161818** ChooseSubTree in r*tree terminology.
161819*/
161820static int ChooseLeaf(
161821  Rtree *pRtree,               /* Rtree table */
161822  RtreeCell *pCell,            /* Cell to insert into rtree */
161823  int iHeight,                 /* Height of sub-tree rooted at pCell */
161824  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
161825){
161826  int rc;
161827  int ii;
161828  RtreeNode *pNode;
161829  rc = nodeAcquire(pRtree, 1, 0, &pNode);
161830
161831  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
161832    int iCell;
161833    sqlite3_int64 iBest = 0;
161834
161835    RtreeDValue fMinGrowth = RTREE_ZERO;
161836    RtreeDValue fMinArea = RTREE_ZERO;
161837
161838    int nCell = NCELL(pNode);
161839    RtreeCell cell;
161840    RtreeNode *pChild;
161841
161842    RtreeCell *aCell = 0;
161843
161844    /* Select the child node which will be enlarged the least if pCell
161845    ** is inserted into it. Resolve ties by choosing the entry with
161846    ** the smallest area.
161847    */
161848    for(iCell=0; iCell<nCell; iCell++){
161849      int bBest = 0;
161850      RtreeDValue growth;
161851      RtreeDValue area;
161852      nodeGetCell(pRtree, pNode, iCell, &cell);
161853      growth = cellGrowth(pRtree, &cell, pCell);
161854      area = cellArea(pRtree, &cell);
161855      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
161856        bBest = 1;
161857      }
161858      if( bBest ){
161859        fMinGrowth = growth;
161860        fMinArea = area;
161861        iBest = cell.iRowid;
161862      }
161863    }
161864
161865    sqlite3_free(aCell);
161866    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
161867    nodeRelease(pRtree, pNode);
161868    pNode = pChild;
161869  }
161870
161871  *ppLeaf = pNode;
161872  return rc;
161873}
161874
161875/*
161876** A cell with the same content as pCell has just been inserted into
161877** the node pNode. This function updates the bounding box cells in
161878** all ancestor elements.
161879*/
161880static int AdjustTree(
161881  Rtree *pRtree,                    /* Rtree table */
161882  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
161883  RtreeCell *pCell                  /* This cell was just inserted */
161884){
161885  RtreeNode *p = pNode;
161886  while( p->pParent ){
161887    RtreeNode *pParent = p->pParent;
161888    RtreeCell cell;
161889    int iCell;
161890
161891    if( nodeParentIndex(pRtree, p, &iCell) ){
161892      return SQLITE_CORRUPT_VTAB;
161893    }
161894
161895    nodeGetCell(pRtree, pParent, iCell, &cell);
161896    if( !cellContains(pRtree, &cell, pCell) ){
161897      cellUnion(pRtree, &cell, pCell);
161898      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
161899    }
161900
161901    p = pParent;
161902  }
161903  return SQLITE_OK;
161904}
161905
161906/*
161907** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
161908*/
161909static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
161910  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
161911  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
161912  sqlite3_step(pRtree->pWriteRowid);
161913  return sqlite3_reset(pRtree->pWriteRowid);
161914}
161915
161916/*
161917** Write mapping (iNode->iPar) to the <rtree>_parent table.
161918*/
161919static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
161920  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
161921  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
161922  sqlite3_step(pRtree->pWriteParent);
161923  return sqlite3_reset(pRtree->pWriteParent);
161924}
161925
161926static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
161927
161928
161929/*
161930** Arguments aIdx, aDistance and aSpare all point to arrays of size
161931** nIdx. The aIdx array contains the set of integers from 0 to
161932** (nIdx-1) in no particular order. This function sorts the values
161933** in aIdx according to the indexed values in aDistance. For
161934** example, assuming the inputs:
161935**
161936**   aIdx      = { 0,   1,   2,   3 }
161937**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
161938**
161939** this function sets the aIdx array to contain:
161940**
161941**   aIdx      = { 0,   1,   2,   3 }
161942**
161943** The aSpare array is used as temporary working space by the
161944** sorting algorithm.
161945*/
161946static void SortByDistance(
161947  int *aIdx,
161948  int nIdx,
161949  RtreeDValue *aDistance,
161950  int *aSpare
161951){
161952  if( nIdx>1 ){
161953    int iLeft = 0;
161954    int iRight = 0;
161955
161956    int nLeft = nIdx/2;
161957    int nRight = nIdx-nLeft;
161958    int *aLeft = aIdx;
161959    int *aRight = &aIdx[nLeft];
161960
161961    SortByDistance(aLeft, nLeft, aDistance, aSpare);
161962    SortByDistance(aRight, nRight, aDistance, aSpare);
161963
161964    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
161965    aLeft = aSpare;
161966
161967    while( iLeft<nLeft || iRight<nRight ){
161968      if( iLeft==nLeft ){
161969        aIdx[iLeft+iRight] = aRight[iRight];
161970        iRight++;
161971      }else if( iRight==nRight ){
161972        aIdx[iLeft+iRight] = aLeft[iLeft];
161973        iLeft++;
161974      }else{
161975        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
161976        RtreeDValue fRight = aDistance[aRight[iRight]];
161977        if( fLeft<fRight ){
161978          aIdx[iLeft+iRight] = aLeft[iLeft];
161979          iLeft++;
161980        }else{
161981          aIdx[iLeft+iRight] = aRight[iRight];
161982          iRight++;
161983        }
161984      }
161985    }
161986
161987#if 0
161988    /* Check that the sort worked */
161989    {
161990      int jj;
161991      for(jj=1; jj<nIdx; jj++){
161992        RtreeDValue left = aDistance[aIdx[jj-1]];
161993        RtreeDValue right = aDistance[aIdx[jj]];
161994        assert( left<=right );
161995      }
161996    }
161997#endif
161998  }
161999}
162000
162001/*
162002** Arguments aIdx, aCell and aSpare all point to arrays of size
162003** nIdx. The aIdx array contains the set of integers from 0 to
162004** (nIdx-1) in no particular order. This function sorts the values
162005** in aIdx according to dimension iDim of the cells in aCell. The
162006** minimum value of dimension iDim is considered first, the
162007** maximum used to break ties.
162008**
162009** The aSpare array is used as temporary working space by the
162010** sorting algorithm.
162011*/
162012static void SortByDimension(
162013  Rtree *pRtree,
162014  int *aIdx,
162015  int nIdx,
162016  int iDim,
162017  RtreeCell *aCell,
162018  int *aSpare
162019){
162020  if( nIdx>1 ){
162021
162022    int iLeft = 0;
162023    int iRight = 0;
162024
162025    int nLeft = nIdx/2;
162026    int nRight = nIdx-nLeft;
162027    int *aLeft = aIdx;
162028    int *aRight = &aIdx[nLeft];
162029
162030    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
162031    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
162032
162033    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
162034    aLeft = aSpare;
162035    while( iLeft<nLeft || iRight<nRight ){
162036      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
162037      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
162038      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
162039      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
162040      if( (iLeft!=nLeft) && ((iRight==nRight)
162041       || (xleft1<xright1)
162042       || (xleft1==xright1 && xleft2<xright2)
162043      )){
162044        aIdx[iLeft+iRight] = aLeft[iLeft];
162045        iLeft++;
162046      }else{
162047        aIdx[iLeft+iRight] = aRight[iRight];
162048        iRight++;
162049      }
162050    }
162051
162052#if 0
162053    /* Check that the sort worked */
162054    {
162055      int jj;
162056      for(jj=1; jj<nIdx; jj++){
162057        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
162058        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
162059        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
162060        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
162061        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
162062      }
162063    }
162064#endif
162065  }
162066}
162067
162068/*
162069** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
162070*/
162071static int splitNodeStartree(
162072  Rtree *pRtree,
162073  RtreeCell *aCell,
162074  int nCell,
162075  RtreeNode *pLeft,
162076  RtreeNode *pRight,
162077  RtreeCell *pBboxLeft,
162078  RtreeCell *pBboxRight
162079){
162080  int **aaSorted;
162081  int *aSpare;
162082  int ii;
162083
162084  int iBestDim = 0;
162085  int iBestSplit = 0;
162086  RtreeDValue fBestMargin = RTREE_ZERO;
162087
162088  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
162089
162090  aaSorted = (int **)sqlite3_malloc(nByte);
162091  if( !aaSorted ){
162092    return SQLITE_NOMEM;
162093  }
162094
162095  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
162096  memset(aaSorted, 0, nByte);
162097  for(ii=0; ii<pRtree->nDim; ii++){
162098    int jj;
162099    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
162100    for(jj=0; jj<nCell; jj++){
162101      aaSorted[ii][jj] = jj;
162102    }
162103    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
162104  }
162105
162106  for(ii=0; ii<pRtree->nDim; ii++){
162107    RtreeDValue margin = RTREE_ZERO;
162108    RtreeDValue fBestOverlap = RTREE_ZERO;
162109    RtreeDValue fBestArea = RTREE_ZERO;
162110    int iBestLeft = 0;
162111    int nLeft;
162112
162113    for(
162114      nLeft=RTREE_MINCELLS(pRtree);
162115      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
162116      nLeft++
162117    ){
162118      RtreeCell left;
162119      RtreeCell right;
162120      int kk;
162121      RtreeDValue overlap;
162122      RtreeDValue area;
162123
162124      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
162125      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
162126      for(kk=1; kk<(nCell-1); kk++){
162127        if( kk<nLeft ){
162128          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
162129        }else{
162130          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
162131        }
162132      }
162133      margin += cellMargin(pRtree, &left);
162134      margin += cellMargin(pRtree, &right);
162135      overlap = cellOverlap(pRtree, &left, &right, 1);
162136      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
162137      if( (nLeft==RTREE_MINCELLS(pRtree))
162138       || (overlap<fBestOverlap)
162139       || (overlap==fBestOverlap && area<fBestArea)
162140      ){
162141        iBestLeft = nLeft;
162142        fBestOverlap = overlap;
162143        fBestArea = area;
162144      }
162145    }
162146
162147    if( ii==0 || margin<fBestMargin ){
162148      iBestDim = ii;
162149      fBestMargin = margin;
162150      iBestSplit = iBestLeft;
162151    }
162152  }
162153
162154  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
162155  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
162156  for(ii=0; ii<nCell; ii++){
162157    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
162158    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
162159    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
162160    nodeInsertCell(pRtree, pTarget, pCell);
162161    cellUnion(pRtree, pBbox, pCell);
162162  }
162163
162164  sqlite3_free(aaSorted);
162165  return SQLITE_OK;
162166}
162167
162168
162169static int updateMapping(
162170  Rtree *pRtree,
162171  i64 iRowid,
162172  RtreeNode *pNode,
162173  int iHeight
162174){
162175  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
162176  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
162177  if( iHeight>0 ){
162178    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
162179    if( pChild ){
162180      nodeRelease(pRtree, pChild->pParent);
162181      nodeReference(pNode);
162182      pChild->pParent = pNode;
162183    }
162184  }
162185  return xSetMapping(pRtree, iRowid, pNode->iNode);
162186}
162187
162188static int SplitNode(
162189  Rtree *pRtree,
162190  RtreeNode *pNode,
162191  RtreeCell *pCell,
162192  int iHeight
162193){
162194  int i;
162195  int newCellIsRight = 0;
162196
162197  int rc = SQLITE_OK;
162198  int nCell = NCELL(pNode);
162199  RtreeCell *aCell;
162200  int *aiUsed;
162201
162202  RtreeNode *pLeft = 0;
162203  RtreeNode *pRight = 0;
162204
162205  RtreeCell leftbbox;
162206  RtreeCell rightbbox;
162207
162208  /* Allocate an array and populate it with a copy of pCell and
162209  ** all cells from node pLeft. Then zero the original node.
162210  */
162211  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
162212  if( !aCell ){
162213    rc = SQLITE_NOMEM;
162214    goto splitnode_out;
162215  }
162216  aiUsed = (int *)&aCell[nCell+1];
162217  memset(aiUsed, 0, sizeof(int)*(nCell+1));
162218  for(i=0; i<nCell; i++){
162219    nodeGetCell(pRtree, pNode, i, &aCell[i]);
162220  }
162221  nodeZero(pRtree, pNode);
162222  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
162223  nCell++;
162224
162225  if( pNode->iNode==1 ){
162226    pRight = nodeNew(pRtree, pNode);
162227    pLeft = nodeNew(pRtree, pNode);
162228    pRtree->iDepth++;
162229    pNode->isDirty = 1;
162230    writeInt16(pNode->zData, pRtree->iDepth);
162231  }else{
162232    pLeft = pNode;
162233    pRight = nodeNew(pRtree, pLeft->pParent);
162234    nodeReference(pLeft);
162235  }
162236
162237  if( !pLeft || !pRight ){
162238    rc = SQLITE_NOMEM;
162239    goto splitnode_out;
162240  }
162241
162242  memset(pLeft->zData, 0, pRtree->iNodeSize);
162243  memset(pRight->zData, 0, pRtree->iNodeSize);
162244
162245  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
162246                         &leftbbox, &rightbbox);
162247  if( rc!=SQLITE_OK ){
162248    goto splitnode_out;
162249  }
162250
162251  /* Ensure both child nodes have node numbers assigned to them by calling
162252  ** nodeWrite(). Node pRight always needs a node number, as it was created
162253  ** by nodeNew() above. But node pLeft sometimes already has a node number.
162254  ** In this case avoid the all to nodeWrite().
162255  */
162256  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
162257   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
162258  ){
162259    goto splitnode_out;
162260  }
162261
162262  rightbbox.iRowid = pRight->iNode;
162263  leftbbox.iRowid = pLeft->iNode;
162264
162265  if( pNode->iNode==1 ){
162266    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
162267    if( rc!=SQLITE_OK ){
162268      goto splitnode_out;
162269    }
162270  }else{
162271    RtreeNode *pParent = pLeft->pParent;
162272    int iCell;
162273    rc = nodeParentIndex(pRtree, pLeft, &iCell);
162274    if( rc==SQLITE_OK ){
162275      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
162276      rc = AdjustTree(pRtree, pParent, &leftbbox);
162277    }
162278    if( rc!=SQLITE_OK ){
162279      goto splitnode_out;
162280    }
162281  }
162282  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
162283    goto splitnode_out;
162284  }
162285
162286  for(i=0; i<NCELL(pRight); i++){
162287    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
162288    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
162289    if( iRowid==pCell->iRowid ){
162290      newCellIsRight = 1;
162291    }
162292    if( rc!=SQLITE_OK ){
162293      goto splitnode_out;
162294    }
162295  }
162296  if( pNode->iNode==1 ){
162297    for(i=0; i<NCELL(pLeft); i++){
162298      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
162299      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
162300      if( rc!=SQLITE_OK ){
162301        goto splitnode_out;
162302      }
162303    }
162304  }else if( newCellIsRight==0 ){
162305    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
162306  }
162307
162308  if( rc==SQLITE_OK ){
162309    rc = nodeRelease(pRtree, pRight);
162310    pRight = 0;
162311  }
162312  if( rc==SQLITE_OK ){
162313    rc = nodeRelease(pRtree, pLeft);
162314    pLeft = 0;
162315  }
162316
162317splitnode_out:
162318  nodeRelease(pRtree, pRight);
162319  nodeRelease(pRtree, pLeft);
162320  sqlite3_free(aCell);
162321  return rc;
162322}
162323
162324/*
162325** If node pLeaf is not the root of the r-tree and its pParent pointer is
162326** still NULL, load all ancestor nodes of pLeaf into memory and populate
162327** the pLeaf->pParent chain all the way up to the root node.
162328**
162329** This operation is required when a row is deleted (or updated - an update
162330** is implemented as a delete followed by an insert). SQLite provides the
162331** rowid of the row to delete, which can be used to find the leaf on which
162332** the entry resides (argument pLeaf). Once the leaf is located, this
162333** function is called to determine its ancestry.
162334*/
162335static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
162336  int rc = SQLITE_OK;
162337  RtreeNode *pChild = pLeaf;
162338  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
162339    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
162340    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
162341    rc = sqlite3_step(pRtree->pReadParent);
162342    if( rc==SQLITE_ROW ){
162343      RtreeNode *pTest;           /* Used to test for reference loops */
162344      i64 iNode;                  /* Node number of parent node */
162345
162346      /* Before setting pChild->pParent, test that we are not creating a
162347      ** loop of references (as we would if, say, pChild==pParent). We don't
162348      ** want to do this as it leads to a memory leak when trying to delete
162349      ** the referenced counted node structures.
162350      */
162351      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
162352      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
162353      if( !pTest ){
162354        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
162355      }
162356    }
162357    rc = sqlite3_reset(pRtree->pReadParent);
162358    if( rc==SQLITE_OK ) rc = rc2;
162359    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
162360    pChild = pChild->pParent;
162361  }
162362  return rc;
162363}
162364
162365static int deleteCell(Rtree *, RtreeNode *, int, int);
162366
162367static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
162368  int rc;
162369  int rc2;
162370  RtreeNode *pParent = 0;
162371  int iCell;
162372
162373  assert( pNode->nRef==1 );
162374
162375  /* Remove the entry in the parent cell. */
162376  rc = nodeParentIndex(pRtree, pNode, &iCell);
162377  if( rc==SQLITE_OK ){
162378    pParent = pNode->pParent;
162379    pNode->pParent = 0;
162380    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
162381  }
162382  rc2 = nodeRelease(pRtree, pParent);
162383  if( rc==SQLITE_OK ){
162384    rc = rc2;
162385  }
162386  if( rc!=SQLITE_OK ){
162387    return rc;
162388  }
162389
162390  /* Remove the xxx_node entry. */
162391  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
162392  sqlite3_step(pRtree->pDeleteNode);
162393  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
162394    return rc;
162395  }
162396
162397  /* Remove the xxx_parent entry. */
162398  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
162399  sqlite3_step(pRtree->pDeleteParent);
162400  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
162401    return rc;
162402  }
162403
162404  /* Remove the node from the in-memory hash table and link it into
162405  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
162406  */
162407  nodeHashDelete(pRtree, pNode);
162408  pNode->iNode = iHeight;
162409  pNode->pNext = pRtree->pDeleted;
162410  pNode->nRef++;
162411  pRtree->pDeleted = pNode;
162412
162413  return SQLITE_OK;
162414}
162415
162416static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
162417  RtreeNode *pParent = pNode->pParent;
162418  int rc = SQLITE_OK;
162419  if( pParent ){
162420    int ii;
162421    int nCell = NCELL(pNode);
162422    RtreeCell box;                            /* Bounding box for pNode */
162423    nodeGetCell(pRtree, pNode, 0, &box);
162424    for(ii=1; ii<nCell; ii++){
162425      RtreeCell cell;
162426      nodeGetCell(pRtree, pNode, ii, &cell);
162427      cellUnion(pRtree, &box, &cell);
162428    }
162429    box.iRowid = pNode->iNode;
162430    rc = nodeParentIndex(pRtree, pNode, &ii);
162431    if( rc==SQLITE_OK ){
162432      nodeOverwriteCell(pRtree, pParent, &box, ii);
162433      rc = fixBoundingBox(pRtree, pParent);
162434    }
162435  }
162436  return rc;
162437}
162438
162439/*
162440** Delete the cell at index iCell of node pNode. After removing the
162441** cell, adjust the r-tree data structure if required.
162442*/
162443static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
162444  RtreeNode *pParent;
162445  int rc;
162446
162447  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
162448    return rc;
162449  }
162450
162451  /* Remove the cell from the node. This call just moves bytes around
162452  ** the in-memory node image, so it cannot fail.
162453  */
162454  nodeDeleteCell(pRtree, pNode, iCell);
162455
162456  /* If the node is not the tree root and now has less than the minimum
162457  ** number of cells, remove it from the tree. Otherwise, update the
162458  ** cell in the parent node so that it tightly contains the updated
162459  ** node.
162460  */
162461  pParent = pNode->pParent;
162462  assert( pParent || pNode->iNode==1 );
162463  if( pParent ){
162464    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
162465      rc = removeNode(pRtree, pNode, iHeight);
162466    }else{
162467      rc = fixBoundingBox(pRtree, pNode);
162468    }
162469  }
162470
162471  return rc;
162472}
162473
162474static int Reinsert(
162475  Rtree *pRtree,
162476  RtreeNode *pNode,
162477  RtreeCell *pCell,
162478  int iHeight
162479){
162480  int *aOrder;
162481  int *aSpare;
162482  RtreeCell *aCell;
162483  RtreeDValue *aDistance;
162484  int nCell;
162485  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
162486  int iDim;
162487  int ii;
162488  int rc = SQLITE_OK;
162489  int n;
162490
162491  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
162492
162493  nCell = NCELL(pNode)+1;
162494  n = (nCell+1)&(~1);
162495
162496  /* Allocate the buffers used by this operation. The allocation is
162497  ** relinquished before this function returns.
162498  */
162499  aCell = (RtreeCell *)sqlite3_malloc(n * (
162500    sizeof(RtreeCell)     +         /* aCell array */
162501    sizeof(int)           +         /* aOrder array */
162502    sizeof(int)           +         /* aSpare array */
162503    sizeof(RtreeDValue)             /* aDistance array */
162504  ));
162505  if( !aCell ){
162506    return SQLITE_NOMEM;
162507  }
162508  aOrder    = (int *)&aCell[n];
162509  aSpare    = (int *)&aOrder[n];
162510  aDistance = (RtreeDValue *)&aSpare[n];
162511
162512  for(ii=0; ii<nCell; ii++){
162513    if( ii==(nCell-1) ){
162514      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
162515    }else{
162516      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
162517    }
162518    aOrder[ii] = ii;
162519    for(iDim=0; iDim<pRtree->nDim; iDim++){
162520      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
162521      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
162522    }
162523  }
162524  for(iDim=0; iDim<pRtree->nDim; iDim++){
162525    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
162526  }
162527
162528  for(ii=0; ii<nCell; ii++){
162529    aDistance[ii] = RTREE_ZERO;
162530    for(iDim=0; iDim<pRtree->nDim; iDim++){
162531      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
162532                               DCOORD(aCell[ii].aCoord[iDim*2]));
162533      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
162534    }
162535  }
162536
162537  SortByDistance(aOrder, nCell, aDistance, aSpare);
162538  nodeZero(pRtree, pNode);
162539
162540  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
162541    RtreeCell *p = &aCell[aOrder[ii]];
162542    nodeInsertCell(pRtree, pNode, p);
162543    if( p->iRowid==pCell->iRowid ){
162544      if( iHeight==0 ){
162545        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
162546      }else{
162547        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
162548      }
162549    }
162550  }
162551  if( rc==SQLITE_OK ){
162552    rc = fixBoundingBox(pRtree, pNode);
162553  }
162554  for(; rc==SQLITE_OK && ii<nCell; ii++){
162555    /* Find a node to store this cell in. pNode->iNode currently contains
162556    ** the height of the sub-tree headed by the cell.
162557    */
162558    RtreeNode *pInsert;
162559    RtreeCell *p = &aCell[aOrder[ii]];
162560    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
162561    if( rc==SQLITE_OK ){
162562      int rc2;
162563      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
162564      rc2 = nodeRelease(pRtree, pInsert);
162565      if( rc==SQLITE_OK ){
162566        rc = rc2;
162567      }
162568    }
162569  }
162570
162571  sqlite3_free(aCell);
162572  return rc;
162573}
162574
162575/*
162576** Insert cell pCell into node pNode. Node pNode is the head of a
162577** subtree iHeight high (leaf nodes have iHeight==0).
162578*/
162579static int rtreeInsertCell(
162580  Rtree *pRtree,
162581  RtreeNode *pNode,
162582  RtreeCell *pCell,
162583  int iHeight
162584){
162585  int rc = SQLITE_OK;
162586  if( iHeight>0 ){
162587    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
162588    if( pChild ){
162589      nodeRelease(pRtree, pChild->pParent);
162590      nodeReference(pNode);
162591      pChild->pParent = pNode;
162592    }
162593  }
162594  if( nodeInsertCell(pRtree, pNode, pCell) ){
162595    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
162596      rc = SplitNode(pRtree, pNode, pCell, iHeight);
162597    }else{
162598      pRtree->iReinsertHeight = iHeight;
162599      rc = Reinsert(pRtree, pNode, pCell, iHeight);
162600    }
162601  }else{
162602    rc = AdjustTree(pRtree, pNode, pCell);
162603    if( rc==SQLITE_OK ){
162604      if( iHeight==0 ){
162605        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
162606      }else{
162607        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
162608      }
162609    }
162610  }
162611  return rc;
162612}
162613
162614static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
162615  int ii;
162616  int rc = SQLITE_OK;
162617  int nCell = NCELL(pNode);
162618
162619  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
162620    RtreeNode *pInsert;
162621    RtreeCell cell;
162622    nodeGetCell(pRtree, pNode, ii, &cell);
162623
162624    /* Find a node to store this cell in. pNode->iNode currently contains
162625    ** the height of the sub-tree headed by the cell.
162626    */
162627    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
162628    if( rc==SQLITE_OK ){
162629      int rc2;
162630      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
162631      rc2 = nodeRelease(pRtree, pInsert);
162632      if( rc==SQLITE_OK ){
162633        rc = rc2;
162634      }
162635    }
162636  }
162637  return rc;
162638}
162639
162640/*
162641** Select a currently unused rowid for a new r-tree record.
162642*/
162643static int newRowid(Rtree *pRtree, i64 *piRowid){
162644  int rc;
162645  sqlite3_bind_null(pRtree->pWriteRowid, 1);
162646  sqlite3_bind_null(pRtree->pWriteRowid, 2);
162647  sqlite3_step(pRtree->pWriteRowid);
162648  rc = sqlite3_reset(pRtree->pWriteRowid);
162649  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
162650  return rc;
162651}
162652
162653/*
162654** Remove the entry with rowid=iDelete from the r-tree structure.
162655*/
162656static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
162657  int rc;                         /* Return code */
162658  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
162659  int iCell;                      /* Index of iDelete cell in pLeaf */
162660  RtreeNode *pRoot;               /* Root node of rtree structure */
162661
162662
162663  /* Obtain a reference to the root node to initialize Rtree.iDepth */
162664  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
162665
162666  /* Obtain a reference to the leaf node that contains the entry
162667  ** about to be deleted.
162668  */
162669  if( rc==SQLITE_OK ){
162670    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
162671  }
162672
162673  /* Delete the cell in question from the leaf node. */
162674  if( rc==SQLITE_OK ){
162675    int rc2;
162676    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
162677    if( rc==SQLITE_OK ){
162678      rc = deleteCell(pRtree, pLeaf, iCell, 0);
162679    }
162680    rc2 = nodeRelease(pRtree, pLeaf);
162681    if( rc==SQLITE_OK ){
162682      rc = rc2;
162683    }
162684  }
162685
162686  /* Delete the corresponding entry in the <rtree>_rowid table. */
162687  if( rc==SQLITE_OK ){
162688    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
162689    sqlite3_step(pRtree->pDeleteRowid);
162690    rc = sqlite3_reset(pRtree->pDeleteRowid);
162691  }
162692
162693  /* Check if the root node now has exactly one child. If so, remove
162694  ** it, schedule the contents of the child for reinsertion and
162695  ** reduce the tree height by one.
162696  **
162697  ** This is equivalent to copying the contents of the child into
162698  ** the root node (the operation that Gutman's paper says to perform
162699  ** in this scenario).
162700  */
162701  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
162702    int rc2;
162703    RtreeNode *pChild;
162704    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
162705    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
162706    if( rc==SQLITE_OK ){
162707      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
162708    }
162709    rc2 = nodeRelease(pRtree, pChild);
162710    if( rc==SQLITE_OK ) rc = rc2;
162711    if( rc==SQLITE_OK ){
162712      pRtree->iDepth--;
162713      writeInt16(pRoot->zData, pRtree->iDepth);
162714      pRoot->isDirty = 1;
162715    }
162716  }
162717
162718  /* Re-insert the contents of any underfull nodes removed from the tree. */
162719  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
162720    if( rc==SQLITE_OK ){
162721      rc = reinsertNodeContent(pRtree, pLeaf);
162722    }
162723    pRtree->pDeleted = pLeaf->pNext;
162724    sqlite3_free(pLeaf);
162725  }
162726
162727  /* Release the reference to the root node. */
162728  if( rc==SQLITE_OK ){
162729    rc = nodeRelease(pRtree, pRoot);
162730  }else{
162731    nodeRelease(pRtree, pRoot);
162732  }
162733
162734  return rc;
162735}
162736
162737/*
162738** Rounding constants for float->double conversion.
162739*/
162740#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
162741#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
162742
162743#if !defined(SQLITE_RTREE_INT_ONLY)
162744/*
162745** Convert an sqlite3_value into an RtreeValue (presumably a float)
162746** while taking care to round toward negative or positive, respectively.
162747*/
162748static RtreeValue rtreeValueDown(sqlite3_value *v){
162749  double d = sqlite3_value_double(v);
162750  float f = (float)d;
162751  if( f>d ){
162752    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
162753  }
162754  return f;
162755}
162756static RtreeValue rtreeValueUp(sqlite3_value *v){
162757  double d = sqlite3_value_double(v);
162758  float f = (float)d;
162759  if( f<d ){
162760    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
162761  }
162762  return f;
162763}
162764#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
162765
162766/*
162767** A constraint has failed while inserting a row into an rtree table.
162768** Assuming no OOM error occurs, this function sets the error message
162769** (at pRtree->base.zErrMsg) to an appropriate value and returns
162770** SQLITE_CONSTRAINT.
162771**
162772** Parameter iCol is the index of the leftmost column involved in the
162773** constraint failure. If it is 0, then the constraint that failed is
162774** the unique constraint on the id column. Otherwise, it is the rtree
162775** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
162776**
162777** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
162778*/
162779static int rtreeConstraintError(Rtree *pRtree, int iCol){
162780  sqlite3_stmt *pStmt = 0;
162781  char *zSql;
162782  int rc;
162783
162784  assert( iCol==0 || iCol%2 );
162785  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
162786  if( zSql ){
162787    rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
162788  }else{
162789    rc = SQLITE_NOMEM;
162790  }
162791  sqlite3_free(zSql);
162792
162793  if( rc==SQLITE_OK ){
162794    if( iCol==0 ){
162795      const char *zCol = sqlite3_column_name(pStmt, 0);
162796      pRtree->base.zErrMsg = sqlite3_mprintf(
162797          "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
162798      );
162799    }else{
162800      const char *zCol1 = sqlite3_column_name(pStmt, iCol);
162801      const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
162802      pRtree->base.zErrMsg = sqlite3_mprintf(
162803          "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
162804      );
162805    }
162806  }
162807
162808  sqlite3_finalize(pStmt);
162809  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
162810}
162811
162812
162813
162814/*
162815** The xUpdate method for rtree module virtual tables.
162816*/
162817static int rtreeUpdate(
162818  sqlite3_vtab *pVtab,
162819  int nData,
162820  sqlite3_value **azData,
162821  sqlite_int64 *pRowid
162822){
162823  Rtree *pRtree = (Rtree *)pVtab;
162824  int rc = SQLITE_OK;
162825  RtreeCell cell;                 /* New cell to insert if nData>1 */
162826  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
162827
162828  rtreeReference(pRtree);
162829  assert(nData>=1);
162830
162831  cell.iRowid = 0;  /* Used only to suppress a compiler warning */
162832
162833  /* Constraint handling. A write operation on an r-tree table may return
162834  ** SQLITE_CONSTRAINT for two reasons:
162835  **
162836  **   1. A duplicate rowid value, or
162837  **   2. The supplied data violates the "x2>=x1" constraint.
162838  **
162839  ** In the first case, if the conflict-handling mode is REPLACE, then
162840  ** the conflicting row can be removed before proceeding. In the second
162841  ** case, SQLITE_CONSTRAINT must be returned regardless of the
162842  ** conflict-handling mode specified by the user.
162843  */
162844  if( nData>1 ){
162845    int ii;
162846
162847    /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
162848    **
162849    ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
162850    ** with "column" that are interpreted as table constraints.
162851    ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
162852    ** This problem was discovered after years of use, so we silently ignore
162853    ** these kinds of misdeclared tables to avoid breaking any legacy.
162854    */
162855    assert( nData<=(pRtree->nDim*2 + 3) );
162856
162857#ifndef SQLITE_RTREE_INT_ONLY
162858    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
162859      for(ii=0; ii<nData-4; ii+=2){
162860        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
162861        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
162862        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
162863          rc = rtreeConstraintError(pRtree, ii+1);
162864          goto constraint;
162865        }
162866      }
162867    }else
162868#endif
162869    {
162870      for(ii=0; ii<nData-4; ii+=2){
162871        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
162872        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
162873        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
162874          rc = rtreeConstraintError(pRtree, ii+1);
162875          goto constraint;
162876        }
162877      }
162878    }
162879
162880    /* If a rowid value was supplied, check if it is already present in
162881    ** the table. If so, the constraint has failed. */
162882    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
162883      cell.iRowid = sqlite3_value_int64(azData[2]);
162884      if( sqlite3_value_type(azData[0])==SQLITE_NULL
162885       || sqlite3_value_int64(azData[0])!=cell.iRowid
162886      ){
162887        int steprc;
162888        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
162889        steprc = sqlite3_step(pRtree->pReadRowid);
162890        rc = sqlite3_reset(pRtree->pReadRowid);
162891        if( SQLITE_ROW==steprc ){
162892          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
162893            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
162894          }else{
162895            rc = rtreeConstraintError(pRtree, 0);
162896            goto constraint;
162897          }
162898        }
162899      }
162900      bHaveRowid = 1;
162901    }
162902  }
162903
162904  /* If azData[0] is not an SQL NULL value, it is the rowid of a
162905  ** record to delete from the r-tree table. The following block does
162906  ** just that.
162907  */
162908  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
162909    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
162910  }
162911
162912  /* If the azData[] array contains more than one element, elements
162913  ** (azData[2]..azData[argc-1]) contain a new record to insert into
162914  ** the r-tree structure.
162915  */
162916  if( rc==SQLITE_OK && nData>1 ){
162917    /* Insert the new record into the r-tree */
162918    RtreeNode *pLeaf = 0;
162919
162920    /* Figure out the rowid of the new row. */
162921    if( bHaveRowid==0 ){
162922      rc = newRowid(pRtree, &cell.iRowid);
162923    }
162924    *pRowid = cell.iRowid;
162925
162926    if( rc==SQLITE_OK ){
162927      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
162928    }
162929    if( rc==SQLITE_OK ){
162930      int rc2;
162931      pRtree->iReinsertHeight = -1;
162932      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
162933      rc2 = nodeRelease(pRtree, pLeaf);
162934      if( rc==SQLITE_OK ){
162935        rc = rc2;
162936      }
162937    }
162938  }
162939
162940constraint:
162941  rtreeRelease(pRtree);
162942  return rc;
162943}
162944
162945/*
162946** The xRename method for rtree module virtual tables.
162947*/
162948static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
162949  Rtree *pRtree = (Rtree *)pVtab;
162950  int rc = SQLITE_NOMEM;
162951  char *zSql = sqlite3_mprintf(
162952    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
162953    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
162954    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
162955    , pRtree->zDb, pRtree->zName, zNewName
162956    , pRtree->zDb, pRtree->zName, zNewName
162957    , pRtree->zDb, pRtree->zName, zNewName
162958  );
162959  if( zSql ){
162960    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
162961    sqlite3_free(zSql);
162962  }
162963  return rc;
162964}
162965
162966/*
162967** This function populates the pRtree->nRowEst variable with an estimate
162968** of the number of rows in the virtual table. If possible, this is based
162969** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
162970*/
162971static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
162972  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
162973  char *zSql;
162974  sqlite3_stmt *p;
162975  int rc;
162976  i64 nRow = 0;
162977
162978  if( sqlite3_table_column_metadata(db,pRtree->zDb,"sqlite_stat1",
162979          0,0,0,0,0,0)==SQLITE_ERROR ){
162980    pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
162981    return SQLITE_OK;
162982  }
162983  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
162984  if( zSql==0 ){
162985    rc = SQLITE_NOMEM;
162986  }else{
162987    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
162988    if( rc==SQLITE_OK ){
162989      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
162990      rc = sqlite3_finalize(p);
162991    }else if( rc!=SQLITE_NOMEM ){
162992      rc = SQLITE_OK;
162993    }
162994
162995    if( rc==SQLITE_OK ){
162996      if( nRow==0 ){
162997        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
162998      }else{
162999        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
163000      }
163001    }
163002    sqlite3_free(zSql);
163003  }
163004
163005  return rc;
163006}
163007
163008static sqlite3_module rtreeModule = {
163009  0,                          /* iVersion */
163010  rtreeCreate,                /* xCreate - create a table */
163011  rtreeConnect,               /* xConnect - connect to an existing table */
163012  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
163013  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
163014  rtreeDestroy,               /* xDestroy - Drop a table */
163015  rtreeOpen,                  /* xOpen - open a cursor */
163016  rtreeClose,                 /* xClose - close a cursor */
163017  rtreeFilter,                /* xFilter - configure scan constraints */
163018  rtreeNext,                  /* xNext - advance a cursor */
163019  rtreeEof,                   /* xEof */
163020  rtreeColumn,                /* xColumn - read data */
163021  rtreeRowid,                 /* xRowid - read data */
163022  rtreeUpdate,                /* xUpdate - write data */
163023  0,                          /* xBegin - begin transaction */
163024  0,                          /* xSync - sync transaction */
163025  0,                          /* xCommit - commit transaction */
163026  0,                          /* xRollback - rollback transaction */
163027  0,                          /* xFindFunction - function overloading */
163028  rtreeRename,                /* xRename - rename the table */
163029  0,                          /* xSavepoint */
163030  0,                          /* xRelease */
163031  0                           /* xRollbackTo */
163032};
163033
163034static int rtreeSqlInit(
163035  Rtree *pRtree,
163036  sqlite3 *db,
163037  const char *zDb,
163038  const char *zPrefix,
163039  int isCreate
163040){
163041  int rc = SQLITE_OK;
163042
163043  #define N_STATEMENT 9
163044  static const char *azSql[N_STATEMENT] = {
163045    /* Read and write the xxx_node table */
163046    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
163047    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
163048    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
163049
163050    /* Read and write the xxx_rowid table */
163051    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
163052    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
163053    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
163054
163055    /* Read and write the xxx_parent table */
163056    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
163057    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
163058    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
163059  };
163060  sqlite3_stmt **appStmt[N_STATEMENT];
163061  int i;
163062
163063  pRtree->db = db;
163064
163065  if( isCreate ){
163066    char *zCreate = sqlite3_mprintf(
163067"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
163068"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
163069"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
163070                                  " parentnode INTEGER);"
163071"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
163072      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
163073    );
163074    if( !zCreate ){
163075      return SQLITE_NOMEM;
163076    }
163077    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
163078    sqlite3_free(zCreate);
163079    if( rc!=SQLITE_OK ){
163080      return rc;
163081    }
163082  }
163083
163084  appStmt[0] = &pRtree->pReadNode;
163085  appStmt[1] = &pRtree->pWriteNode;
163086  appStmt[2] = &pRtree->pDeleteNode;
163087  appStmt[3] = &pRtree->pReadRowid;
163088  appStmt[4] = &pRtree->pWriteRowid;
163089  appStmt[5] = &pRtree->pDeleteRowid;
163090  appStmt[6] = &pRtree->pReadParent;
163091  appStmt[7] = &pRtree->pWriteParent;
163092  appStmt[8] = &pRtree->pDeleteParent;
163093
163094  rc = rtreeQueryStat1(db, pRtree);
163095  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
163096    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
163097    if( zSql ){
163098      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
163099    }else{
163100      rc = SQLITE_NOMEM;
163101    }
163102    sqlite3_free(zSql);
163103  }
163104
163105  return rc;
163106}
163107
163108/*
163109** The second argument to this function contains the text of an SQL statement
163110** that returns a single integer value. The statement is compiled and executed
163111** using database connection db. If successful, the integer value returned
163112** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
163113** code is returned and the value of *piVal after returning is not defined.
163114*/
163115static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
163116  int rc = SQLITE_NOMEM;
163117  if( zSql ){
163118    sqlite3_stmt *pStmt = 0;
163119    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
163120    if( rc==SQLITE_OK ){
163121      if( SQLITE_ROW==sqlite3_step(pStmt) ){
163122        *piVal = sqlite3_column_int(pStmt, 0);
163123      }
163124      rc = sqlite3_finalize(pStmt);
163125    }
163126  }
163127  return rc;
163128}
163129
163130/*
163131** This function is called from within the xConnect() or xCreate() method to
163132** determine the node-size used by the rtree table being created or connected
163133** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
163134** Otherwise, an SQLite error code is returned.
163135**
163136** If this function is being called as part of an xConnect(), then the rtree
163137** table already exists. In this case the node-size is determined by inspecting
163138** the root node of the tree.
163139**
163140** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
163141** This ensures that each node is stored on a single database page. If the
163142** database page-size is so large that more than RTREE_MAXCELLS entries
163143** would fit in a single node, use a smaller node-size.
163144*/
163145static int getNodeSize(
163146  sqlite3 *db,                    /* Database handle */
163147  Rtree *pRtree,                  /* Rtree handle */
163148  int isCreate,                   /* True for xCreate, false for xConnect */
163149  char **pzErr                    /* OUT: Error message, if any */
163150){
163151  int rc;
163152  char *zSql;
163153  if( isCreate ){
163154    int iPageSize = 0;
163155    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
163156    rc = getIntFromStmt(db, zSql, &iPageSize);
163157    if( rc==SQLITE_OK ){
163158      pRtree->iNodeSize = iPageSize-64;
163159      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
163160        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
163161      }
163162    }else{
163163      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163164    }
163165  }else{
163166    zSql = sqlite3_mprintf(
163167        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
163168        pRtree->zDb, pRtree->zName
163169    );
163170    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
163171    if( rc!=SQLITE_OK ){
163172      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163173    }
163174  }
163175
163176  sqlite3_free(zSql);
163177  return rc;
163178}
163179
163180/*
163181** This function is the implementation of both the xConnect and xCreate
163182** methods of the r-tree virtual table.
163183**
163184**   argv[0]   -> module name
163185**   argv[1]   -> database name
163186**   argv[2]   -> table name
163187**   argv[...] -> column names...
163188*/
163189static int rtreeInit(
163190  sqlite3 *db,                        /* Database connection */
163191  void *pAux,                         /* One of the RTREE_COORD_* constants */
163192  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
163193  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
163194  char **pzErr,                       /* OUT: Error message, if any */
163195  int isCreate                        /* True for xCreate, false for xConnect */
163196){
163197  int rc = SQLITE_OK;
163198  Rtree *pRtree;
163199  int nDb;              /* Length of string argv[1] */
163200  int nName;            /* Length of string argv[2] */
163201  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
163202
163203  const char *aErrMsg[] = {
163204    0,                                                    /* 0 */
163205    "Wrong number of columns for an rtree table",         /* 1 */
163206    "Too few columns for an rtree table",                 /* 2 */
163207    "Too many columns for an rtree table"                 /* 3 */
163208  };
163209
163210  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
163211  if( aErrMsg[iErr] ){
163212    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
163213    return SQLITE_ERROR;
163214  }
163215
163216  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
163217
163218  /* Allocate the sqlite3_vtab structure */
163219  nDb = (int)strlen(argv[1]);
163220  nName = (int)strlen(argv[2]);
163221  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
163222  if( !pRtree ){
163223    return SQLITE_NOMEM;
163224  }
163225  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
163226  pRtree->nBusy = 1;
163227  pRtree->base.pModule = &rtreeModule;
163228  pRtree->zDb = (char *)&pRtree[1];
163229  pRtree->zName = &pRtree->zDb[nDb+1];
163230  pRtree->nDim = (argc-4)/2;
163231  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
163232  pRtree->eCoordType = eCoordType;
163233  memcpy(pRtree->zDb, argv[1], nDb);
163234  memcpy(pRtree->zName, argv[2], nName);
163235
163236  /* Figure out the node size to use. */
163237  rc = getNodeSize(db, pRtree, isCreate, pzErr);
163238
163239  /* Create/Connect to the underlying relational database schema. If
163240  ** that is successful, call sqlite3_declare_vtab() to configure
163241  ** the r-tree table schema.
163242  */
163243  if( rc==SQLITE_OK ){
163244    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
163245      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163246    }else{
163247      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
163248      char *zTmp;
163249      int ii;
163250      for(ii=4; zSql && ii<argc; ii++){
163251        zTmp = zSql;
163252        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
163253        sqlite3_free(zTmp);
163254      }
163255      if( zSql ){
163256        zTmp = zSql;
163257        zSql = sqlite3_mprintf("%s);", zTmp);
163258        sqlite3_free(zTmp);
163259      }
163260      if( !zSql ){
163261        rc = SQLITE_NOMEM;
163262      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
163263        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163264      }
163265      sqlite3_free(zSql);
163266    }
163267  }
163268
163269  if( rc==SQLITE_OK ){
163270    *ppVtab = (sqlite3_vtab *)pRtree;
163271  }else{
163272    assert( *ppVtab==0 );
163273    assert( pRtree->nBusy==1 );
163274    rtreeRelease(pRtree);
163275  }
163276  return rc;
163277}
163278
163279
163280/*
163281** Implementation of a scalar function that decodes r-tree nodes to
163282** human readable strings. This can be used for debugging and analysis.
163283**
163284** The scalar function takes two arguments: (1) the number of dimensions
163285** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
163286** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
163287** deserialize all nodes, a statement like:
163288**
163289**   SELECT rtreenode(2, data) FROM rt_node;
163290**
163291** The human readable string takes the form of a Tcl list with one
163292** entry for each cell in the r-tree node. Each entry is itself a
163293** list, containing the 8-byte rowid/pageno followed by the
163294** <num-dimension>*2 coordinates.
163295*/
163296static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
163297  char *zText = 0;
163298  RtreeNode node;
163299  Rtree tree;
163300  int ii;
163301
163302  UNUSED_PARAMETER(nArg);
163303  memset(&node, 0, sizeof(RtreeNode));
163304  memset(&tree, 0, sizeof(Rtree));
163305  tree.nDim = sqlite3_value_int(apArg[0]);
163306  tree.nBytesPerCell = 8 + 8 * tree.nDim;
163307  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
163308
163309  for(ii=0; ii<NCELL(&node); ii++){
163310    char zCell[512];
163311    int nCell = 0;
163312    RtreeCell cell;
163313    int jj;
163314
163315    nodeGetCell(&tree, &node, ii, &cell);
163316    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
163317    nCell = (int)strlen(zCell);
163318    for(jj=0; jj<tree.nDim*2; jj++){
163319#ifndef SQLITE_RTREE_INT_ONLY
163320      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
163321                       (double)cell.aCoord[jj].f);
163322#else
163323      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
163324                       cell.aCoord[jj].i);
163325#endif
163326      nCell = (int)strlen(zCell);
163327    }
163328
163329    if( zText ){
163330      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
163331      sqlite3_free(zText);
163332      zText = zTextNew;
163333    }else{
163334      zText = sqlite3_mprintf("{%s}", zCell);
163335    }
163336  }
163337
163338  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
163339}
163340
163341/* This routine implements an SQL function that returns the "depth" parameter
163342** from the front of a blob that is an r-tree node.  For example:
163343**
163344**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
163345**
163346** The depth value is 0 for all nodes other than the root node, and the root
163347** node always has nodeno=1, so the example above is the primary use for this
163348** routine.  This routine is intended for testing and analysis only.
163349*/
163350static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
163351  UNUSED_PARAMETER(nArg);
163352  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
163353   || sqlite3_value_bytes(apArg[0])<2
163354  ){
163355    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
163356  }else{
163357    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
163358    sqlite3_result_int(ctx, readInt16(zBlob));
163359  }
163360}
163361
163362/*
163363** Register the r-tree module with database handle db. This creates the
163364** virtual table module "rtree" and the debugging/analysis scalar
163365** function "rtreenode".
163366*/
163367SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
163368  const int utf8 = SQLITE_UTF8;
163369  int rc;
163370
163371  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
163372  if( rc==SQLITE_OK ){
163373    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
163374  }
163375  if( rc==SQLITE_OK ){
163376#ifdef SQLITE_RTREE_INT_ONLY
163377    void *c = (void *)RTREE_COORD_INT32;
163378#else
163379    void *c = (void *)RTREE_COORD_REAL32;
163380#endif
163381    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
163382  }
163383  if( rc==SQLITE_OK ){
163384    void *c = (void *)RTREE_COORD_INT32;
163385    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
163386  }
163387
163388  return rc;
163389}
163390
163391/*
163392** This routine deletes the RtreeGeomCallback object that was attached
163393** one of the SQL functions create by sqlite3_rtree_geometry_callback()
163394** or sqlite3_rtree_query_callback().  In other words, this routine is the
163395** destructor for an RtreeGeomCallback objecct.  This routine is called when
163396** the corresponding SQL function is deleted.
163397*/
163398static void rtreeFreeCallback(void *p){
163399  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
163400  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
163401  sqlite3_free(p);
163402}
163403
163404/*
163405** This routine frees the BLOB that is returned by geomCallback().
163406*/
163407static void rtreeMatchArgFree(void *pArg){
163408  int i;
163409  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
163410  for(i=0; i<p->nParam; i++){
163411    sqlite3_value_free(p->apSqlParam[i]);
163412  }
163413  sqlite3_free(p);
163414}
163415
163416/*
163417** Each call to sqlite3_rtree_geometry_callback() or
163418** sqlite3_rtree_query_callback() creates an ordinary SQLite
163419** scalar function that is implemented by this routine.
163420**
163421** All this function does is construct an RtreeMatchArg object that
163422** contains the geometry-checking callback routines and a list of
163423** parameters to this function, then return that RtreeMatchArg object
163424** as a BLOB.
163425**
163426** The R-Tree MATCH operator will read the returned BLOB, deserialize
163427** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
163428** out which elements of the R-Tree should be returned by the query.
163429*/
163430static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
163431  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
163432  RtreeMatchArg *pBlob;
163433  int nBlob;
163434  int memErr = 0;
163435
163436  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
163437           + nArg*sizeof(sqlite3_value*);
163438  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
163439  if( !pBlob ){
163440    sqlite3_result_error_nomem(ctx);
163441  }else{
163442    int i;
163443    pBlob->magic = RTREE_GEOMETRY_MAGIC;
163444    pBlob->cb = pGeomCtx[0];
163445    pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
163446    pBlob->nParam = nArg;
163447    for(i=0; i<nArg; i++){
163448      pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
163449      if( pBlob->apSqlParam[i]==0 ) memErr = 1;
163450#ifdef SQLITE_RTREE_INT_ONLY
163451      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
163452#else
163453      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
163454#endif
163455    }
163456    if( memErr ){
163457      sqlite3_result_error_nomem(ctx);
163458      rtreeMatchArgFree(pBlob);
163459    }else{
163460      sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
163461    }
163462  }
163463}
163464
163465/*
163466** Register a new geometry function for use with the r-tree MATCH operator.
163467*/
163468SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
163469  sqlite3 *db,                  /* Register SQL function on this connection */
163470  const char *zGeom,            /* Name of the new SQL function */
163471  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
163472  void *pContext                /* Extra data associated with the callback */
163473){
163474  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
163475
163476  /* Allocate and populate the context object. */
163477  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
163478  if( !pGeomCtx ) return SQLITE_NOMEM;
163479  pGeomCtx->xGeom = xGeom;
163480  pGeomCtx->xQueryFunc = 0;
163481  pGeomCtx->xDestructor = 0;
163482  pGeomCtx->pContext = pContext;
163483  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
163484      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
163485  );
163486}
163487
163488/*
163489** Register a new 2nd-generation geometry function for use with the
163490** r-tree MATCH operator.
163491*/
163492SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
163493  sqlite3 *db,                 /* Register SQL function on this connection */
163494  const char *zQueryFunc,      /* Name of new SQL function */
163495  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
163496  void *pContext,              /* Extra data passed into the callback */
163497  void (*xDestructor)(void*)   /* Destructor for the extra data */
163498){
163499  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
163500
163501  /* Allocate and populate the context object. */
163502  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
163503  if( !pGeomCtx ) return SQLITE_NOMEM;
163504  pGeomCtx->xGeom = 0;
163505  pGeomCtx->xQueryFunc = xQueryFunc;
163506  pGeomCtx->xDestructor = xDestructor;
163507  pGeomCtx->pContext = pContext;
163508  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
163509      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
163510  );
163511}
163512
163513#if !SQLITE_CORE
163514#ifdef _WIN32
163515__declspec(dllexport)
163516#endif
163517SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
163518  sqlite3 *db,
163519  char **pzErrMsg,
163520  const sqlite3_api_routines *pApi
163521){
163522  SQLITE_EXTENSION_INIT2(pApi)
163523  return sqlite3RtreeInit(db);
163524}
163525#endif
163526
163527#endif
163528
163529/************** End of rtree.c ***********************************************/
163530/************** Begin file icu.c *********************************************/
163531/*
163532** 2007 May 6
163533**
163534** The author disclaims copyright to this source code.  In place of
163535** a legal notice, here is a blessing:
163536**
163537**    May you do good and not evil.
163538**    May you find forgiveness for yourself and forgive others.
163539**    May you share freely, never taking more than you give.
163540**
163541*************************************************************************
163542** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
163543**
163544** This file implements an integration between the ICU library
163545** ("International Components for Unicode", an open-source library
163546** for handling unicode data) and SQLite. The integration uses
163547** ICU to provide the following to SQLite:
163548**
163549**   * An implementation of the SQL regexp() function (and hence REGEXP
163550**     operator) using the ICU uregex_XX() APIs.
163551**
163552**   * Implementations of the SQL scalar upper() and lower() functions
163553**     for case mapping.
163554**
163555**   * Integration of ICU and SQLite collation sequences.
163556**
163557**   * An implementation of the LIKE operator that uses ICU to
163558**     provide case-independent matching.
163559*/
163560
163561#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
163562
163563/* Include ICU headers */
163564#include <unicode/utypes.h>
163565#include <unicode/uregex.h>
163566#include <unicode/ustring.h>
163567#include <unicode/ucol.h>
163568
163569/* #include <assert.h> */
163570
163571#ifndef SQLITE_CORE
163572/*   #include "sqlite3ext.h" */
163573  SQLITE_EXTENSION_INIT1
163574#else
163575/*   #include "sqlite3.h" */
163576#endif
163577
163578/*
163579** Maximum length (in bytes) of the pattern in a LIKE or GLOB
163580** operator.
163581*/
163582#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
163583# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
163584#endif
163585
163586/*
163587** Version of sqlite3_free() that is always a function, never a macro.
163588*/
163589static void xFree(void *p){
163590  sqlite3_free(p);
163591}
163592
163593/*
163594** This lookup table is used to help decode the first byte of
163595** a multi-byte UTF8 character. It is copied here from SQLite source
163596** code file utf8.c.
163597*/
163598static const unsigned char icuUtf8Trans1[] = {
163599  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163600  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
163601  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
163602  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
163603  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163604  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
163605  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163606  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
163607};
163608
163609#define SQLITE_ICU_READ_UTF8(zIn, c)                       \
163610  c = *(zIn++);                                            \
163611  if( c>=0xc0 ){                                           \
163612    c = icuUtf8Trans1[c-0xc0];                             \
163613    while( (*zIn & 0xc0)==0x80 ){                          \
163614      c = (c<<6) + (0x3f & *(zIn++));                      \
163615    }                                                      \
163616  }
163617
163618#define SQLITE_ICU_SKIP_UTF8(zIn)                          \
163619  assert( *zIn );                                          \
163620  if( *(zIn++)>=0xc0 ){                                    \
163621    while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
163622  }
163623
163624
163625/*
163626** Compare two UTF-8 strings for equality where the first string is
163627** a "LIKE" expression. Return true (1) if they are the same and
163628** false (0) if they are different.
163629*/
163630static int icuLikeCompare(
163631  const uint8_t *zPattern,   /* LIKE pattern */
163632  const uint8_t *zString,    /* The UTF-8 string to compare against */
163633  const UChar32 uEsc         /* The escape character */
163634){
163635  static const int MATCH_ONE = (UChar32)'_';
163636  static const int MATCH_ALL = (UChar32)'%';
163637
163638  int prevEscape = 0;     /* True if the previous character was uEsc */
163639
163640  while( 1 ){
163641
163642    /* Read (and consume) the next character from the input pattern. */
163643    UChar32 uPattern;
163644    SQLITE_ICU_READ_UTF8(zPattern, uPattern);
163645    if( uPattern==0 ) break;
163646
163647    /* There are now 4 possibilities:
163648    **
163649    **     1. uPattern is an unescaped match-all character "%",
163650    **     2. uPattern is an unescaped match-one character "_",
163651    **     3. uPattern is an unescaped escape character, or
163652    **     4. uPattern is to be handled as an ordinary character
163653    */
163654    if( !prevEscape && uPattern==MATCH_ALL ){
163655      /* Case 1. */
163656      uint8_t c;
163657
163658      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
163659      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
163660      ** test string.
163661      */
163662      while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
163663        if( c==MATCH_ONE ){
163664          if( *zString==0 ) return 0;
163665          SQLITE_ICU_SKIP_UTF8(zString);
163666        }
163667        zPattern++;
163668      }
163669
163670      if( *zPattern==0 ) return 1;
163671
163672      while( *zString ){
163673        if( icuLikeCompare(zPattern, zString, uEsc) ){
163674          return 1;
163675        }
163676        SQLITE_ICU_SKIP_UTF8(zString);
163677      }
163678      return 0;
163679
163680    }else if( !prevEscape && uPattern==MATCH_ONE ){
163681      /* Case 2. */
163682      if( *zString==0 ) return 0;
163683      SQLITE_ICU_SKIP_UTF8(zString);
163684
163685    }else if( !prevEscape && uPattern==uEsc){
163686      /* Case 3. */
163687      prevEscape = 1;
163688
163689    }else{
163690      /* Case 4. */
163691      UChar32 uString;
163692      SQLITE_ICU_READ_UTF8(zString, uString);
163693      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
163694      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
163695      if( uString!=uPattern ){
163696        return 0;
163697      }
163698      prevEscape = 0;
163699    }
163700  }
163701
163702  return *zString==0;
163703}
163704
163705/*
163706** Implementation of the like() SQL function.  This function implements
163707** the build-in LIKE operator.  The first argument to the function is the
163708** pattern and the second argument is the string.  So, the SQL statements:
163709**
163710**       A LIKE B
163711**
163712** is implemented as like(B, A). If there is an escape character E,
163713**
163714**       A LIKE B ESCAPE E
163715**
163716** is mapped to like(B, A, E).
163717*/
163718static void icuLikeFunc(
163719  sqlite3_context *context,
163720  int argc,
163721  sqlite3_value **argv
163722){
163723  const unsigned char *zA = sqlite3_value_text(argv[0]);
163724  const unsigned char *zB = sqlite3_value_text(argv[1]);
163725  UChar32 uEsc = 0;
163726
163727  /* Limit the length of the LIKE or GLOB pattern to avoid problems
163728  ** of deep recursion and N*N behavior in patternCompare().
163729  */
163730  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
163731    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
163732    return;
163733  }
163734
163735
163736  if( argc==3 ){
163737    /* The escape character string must consist of a single UTF-8 character.
163738    ** Otherwise, return an error.
163739    */
163740    int nE= sqlite3_value_bytes(argv[2]);
163741    const unsigned char *zE = sqlite3_value_text(argv[2]);
163742    int i = 0;
163743    if( zE==0 ) return;
163744    U8_NEXT(zE, i, nE, uEsc);
163745    if( i!=nE){
163746      sqlite3_result_error(context,
163747          "ESCAPE expression must be a single character", -1);
163748      return;
163749    }
163750  }
163751
163752  if( zA && zB ){
163753    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
163754  }
163755}
163756
163757/*
163758** This function is called when an ICU function called from within
163759** the implementation of an SQL scalar function returns an error.
163760**
163761** The scalar function context passed as the first argument is
163762** loaded with an error message based on the following two args.
163763*/
163764static void icuFunctionError(
163765  sqlite3_context *pCtx,       /* SQLite scalar function context */
163766  const char *zName,           /* Name of ICU function that failed */
163767  UErrorCode e                 /* Error code returned by ICU function */
163768){
163769  char zBuf[128];
163770  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
163771  zBuf[127] = '\0';
163772  sqlite3_result_error(pCtx, zBuf, -1);
163773}
163774
163775/*
163776** Function to delete compiled regexp objects. Registered as
163777** a destructor function with sqlite3_set_auxdata().
163778*/
163779static void icuRegexpDelete(void *p){
163780  URegularExpression *pExpr = (URegularExpression *)p;
163781  uregex_close(pExpr);
163782}
163783
163784/*
163785** Implementation of SQLite REGEXP operator. This scalar function takes
163786** two arguments. The first is a regular expression pattern to compile
163787** the second is a string to match against that pattern. If either
163788** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
163789** is 1 if the string matches the pattern, or 0 otherwise.
163790**
163791** SQLite maps the regexp() function to the regexp() operator such
163792** that the following two are equivalent:
163793**
163794**     zString REGEXP zPattern
163795**     regexp(zPattern, zString)
163796**
163797** Uses the following ICU regexp APIs:
163798**
163799**     uregex_open()
163800**     uregex_matches()
163801**     uregex_close()
163802*/
163803static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
163804  UErrorCode status = U_ZERO_ERROR;
163805  URegularExpression *pExpr;
163806  UBool res;
163807  const UChar *zString = sqlite3_value_text16(apArg[1]);
163808
163809  (void)nArg;  /* Unused parameter */
163810
163811  /* If the left hand side of the regexp operator is NULL,
163812  ** then the result is also NULL.
163813  */
163814  if( !zString ){
163815    return;
163816  }
163817
163818  pExpr = sqlite3_get_auxdata(p, 0);
163819  if( !pExpr ){
163820    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
163821    if( !zPattern ){
163822      return;
163823    }
163824    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
163825
163826    if( U_SUCCESS(status) ){
163827      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
163828    }else{
163829      assert(!pExpr);
163830      icuFunctionError(p, "uregex_open", status);
163831      return;
163832    }
163833  }
163834
163835  /* Configure the text that the regular expression operates on. */
163836  uregex_setText(pExpr, zString, -1, &status);
163837  if( !U_SUCCESS(status) ){
163838    icuFunctionError(p, "uregex_setText", status);
163839    return;
163840  }
163841
163842  /* Attempt the match */
163843  res = uregex_matches(pExpr, 0, &status);
163844  if( !U_SUCCESS(status) ){
163845    icuFunctionError(p, "uregex_matches", status);
163846    return;
163847  }
163848
163849  /* Set the text that the regular expression operates on to a NULL
163850  ** pointer. This is not really necessary, but it is tidier than
163851  ** leaving the regular expression object configured with an invalid
163852  ** pointer after this function returns.
163853  */
163854  uregex_setText(pExpr, 0, 0, &status);
163855
163856  /* Return 1 or 0. */
163857  sqlite3_result_int(p, res ? 1 : 0);
163858}
163859
163860/*
163861** Implementations of scalar functions for case mapping - upper() and
163862** lower(). Function upper() converts its input to upper-case (ABC).
163863** Function lower() converts to lower-case (abc).
163864**
163865** ICU provides two types of case mapping, "general" case mapping and
163866** "language specific". Refer to ICU documentation for the differences
163867** between the two.
163868**
163869** To utilise "general" case mapping, the upper() or lower() scalar
163870** functions are invoked with one argument:
163871**
163872**     upper('ABC') -> 'abc'
163873**     lower('abc') -> 'ABC'
163874**
163875** To access ICU "language specific" case mapping, upper() or lower()
163876** should be invoked with two arguments. The second argument is the name
163877** of the locale to use. Passing an empty string ("") or SQL NULL value
163878** as the second argument is the same as invoking the 1 argument version
163879** of upper() or lower().
163880**
163881**     lower('I', 'en_us') -> 'i'
163882**     lower('I', 'tr_tr') -> '��' (small dotless i)
163883**
163884** http://www.icu-project.org/userguide/posix.html#case_mappings
163885*/
163886static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
163887  const UChar *zInput;            /* Pointer to input string */
163888  UChar *zOutput = 0;             /* Pointer to output buffer */
163889  int nInput;                     /* Size of utf-16 input string in bytes */
163890  int nOut;                       /* Size of output buffer in bytes */
163891  int cnt;
163892  int bToUpper;                   /* True for toupper(), false for tolower() */
163893  UErrorCode status;
163894  const char *zLocale = 0;
163895
163896  assert(nArg==1 || nArg==2);
163897  bToUpper = (sqlite3_user_data(p)!=0);
163898  if( nArg==2 ){
163899    zLocale = (const char *)sqlite3_value_text(apArg[1]);
163900  }
163901
163902  zInput = sqlite3_value_text16(apArg[0]);
163903  if( !zInput ){
163904    return;
163905  }
163906  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
163907  if( nOut==0 ){
163908    sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
163909    return;
163910  }
163911
163912  for(cnt=0; cnt<2; cnt++){
163913    UChar *zNew = sqlite3_realloc(zOutput, nOut);
163914    if( zNew==0 ){
163915      sqlite3_free(zOutput);
163916      sqlite3_result_error_nomem(p);
163917      return;
163918    }
163919    zOutput = zNew;
163920    status = U_ZERO_ERROR;
163921    if( bToUpper ){
163922      nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
163923    }else{
163924      nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
163925    }
163926
163927    if( U_SUCCESS(status) ){
163928      sqlite3_result_text16(p, zOutput, nOut, xFree);
163929    }else if( status==U_BUFFER_OVERFLOW_ERROR ){
163930      assert( cnt==0 );
163931      continue;
163932    }else{
163933      icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
163934    }
163935    return;
163936  }
163937  assert( 0 );     /* Unreachable */
163938}
163939
163940/*
163941** Collation sequence destructor function. The pCtx argument points to
163942** a UCollator structure previously allocated using ucol_open().
163943*/
163944static void icuCollationDel(void *pCtx){
163945  UCollator *p = (UCollator *)pCtx;
163946  ucol_close(p);
163947}
163948
163949/*
163950** Collation sequence comparison function. The pCtx argument points to
163951** a UCollator structure previously allocated using ucol_open().
163952*/
163953static int icuCollationColl(
163954  void *pCtx,
163955  int nLeft,
163956  const void *zLeft,
163957  int nRight,
163958  const void *zRight
163959){
163960  UCollationResult res;
163961  UCollator *p = (UCollator *)pCtx;
163962  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
163963  switch( res ){
163964    case UCOL_LESS:    return -1;
163965    case UCOL_GREATER: return +1;
163966    case UCOL_EQUAL:   return 0;
163967  }
163968  assert(!"Unexpected return value from ucol_strcoll()");
163969  return 0;
163970}
163971
163972/*
163973** Implementation of the scalar function icu_load_collation().
163974**
163975** This scalar function is used to add ICU collation based collation
163976** types to an SQLite database connection. It is intended to be called
163977** as follows:
163978**
163979**     SELECT icu_load_collation(<locale>, <collation-name>);
163980**
163981** Where <locale> is a string containing an ICU locale identifier (i.e.
163982** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
163983** collation sequence to create.
163984*/
163985static void icuLoadCollation(
163986  sqlite3_context *p,
163987  int nArg,
163988  sqlite3_value **apArg
163989){
163990  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
163991  UErrorCode status = U_ZERO_ERROR;
163992  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
163993  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
163994  UCollator *pUCollator;    /* ICU library collation object */
163995  int rc;                   /* Return code from sqlite3_create_collation_x() */
163996
163997  assert(nArg==2);
163998  (void)nArg; /* Unused parameter */
163999  zLocale = (const char *)sqlite3_value_text(apArg[0]);
164000  zName = (const char *)sqlite3_value_text(apArg[1]);
164001
164002  if( !zLocale || !zName ){
164003    return;
164004  }
164005
164006  pUCollator = ucol_open(zLocale, &status);
164007  if( !U_SUCCESS(status) ){
164008    icuFunctionError(p, "ucol_open", status);
164009    return;
164010  }
164011  assert(p);
164012
164013  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
164014      icuCollationColl, icuCollationDel
164015  );
164016  if( rc!=SQLITE_OK ){
164017    ucol_close(pUCollator);
164018    sqlite3_result_error(p, "Error registering collation function", -1);
164019  }
164020}
164021
164022/*
164023** Register the ICU extension functions with database db.
164024*/
164025SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
164026  struct IcuScalar {
164027    const char *zName;                        /* Function name */
164028    int nArg;                                 /* Number of arguments */
164029    int enc;                                  /* Optimal text encoding */
164030    void *pContext;                           /* sqlite3_user_data() context */
164031    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
164032  } scalars[] = {
164033    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
164034
164035    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
164036    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
164037    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
164038    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
164039
164040    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
164041    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
164042    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
164043    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
164044
164045    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
164046    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
164047
164048    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
164049  };
164050
164051  int rc = SQLITE_OK;
164052  int i;
164053
164054  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
164055    struct IcuScalar *p = &scalars[i];
164056    rc = sqlite3_create_function(
164057        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
164058    );
164059  }
164060
164061  return rc;
164062}
164063
164064#if !SQLITE_CORE
164065#ifdef _WIN32
164066__declspec(dllexport)
164067#endif
164068SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
164069  sqlite3 *db,
164070  char **pzErrMsg,
164071  const sqlite3_api_routines *pApi
164072){
164073  SQLITE_EXTENSION_INIT2(pApi)
164074  return sqlite3IcuInit(db);
164075}
164076#endif
164077
164078#endif
164079
164080/************** End of icu.c *************************************************/
164081/************** Begin file fts3_icu.c ****************************************/
164082/*
164083** 2007 June 22
164084**
164085** The author disclaims copyright to this source code.  In place of
164086** a legal notice, here is a blessing:
164087**
164088**    May you do good and not evil.
164089**    May you find forgiveness for yourself and forgive others.
164090**    May you share freely, never taking more than you give.
164091**
164092*************************************************************************
164093** This file implements a tokenizer for fts3 based on the ICU library.
164094*/
164095/* #include "fts3Int.h" */
164096#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164097#ifdef SQLITE_ENABLE_ICU
164098
164099/* #include <assert.h> */
164100/* #include <string.h> */
164101/* #include "fts3_tokenizer.h" */
164102
164103#include <unicode/ubrk.h>
164104/* #include <unicode/ucol.h> */
164105/* #include <unicode/ustring.h> */
164106#include <unicode/utf16.h>
164107
164108typedef struct IcuTokenizer IcuTokenizer;
164109typedef struct IcuCursor IcuCursor;
164110
164111struct IcuTokenizer {
164112  sqlite3_tokenizer base;
164113  char *zLocale;
164114};
164115
164116struct IcuCursor {
164117  sqlite3_tokenizer_cursor base;
164118
164119  UBreakIterator *pIter;      /* ICU break-iterator object */
164120  int nChar;                  /* Number of UChar elements in pInput */
164121  UChar *aChar;               /* Copy of input using utf-16 encoding */
164122  int *aOffset;               /* Offsets of each character in utf-8 input */
164123
164124  int nBuffer;
164125  char *zBuffer;
164126
164127  int iToken;
164128};
164129
164130/*
164131** Create a new tokenizer instance.
164132*/
164133static int icuCreate(
164134  int argc,                            /* Number of entries in argv[] */
164135  const char * const *argv,            /* Tokenizer creation arguments */
164136  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
164137){
164138  IcuTokenizer *p;
164139  int n = 0;
164140
164141  if( argc>0 ){
164142    n = strlen(argv[0])+1;
164143  }
164144  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
164145  if( !p ){
164146    return SQLITE_NOMEM;
164147  }
164148  memset(p, 0, sizeof(IcuTokenizer));
164149
164150  if( n ){
164151    p->zLocale = (char *)&p[1];
164152    memcpy(p->zLocale, argv[0], n);
164153  }
164154
164155  *ppTokenizer = (sqlite3_tokenizer *)p;
164156
164157  return SQLITE_OK;
164158}
164159
164160/*
164161** Destroy a tokenizer
164162*/
164163static int icuDestroy(sqlite3_tokenizer *pTokenizer){
164164  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
164165  sqlite3_free(p);
164166  return SQLITE_OK;
164167}
164168
164169/*
164170** Prepare to begin tokenizing a particular string.  The input
164171** string to be tokenized is pInput[0..nBytes-1].  A cursor
164172** used to incrementally tokenize this string is returned in
164173** *ppCursor.
164174*/
164175static int icuOpen(
164176  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
164177  const char *zInput,                    /* Input string */
164178  int nInput,                            /* Length of zInput in bytes */
164179  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
164180){
164181  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
164182  IcuCursor *pCsr;
164183
164184  const int32_t opt = U_FOLD_CASE_DEFAULT;
164185  UErrorCode status = U_ZERO_ERROR;
164186  int nChar;
164187
164188  UChar32 c;
164189  int iInput = 0;
164190  int iOut = 0;
164191
164192  *ppCursor = 0;
164193
164194  if( zInput==0 ){
164195    nInput = 0;
164196    zInput = "";
164197  }else if( nInput<0 ){
164198    nInput = strlen(zInput);
164199  }
164200  nChar = nInput+1;
164201  pCsr = (IcuCursor *)sqlite3_malloc(
164202      sizeof(IcuCursor) +                /* IcuCursor */
164203      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
164204      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
164205  );
164206  if( !pCsr ){
164207    return SQLITE_NOMEM;
164208  }
164209  memset(pCsr, 0, sizeof(IcuCursor));
164210  pCsr->aChar = (UChar *)&pCsr[1];
164211  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
164212
164213  pCsr->aOffset[iOut] = iInput;
164214  U8_NEXT(zInput, iInput, nInput, c);
164215  while( c>0 ){
164216    int isError = 0;
164217    c = u_foldCase(c, opt);
164218    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
164219    if( isError ){
164220      sqlite3_free(pCsr);
164221      return SQLITE_ERROR;
164222    }
164223    pCsr->aOffset[iOut] = iInput;
164224
164225    if( iInput<nInput ){
164226      U8_NEXT(zInput, iInput, nInput, c);
164227    }else{
164228      c = 0;
164229    }
164230  }
164231
164232  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
164233  if( !U_SUCCESS(status) ){
164234    sqlite3_free(pCsr);
164235    return SQLITE_ERROR;
164236  }
164237  pCsr->nChar = iOut;
164238
164239  ubrk_first(pCsr->pIter);
164240  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
164241  return SQLITE_OK;
164242}
164243
164244/*
164245** Close a tokenization cursor previously opened by a call to icuOpen().
164246*/
164247static int icuClose(sqlite3_tokenizer_cursor *pCursor){
164248  IcuCursor *pCsr = (IcuCursor *)pCursor;
164249  ubrk_close(pCsr->pIter);
164250  sqlite3_free(pCsr->zBuffer);
164251  sqlite3_free(pCsr);
164252  return SQLITE_OK;
164253}
164254
164255/*
164256** Extract the next token from a tokenization cursor.
164257*/
164258static int icuNext(
164259  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
164260  const char **ppToken,               /* OUT: *ppToken is the token text */
164261  int *pnBytes,                       /* OUT: Number of bytes in token */
164262  int *piStartOffset,                 /* OUT: Starting offset of token */
164263  int *piEndOffset,                   /* OUT: Ending offset of token */
164264  int *piPosition                     /* OUT: Position integer of token */
164265){
164266  IcuCursor *pCsr = (IcuCursor *)pCursor;
164267
164268  int iStart = 0;
164269  int iEnd = 0;
164270  int nByte = 0;
164271
164272  while( iStart==iEnd ){
164273    UChar32 c;
164274
164275    iStart = ubrk_current(pCsr->pIter);
164276    iEnd = ubrk_next(pCsr->pIter);
164277    if( iEnd==UBRK_DONE ){
164278      return SQLITE_DONE;
164279    }
164280
164281    while( iStart<iEnd ){
164282      int iWhite = iStart;
164283      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
164284      if( u_isspace(c) ){
164285        iStart = iWhite;
164286      }else{
164287        break;
164288      }
164289    }
164290    assert(iStart<=iEnd);
164291  }
164292
164293  do {
164294    UErrorCode status = U_ZERO_ERROR;
164295    if( nByte ){
164296      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
164297      if( !zNew ){
164298        return SQLITE_NOMEM;
164299      }
164300      pCsr->zBuffer = zNew;
164301      pCsr->nBuffer = nByte;
164302    }
164303
164304    u_strToUTF8(
164305        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
164306        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
164307        &status                                  /* Output success/failure */
164308    );
164309  } while( nByte>pCsr->nBuffer );
164310
164311  *ppToken = pCsr->zBuffer;
164312  *pnBytes = nByte;
164313  *piStartOffset = pCsr->aOffset[iStart];
164314  *piEndOffset = pCsr->aOffset[iEnd];
164315  *piPosition = pCsr->iToken++;
164316
164317  return SQLITE_OK;
164318}
164319
164320/*
164321** The set of routines that implement the simple tokenizer
164322*/
164323static const sqlite3_tokenizer_module icuTokenizerModule = {
164324  0,                           /* iVersion    */
164325  icuCreate,                   /* xCreate     */
164326  icuDestroy,                  /* xCreate     */
164327  icuOpen,                     /* xOpen       */
164328  icuClose,                    /* xClose      */
164329  icuNext,                     /* xNext       */
164330  0,                           /* xLanguageid */
164331};
164332
164333/*
164334** Set *ppModule to point at the implementation of the ICU tokenizer.
164335*/
164336SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
164337  sqlite3_tokenizer_module const**ppModule
164338){
164339  *ppModule = &icuTokenizerModule;
164340}
164341
164342#endif /* defined(SQLITE_ENABLE_ICU) */
164343#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
164344
164345/************** End of fts3_icu.c ********************************************/
164346/************** Begin file sqlite3rbu.c **************************************/
164347/*
164348** 2014 August 30
164349**
164350** The author disclaims copyright to this source code.  In place of
164351** a legal notice, here is a blessing:
164352**
164353**    May you do good and not evil.
164354**    May you find forgiveness for yourself and forgive others.
164355**    May you share freely, never taking more than you give.
164356**
164357*************************************************************************
164358**
164359**
164360** OVERVIEW
164361**
164362**  The RBU extension requires that the RBU update be packaged as an
164363**  SQLite database. The tables it expects to find are described in
164364**  sqlite3rbu.h.  Essentially, for each table xyz in the target database
164365**  that the user wishes to write to, a corresponding data_xyz table is
164366**  created in the RBU database and populated with one row for each row to
164367**  update, insert or delete from the target table.
164368**
164369**  The update proceeds in three stages:
164370**
164371**  1) The database is updated. The modified database pages are written
164372**     to a *-oal file. A *-oal file is just like a *-wal file, except
164373**     that it is named "<database>-oal" instead of "<database>-wal".
164374**     Because regular SQLite clients do not look for file named
164375**     "<database>-oal", they go on using the original database in
164376**     rollback mode while the *-oal file is being generated.
164377**
164378**     During this stage RBU does not update the database by writing
164379**     directly to the target tables. Instead it creates "imposter"
164380**     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
164381**     to update each b-tree individually. All updates required by each
164382**     b-tree are completed before moving on to the next, and all
164383**     updates are done in sorted key order.
164384**
164385**  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
164386**     location using a call to rename(2). Before doing this the RBU
164387**     module takes an EXCLUSIVE lock on the database file, ensuring
164388**     that there are no other active readers.
164389**
164390**     Once the EXCLUSIVE lock is released, any other database readers
164391**     detect the new *-wal file and read the database in wal mode. At
164392**     this point they see the new version of the database - including
164393**     the updates made as part of the RBU update.
164394**
164395**  3) The new *-wal file is checkpointed. This proceeds in the same way
164396**     as a regular database checkpoint, except that a single frame is
164397**     checkpointed each time sqlite3rbu_step() is called. If the RBU
164398**     handle is closed before the entire *-wal file is checkpointed,
164399**     the checkpoint progress is saved in the RBU database and the
164400**     checkpoint can be resumed by another RBU client at some point in
164401**     the future.
164402**
164403** POTENTIAL PROBLEMS
164404**
164405**  The rename() call might not be portable. And RBU is not currently
164406**  syncing the directory after renaming the file.
164407**
164408**  When state is saved, any commit to the *-oal file and the commit to
164409**  the RBU update database are not atomic. So if the power fails at the
164410**  wrong moment they might get out of sync. As the main database will be
164411**  committed before the RBU update database this will likely either just
164412**  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
164413**  constraint violations).
164414**
164415**  If some client does modify the target database mid RBU update, or some
164416**  other error occurs, the RBU extension will keep throwing errors. It's
164417**  not really clear how to get out of this state. The system could just
164418**  by delete the RBU update database and *-oal file and have the device
164419**  download the update again and start over.
164420**
164421**  At present, for an UPDATE, both the new.* and old.* records are
164422**  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
164423**  fields are collected.  This means we're probably writing a lot more
164424**  data to disk when saving the state of an ongoing update to the RBU
164425**  update database than is strictly necessary.
164426**
164427*/
164428
164429/* #include <assert.h> */
164430/* #include <string.h> */
164431/* #include <stdio.h> */
164432
164433/* #include "sqlite3.h" */
164434
164435#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
164436/************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
164437/************** Begin file sqlite3rbu.h **************************************/
164438/*
164439** 2014 August 30
164440**
164441** The author disclaims copyright to this source code.  In place of
164442** a legal notice, here is a blessing:
164443**
164444**    May you do good and not evil.
164445**    May you find forgiveness for yourself and forgive others.
164446**    May you share freely, never taking more than you give.
164447**
164448*************************************************************************
164449**
164450** This file contains the public interface for the RBU extension.
164451*/
164452
164453/*
164454** SUMMARY
164455**
164456** Writing a transaction containing a large number of operations on
164457** b-tree indexes that are collectively larger than the available cache
164458** memory can be very inefficient.
164459**
164460** The problem is that in order to update a b-tree, the leaf page (at least)
164461** containing the entry being inserted or deleted must be modified. If the
164462** working set of leaves is larger than the available cache memory, then a
164463** single leaf that is modified more than once as part of the transaction
164464** may be loaded from or written to the persistent media multiple times.
164465** Additionally, because the index updates are likely to be applied in
164466** random order, access to pages within the database is also likely to be in
164467** random order, which is itself quite inefficient.
164468**
164469** One way to improve the situation is to sort the operations on each index
164470** by index key before applying them to the b-tree. This leads to an IO
164471** pattern that resembles a single linear scan through the index b-tree,
164472** and all but guarantees each modified leaf page is loaded and stored
164473** exactly once. SQLite uses this trick to improve the performance of
164474** CREATE INDEX commands. This extension allows it to be used to improve
164475** the performance of large transactions on existing databases.
164476**
164477** Additionally, this extension allows the work involved in writing the
164478** large transaction to be broken down into sub-transactions performed
164479** sequentially by separate processes. This is useful if the system cannot
164480** guarantee that a single update process will run for long enough to apply
164481** the entire update, for example because the update is being applied on a
164482** mobile device that is frequently rebooted. Even after the writer process
164483** has committed one or more sub-transactions, other database clients continue
164484** to read from the original database snapshot. In other words, partially
164485** applied transactions are not visible to other clients.
164486**
164487** "RBU" stands for "Resumable Bulk Update". As in a large database update
164488** transmitted via a wireless network to a mobile device. A transaction
164489** applied using this extension is hence refered to as an "RBU update".
164490**
164491**
164492** LIMITATIONS
164493**
164494** An "RBU update" transaction is subject to the following limitations:
164495**
164496**   * The transaction must consist of INSERT, UPDATE and DELETE operations
164497**     only.
164498**
164499**   * INSERT statements may not use any default values.
164500**
164501**   * UPDATE and DELETE statements must identify their target rows by
164502**     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
164503**     KEY fields may not be updated or deleted. If the table being written
164504**     has no PRIMARY KEY, affected rows must be identified by rowid.
164505**
164506**   * UPDATE statements may not modify PRIMARY KEY columns.
164507**
164508**   * No triggers will be fired.
164509**
164510**   * No foreign key violations are detected or reported.
164511**
164512**   * CHECK constraints are not enforced.
164513**
164514**   * No constraint handling mode except for "OR ROLLBACK" is supported.
164515**
164516**
164517** PREPARATION
164518**
164519** An "RBU update" is stored as a separate SQLite database. A database
164520** containing an RBU update is an "RBU database". For each table in the
164521** target database to be updated, the RBU database should contain a table
164522** named "data_<target name>" containing the same set of columns as the
164523** target table, and one more - "rbu_control". The data_% table should
164524** have no PRIMARY KEY or UNIQUE constraints, but each column should have
164525** the same type as the corresponding column in the target database.
164526** The "rbu_control" column should have no type at all. For example, if
164527** the target database contains:
164528**
164529**   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
164530**
164531** Then the RBU database should contain:
164532**
164533**   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
164534**
164535** The order of the columns in the data_% table does not matter.
164536**
164537** Instead of a regular table, the RBU database may also contain virtual
164538** tables or view named using the data_<target> naming scheme.
164539**
164540** Instead of the plain data_<target> naming scheme, RBU database tables
164541** may also be named data<integer>_<target>, where <integer> is any sequence
164542** of zero or more numeric characters (0-9). This can be significant because
164543** tables within the RBU database are always processed in order sorted by
164544** name. By judicious selection of the the <integer> portion of the names
164545** of the RBU tables the user can therefore control the order in which they
164546** are processed. This can be useful, for example, to ensure that "external
164547** content" FTS4 tables are updated before their underlying content tables.
164548**
164549** If the target database table is a virtual table or a table that has no
164550** PRIMARY KEY declaration, the data_% table must also contain a column
164551** named "rbu_rowid". This column is mapped to the tables implicit primary
164552** key column - "rowid". Virtual tables for which the "rowid" column does
164553** not function like a primary key value cannot be updated using RBU. For
164554** example, if the target db contains either of the following:
164555**
164556**   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
164557**   CREATE TABLE x1(a, b)
164558**
164559** then the RBU database should contain:
164560**
164561**   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
164562**
164563** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
164564** target table must be present in the input table. For virtual tables,
164565** hidden columns are optional - they are updated by RBU if present in
164566** the input table, or not otherwise. For example, to write to an fts4
164567** table with a hidden languageid column such as:
164568**
164569**   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
164570**
164571** Either of the following input table schemas may be used:
164572**
164573**   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
164574**   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
164575**
164576** For each row to INSERT into the target database as part of the RBU
164577** update, the corresponding data_% table should contain a single record
164578** with the "rbu_control" column set to contain integer value 0. The
164579** other columns should be set to the values that make up the new record
164580** to insert.
164581**
164582** If the target database table has an INTEGER PRIMARY KEY, it is not
164583** possible to insert a NULL value into the IPK column. Attempting to
164584** do so results in an SQLITE_MISMATCH error.
164585**
164586** For each row to DELETE from the target database as part of the RBU
164587** update, the corresponding data_% table should contain a single record
164588** with the "rbu_control" column set to contain integer value 1. The
164589** real primary key values of the row to delete should be stored in the
164590** corresponding columns of the data_% table. The values stored in the
164591** other columns are not used.
164592**
164593** For each row to UPDATE from the target database as part of the RBU
164594** update, the corresponding data_% table should contain a single record
164595** with the "rbu_control" column set to contain a value of type text.
164596** The real primary key values identifying the row to update should be
164597** stored in the corresponding columns of the data_% table row, as should
164598** the new values of all columns being update. The text value in the
164599** "rbu_control" column must contain the same number of characters as
164600** there are columns in the target database table, and must consist entirely
164601** of 'x' and '.' characters (or in some special cases 'd' - see below). For
164602** each column that is being updated, the corresponding character is set to
164603** 'x'. For those that remain as they are, the corresponding character of the
164604** rbu_control value should be set to '.'. For example, given the tables
164605** above, the update statement:
164606**
164607**   UPDATE t1 SET c = 'usa' WHERE a = 4;
164608**
164609** is represented by the data_t1 row created by:
164610**
164611**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
164612**
164613** Instead of an 'x' character, characters of the rbu_control value specified
164614** for UPDATEs may also be set to 'd'. In this case, instead of updating the
164615** target table with the value stored in the corresponding data_% column, the
164616** user-defined SQL function "rbu_delta()" is invoked and the result stored in
164617** the target table column. rbu_delta() is invoked with two arguments - the
164618** original value currently stored in the target table column and the
164619** value specified in the data_xxx table.
164620**
164621** For example, this row:
164622**
164623**   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
164624**
164625** is similar to an UPDATE statement such as:
164626**
164627**   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
164628**
164629** Finally, if an 'f' character appears in place of a 'd' or 's' in an
164630** ota_control string, the contents of the data_xxx table column is assumed
164631** to be a "fossil delta" - a patch to be applied to a blob value in the
164632** format used by the fossil source-code management system. In this case
164633** the existing value within the target database table must be of type BLOB.
164634** It is replaced by the result of applying the specified fossil delta to
164635** itself.
164636**
164637** If the target database table is a virtual table or a table with no PRIMARY
164638** KEY, the rbu_control value should not include a character corresponding
164639** to the rbu_rowid value. For example, this:
164640**
164641**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
164642**       VALUES(NULL, 'usa', 12, '.x');
164643**
164644** causes a result similar to:
164645**
164646**   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
164647**
164648** The data_xxx tables themselves should have no PRIMARY KEY declarations.
164649** However, RBU is more efficient if reading the rows in from each data_xxx
164650** table in "rowid" order is roughly the same as reading them sorted by
164651** the PRIMARY KEY of the corresponding target database table. In other
164652** words, rows should be sorted using the destination table PRIMARY KEY
164653** fields before they are inserted into the data_xxx tables.
164654**
164655** USAGE
164656**
164657** The API declared below allows an application to apply an RBU update
164658** stored on disk to an existing target database. Essentially, the
164659** application:
164660**
164661**     1) Opens an RBU handle using the sqlite3rbu_open() function.
164662**
164663**     2) Registers any required virtual table modules with the database
164664**        handle returned by sqlite3rbu_db(). Also, if required, register
164665**        the rbu_delta() implementation.
164666**
164667**     3) Calls the sqlite3rbu_step() function one or more times on
164668**        the new handle. Each call to sqlite3rbu_step() performs a single
164669**        b-tree operation, so thousands of calls may be required to apply
164670**        a complete update.
164671**
164672**     4) Calls sqlite3rbu_close() to close the RBU update handle. If
164673**        sqlite3rbu_step() has been called enough times to completely
164674**        apply the update to the target database, then the RBU database
164675**        is marked as fully applied. Otherwise, the state of the RBU
164676**        update application is saved in the RBU database for later
164677**        resumption.
164678**
164679** See comments below for more detail on APIs.
164680**
164681** If an update is only partially applied to the target database by the
164682** time sqlite3rbu_close() is called, various state information is saved
164683** within the RBU database. This allows subsequent processes to automatically
164684** resume the RBU update from where it left off.
164685**
164686** To remove all RBU extension state information, returning an RBU database
164687** to its original contents, it is sufficient to drop all tables that begin
164688** with the prefix "rbu_"
164689**
164690** DATABASE LOCKING
164691**
164692** An RBU update may not be applied to a database in WAL mode. Attempting
164693** to do so is an error (SQLITE_ERROR).
164694**
164695** While an RBU handle is open, a SHARED lock may be held on the target
164696** database file. This means it is possible for other clients to read the
164697** database, but not to write it.
164698**
164699** If an RBU update is started and then suspended before it is completed,
164700** then an external client writes to the database, then attempting to resume
164701** the suspended RBU update is also an error (SQLITE_BUSY).
164702*/
164703
164704#ifndef _SQLITE3RBU_H
164705#define _SQLITE3RBU_H
164706
164707/* #include "sqlite3.h"              ** Required for error code definitions ** */
164708
164709#if 0
164710extern "C" {
164711#endif
164712
164713typedef struct sqlite3rbu sqlite3rbu;
164714
164715/*
164716** Open an RBU handle.
164717**
164718** Argument zTarget is the path to the target database. Argument zRbu is
164719** the path to the RBU database. Each call to this function must be matched
164720** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
164721** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
164722** or zRbu begin with "file:", it will be interpreted as an SQLite
164723** database URI, not a regular file name.
164724**
164725** If the zState argument is passed a NULL value, the RBU extension stores
164726** the current state of the update (how many rows have been updated, which
164727** indexes are yet to be updated etc.) within the RBU database itself. This
164728** can be convenient, as it means that the RBU application does not need to
164729** organize removing a separate state file after the update is concluded.
164730** Or, if zState is non-NULL, it must be a path to a database file in which
164731** the RBU extension can store the state of the update.
164732**
164733** When resuming an RBU update, the zState argument must be passed the same
164734** value as when the RBU update was started.
164735**
164736** Once the RBU update is finished, the RBU extension does not
164737** automatically remove any zState database file, even if it created it.
164738**
164739** By default, RBU uses the default VFS to access the files on disk. To
164740** use a VFS other than the default, an SQLite "file:" URI containing a
164741** "vfs=..." option may be passed as the zTarget option.
164742**
164743** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
164744** SQLite's built-in VFSs, including the multiplexor VFS. However it does
164745** not work out of the box with zipvfs. Refer to the comment describing
164746** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
164747*/
164748SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
164749  const char *zTarget,
164750  const char *zRbu,
164751  const char *zState
164752);
164753
164754/*
164755** Open an RBU handle to perform an RBU vacuum on database file zTarget.
164756** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
164757** that it can be suspended and resumed like an RBU update.
164758**
164759** The second argument to this function, which may not be NULL, identifies
164760** a database in which to store the state of the RBU vacuum operation if
164761** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
164762** an RBU vacuum operation, the state database should either not exist or
164763** be empty (contain no tables). If an RBU vacuum is suspended by calling
164764** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
164765** returned SQLITE_DONE, the vacuum state is stored in the state database.
164766** The vacuum can be resumed by calling this function to open a new RBU
164767** handle specifying the same target and state databases.
164768**
164769** This function does not delete the state database after an RBU vacuum
164770** is completed, even if it created it. However, if the call to
164771** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
164772** of the state tables within the state database are zeroed. This way,
164773** the next call to sqlite3rbu_vacuum() opens a handle that starts a
164774** new RBU vacuum operation.
164775**
164776** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
164777** describing the sqlite3rbu_create_vfs() API function below for
164778** a description of the complications associated with using RBU with
164779** zipvfs databases.
164780*/
164781SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
164782  const char *zTarget,
164783  const char *zState
164784);
164785
164786/*
164787** Internally, each RBU connection uses a separate SQLite database
164788** connection to access the target and rbu update databases. This
164789** API allows the application direct access to these database handles.
164790**
164791** The first argument passed to this function must be a valid, open, RBU
164792** handle. The second argument should be passed zero to access the target
164793** database handle, or non-zero to access the rbu update database handle.
164794** Accessing the underlying database handles may be useful in the
164795** following scenarios:
164796**
164797**   * If any target tables are virtual tables, it may be necessary to
164798**     call sqlite3_create_module() on the target database handle to
164799**     register the required virtual table implementations.
164800**
164801**   * If the data_xxx tables in the RBU source database are virtual
164802**     tables, the application may need to call sqlite3_create_module() on
164803**     the rbu update db handle to any required virtual table
164804**     implementations.
164805**
164806**   * If the application uses the "rbu_delta()" feature described above,
164807**     it must use sqlite3_create_function() or similar to register the
164808**     rbu_delta() implementation with the target database handle.
164809**
164810** If an error has occurred, either while opening or stepping the RBU object,
164811** this function may return NULL. The error code and message may be collected
164812** when sqlite3rbu_close() is called.
164813**
164814** Database handles returned by this function remain valid until the next
164815** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
164816*/
164817SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
164818
164819/*
164820** Do some work towards applying the RBU update to the target db.
164821**
164822** Return SQLITE_DONE if the update has been completely applied, or
164823** SQLITE_OK if no error occurs but there remains work to do to apply
164824** the RBU update. If an error does occur, some other error code is
164825** returned.
164826**
164827** Once a call to sqlite3rbu_step() has returned a value other than
164828** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
164829** that immediately return the same value.
164830*/
164831SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
164832
164833/*
164834** Force RBU to save its state to disk.
164835**
164836** If a power failure or application crash occurs during an update, following
164837** system recovery RBU may resume the update from the point at which the state
164838** was last saved. In other words, from the most recent successful call to
164839** sqlite3rbu_close() or this function.
164840**
164841** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
164842*/
164843SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
164844
164845/*
164846** Close an RBU handle.
164847**
164848** If the RBU update has been completely applied, mark the RBU database
164849** as fully applied. Otherwise, assuming no error has occurred, save the
164850** current state of the RBU update appliation to the RBU database.
164851**
164852** If an error has already occurred as part of an sqlite3rbu_step()
164853** or sqlite3rbu_open() call, or if one occurs within this function, an
164854** SQLite error code is returned. Additionally, *pzErrmsg may be set to
164855** point to a buffer containing a utf-8 formatted English language error
164856** message. It is the responsibility of the caller to eventually free any
164857** such buffer using sqlite3_free().
164858**
164859** Otherwise, if no error occurs, this function returns SQLITE_OK if the
164860** update has been partially applied, or SQLITE_DONE if it has been
164861** completely applied.
164862*/
164863SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
164864
164865/*
164866** Return the total number of key-value operations (inserts, deletes or
164867** updates) that have been performed on the target database since the
164868** current RBU update was started.
164869*/
164870SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
164871
164872/*
164873** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
164874** progress indications for the two stages of an RBU update. This API may
164875** be useful for driving GUI progress indicators and similar.
164876**
164877** An RBU update is divided into two stages:
164878**
164879**   * Stage 1, in which changes are accumulated in an oal/wal file, and
164880**   * Stage 2, in which the contents of the wal file are copied into the
164881**     main database.
164882**
164883** The update is visible to non-RBU clients during stage 2. During stage 1
164884** non-RBU reader clients may see the original database.
164885**
164886** If this API is called during stage 2 of the update, output variable
164887** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
164888** to a value between 0 and 10000 to indicate the permyriadage progress of
164889** stage 2. A value of 5000 indicates that stage 2 is half finished,
164890** 9000 indicates that it is 90% finished, and so on.
164891**
164892** If this API is called during stage 1 of the update, output variable
164893** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
164894** value to which (*pnOne) is set depends on whether or not the RBU
164895** database contains an "rbu_count" table. The rbu_count table, if it
164896** exists, must contain the same columns as the following:
164897**
164898**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
164899**
164900** There must be one row in the table for each source (data_xxx) table within
164901** the RBU database. The 'tbl' column should contain the name of the source
164902** table. The 'cnt' column should contain the number of rows within the
164903** source table.
164904**
164905** If the rbu_count table is present and populated correctly and this
164906** API is called during stage 1, the *pnOne output variable is set to the
164907** permyriadage progress of the same stage. If the rbu_count table does
164908** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
164909** table exists but is not correctly populated, the value of the *pnOne
164910** output variable during stage 1 is undefined.
164911*/
164912SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
164913
164914/*
164915** Obtain an indication as to the current stage of an RBU update or vacuum.
164916** This function always returns one of the SQLITE_RBU_STATE_XXX constants
164917** defined in this file. Return values should be interpreted as follows:
164918**
164919** SQLITE_RBU_STATE_OAL:
164920**   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
164921**   may either add further data to the *-oal file, or compute data that will
164922**   be added by a subsequent call.
164923**
164924** SQLITE_RBU_STATE_MOVE:
164925**   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
164926**   will move the *-oal file to the equivalent *-wal path. If the current
164927**   operation is an RBU update, then the updated version of the database
164928**   file will become visible to ordinary SQLite clients following the next
164929**   call to sqlite3rbu_step().
164930**
164931** SQLITE_RBU_STATE_CHECKPOINT:
164932**   RBU is currently performing an incremental checkpoint. The next call to
164933**   sqlite3rbu_step() will copy a page of data from the *-wal file into
164934**   the target database file.
164935**
164936** SQLITE_RBU_STATE_DONE:
164937**   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
164938**   will immediately return SQLITE_DONE.
164939**
164940** SQLITE_RBU_STATE_ERROR:
164941**   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
164942**   immediately return the SQLite error code associated with the error.
164943*/
164944#define SQLITE_RBU_STATE_OAL        1
164945#define SQLITE_RBU_STATE_MOVE       2
164946#define SQLITE_RBU_STATE_CHECKPOINT 3
164947#define SQLITE_RBU_STATE_DONE       4
164948#define SQLITE_RBU_STATE_ERROR      5
164949
164950SQLITE_API int SQLITE_STDCALL sqlite3rbu_state(sqlite3rbu *pRbu);
164951
164952/*
164953** Create an RBU VFS named zName that accesses the underlying file-system
164954** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
164955** then the new RBU VFS uses the default system VFS to access the file-system.
164956** The new object is registered as a non-default VFS with SQLite before
164957** returning.
164958**
164959** Part of the RBU implementation uses a custom VFS object. Usually, this
164960** object is created and deleted automatically by RBU.
164961**
164962** The exception is for applications that also use zipvfs. In this case,
164963** the custom VFS must be explicitly created by the user before the RBU
164964** handle is opened. The RBU VFS should be installed so that the zipvfs
164965** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
164966** (for example multiplexor) to access the file-system. For example,
164967** to assemble an RBU enabled VFS stack that uses both zipvfs and
164968** multiplexor (error checking omitted):
164969**
164970**     // Create a VFS named "multiplex" (not the default).
164971**     sqlite3_multiplex_initialize(0, 0);
164972**
164973**     // Create an rbu VFS named "rbu" that uses multiplexor. If the
164974**     // second argument were replaced with NULL, the "rbu" VFS would
164975**     // access the file-system via the system default VFS, bypassing the
164976**     // multiplexor.
164977**     sqlite3rbu_create_vfs("rbu", "multiplex");
164978**
164979**     // Create a zipvfs VFS named "zipvfs" that uses rbu.
164980**     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
164981**
164982**     // Make zipvfs the default VFS.
164983**     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
164984**
164985** Because the default VFS created above includes a RBU functionality, it
164986** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
164987** that does not include the RBU layer results in an error.
164988**
164989** The overhead of adding the "rbu" VFS to the system is negligible for
164990** non-RBU users. There is no harm in an application accessing the
164991** file-system via "rbu" all the time, even if it only uses RBU functionality
164992** occasionally.
164993*/
164994SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
164995
164996/*
164997** Deregister and destroy an RBU vfs created by an earlier call to
164998** sqlite3rbu_create_vfs().
164999**
165000** VFS objects are not reference counted. If a VFS object is destroyed
165001** before all database handles that use it have been closed, the results
165002** are undefined.
165003*/
165004SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
165005
165006#if 0
165007}  /* end of the 'extern "C"' block */
165008#endif
165009
165010#endif /* _SQLITE3RBU_H */
165011
165012/************** End of sqlite3rbu.h ******************************************/
165013/************** Continuing where we left off in sqlite3rbu.c *****************/
165014
165015#if defined(_WIN32_WCE)
165016/* #include "windows.h" */
165017#endif
165018
165019/* Maximum number of prepared UPDATE statements held by this module */
165020#define SQLITE_RBU_UPDATE_CACHESIZE 16
165021
165022/*
165023** Swap two objects of type TYPE.
165024*/
165025#if !defined(SQLITE_AMALGAMATION)
165026# define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
165027#endif
165028
165029/*
165030** The rbu_state table is used to save the state of a partially applied
165031** update so that it can be resumed later. The table consists of integer
165032** keys mapped to values as follows:
165033**
165034** RBU_STATE_STAGE:
165035**   May be set to integer values 1, 2, 4 or 5. As follows:
165036**       1: the *-rbu file is currently under construction.
165037**       2: the *-rbu file has been constructed, but not yet moved
165038**          to the *-wal path.
165039**       4: the checkpoint is underway.
165040**       5: the rbu update has been checkpointed.
165041**
165042** RBU_STATE_TBL:
165043**   Only valid if STAGE==1. The target database name of the table
165044**   currently being written.
165045**
165046** RBU_STATE_IDX:
165047**   Only valid if STAGE==1. The target database name of the index
165048**   currently being written, or NULL if the main table is currently being
165049**   updated.
165050**
165051** RBU_STATE_ROW:
165052**   Only valid if STAGE==1. Number of rows already processed for the current
165053**   table/index.
165054**
165055** RBU_STATE_PROGRESS:
165056**   Trbul number of sqlite3rbu_step() calls made so far as part of this
165057**   rbu update.
165058**
165059** RBU_STATE_CKPT:
165060**   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
165061**   header created by recovering the *-wal file. This is used to detect
165062**   cases when another client appends frames to the *-wal file in the
165063**   middle of an incremental checkpoint (an incremental checkpoint cannot
165064**   be continued if this happens).
165065**
165066** RBU_STATE_COOKIE:
165067**   Valid if STAGE==1. The current change-counter cookie value in the
165068**   target db file.
165069**
165070** RBU_STATE_OALSZ:
165071**   Valid if STAGE==1. The size in bytes of the *-oal file.
165072*/
165073#define RBU_STATE_STAGE        1
165074#define RBU_STATE_TBL          2
165075#define RBU_STATE_IDX          3
165076#define RBU_STATE_ROW          4
165077#define RBU_STATE_PROGRESS     5
165078#define RBU_STATE_CKPT         6
165079#define RBU_STATE_COOKIE       7
165080#define RBU_STATE_OALSZ        8
165081#define RBU_STATE_PHASEONESTEP 9
165082
165083#define RBU_STAGE_OAL         1
165084#define RBU_STAGE_MOVE        2
165085#define RBU_STAGE_CAPTURE     3
165086#define RBU_STAGE_CKPT        4
165087#define RBU_STAGE_DONE        5
165088
165089
165090#define RBU_CREATE_STATE \
165091  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
165092
165093typedef struct RbuFrame RbuFrame;
165094typedef struct RbuObjIter RbuObjIter;
165095typedef struct RbuState RbuState;
165096typedef struct rbu_vfs rbu_vfs;
165097typedef struct rbu_file rbu_file;
165098typedef struct RbuUpdateStmt RbuUpdateStmt;
165099
165100#if !defined(SQLITE_AMALGAMATION)
165101typedef unsigned int u32;
165102typedef unsigned short u16;
165103typedef unsigned char u8;
165104typedef sqlite3_int64 i64;
165105#endif
165106
165107/*
165108** These values must match the values defined in wal.c for the equivalent
165109** locks. These are not magic numbers as they are part of the SQLite file
165110** format.
165111*/
165112#define WAL_LOCK_WRITE  0
165113#define WAL_LOCK_CKPT   1
165114#define WAL_LOCK_READ0  3
165115
165116#define SQLITE_FCNTL_RBUCNT    5149216
165117
165118/*
165119** A structure to store values read from the rbu_state table in memory.
165120*/
165121struct RbuState {
165122  int eStage;
165123  char *zTbl;
165124  char *zIdx;
165125  i64 iWalCksum;
165126  int nRow;
165127  i64 nProgress;
165128  u32 iCookie;
165129  i64 iOalSz;
165130  i64 nPhaseOneStep;
165131};
165132
165133struct RbuUpdateStmt {
165134  char *zMask;                    /* Copy of update mask used with pUpdate */
165135  sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
165136  RbuUpdateStmt *pNext;
165137};
165138
165139/*
165140** An iterator of this type is used to iterate through all objects in
165141** the target database that require updating. For each such table, the
165142** iterator visits, in order:
165143**
165144**     * the table itself,
165145**     * each index of the table (zero or more points to visit), and
165146**     * a special "cleanup table" state.
165147**
165148** abIndexed:
165149**   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
165150**   it points to an array of flags nTblCol elements in size. The flag is
165151**   set for each column that is either a part of the PK or a part of an
165152**   index. Or clear otherwise.
165153**
165154*/
165155struct RbuObjIter {
165156  sqlite3_stmt *pTblIter;         /* Iterate through tables */
165157  sqlite3_stmt *pIdxIter;         /* Index iterator */
165158  int nTblCol;                    /* Size of azTblCol[] array */
165159  char **azTblCol;                /* Array of unquoted target column names */
165160  char **azTblType;               /* Array of target column types */
165161  int *aiSrcOrder;                /* src table col -> target table col */
165162  u8 *abTblPk;                    /* Array of flags, set on target PK columns */
165163  u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
165164  u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
165165  int eType;                      /* Table type - an RBU_PK_XXX value */
165166
165167  /* Output variables. zTbl==0 implies EOF. */
165168  int bCleanup;                   /* True in "cleanup" state */
165169  const char *zTbl;               /* Name of target db table */
165170  const char *zDataTbl;           /* Name of rbu db table (or null) */
165171  const char *zIdx;               /* Name of target db index (or null) */
165172  int iTnum;                      /* Root page of current object */
165173  int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
165174  int bUnique;                    /* Current index is unique */
165175  int nIndex;                     /* Number of aux. indexes on table zTbl */
165176
165177  /* Statements created by rbuObjIterPrepareAll() */
165178  int nCol;                       /* Number of columns in current object */
165179  sqlite3_stmt *pSelect;          /* Source data */
165180  sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
165181  sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
165182  sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
165183
165184  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
165185  RbuUpdateStmt *pRbuUpdate;
165186};
165187
165188/*
165189** Values for RbuObjIter.eType
165190**
165191**     0: Table does not exist (error)
165192**     1: Table has an implicit rowid.
165193**     2: Table has an explicit IPK column.
165194**     3: Table has an external PK index.
165195**     4: Table is WITHOUT ROWID.
165196**     5: Table is a virtual table.
165197*/
165198#define RBU_PK_NOTABLE        0
165199#define RBU_PK_NONE           1
165200#define RBU_PK_IPK            2
165201#define RBU_PK_EXTERNAL       3
165202#define RBU_PK_WITHOUT_ROWID  4
165203#define RBU_PK_VTAB           5
165204
165205
165206/*
165207** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
165208** one of the following operations.
165209*/
165210#define RBU_INSERT     1          /* Insert on a main table b-tree */
165211#define RBU_DELETE     2          /* Delete a row from a main table b-tree */
165212#define RBU_REPLACE    3          /* Delete and then insert a row */
165213#define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
165214#define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
165215
165216#define RBU_UPDATE     6          /* Update a row in a main table b-tree */
165217
165218/*
165219** A single step of an incremental checkpoint - frame iWalFrame of the wal
165220** file should be copied to page iDbPage of the database file.
165221*/
165222struct RbuFrame {
165223  u32 iDbPage;
165224  u32 iWalFrame;
165225};
165226
165227/*
165228** RBU handle.
165229**
165230** nPhaseOneStep:
165231**   If the RBU database contains an rbu_count table, this value is set to
165232**   a running estimate of the number of b-tree operations required to
165233**   finish populating the *-oal file. This allows the sqlite3_bp_progress()
165234**   API to calculate the permyriadage progress of populating the *-oal file
165235**   using the formula:
165236**
165237**     permyriadage = (10000 * nProgress) / nPhaseOneStep
165238**
165239**   nPhaseOneStep is initialized to the sum of:
165240**
165241**     nRow * (nIndex + 1)
165242**
165243**   for all source tables in the RBU database, where nRow is the number
165244**   of rows in the source table and nIndex the number of indexes on the
165245**   corresponding target database table.
165246**
165247**   This estimate is accurate if the RBU update consists entirely of
165248**   INSERT operations. However, it is inaccurate if:
165249**
165250**     * the RBU update contains any UPDATE operations. If the PK specified
165251**       for an UPDATE operation does not exist in the target table, then
165252**       no b-tree operations are required on index b-trees. Or if the
165253**       specified PK does exist, then (nIndex*2) such operations are
165254**       required (one delete and one insert on each index b-tree).
165255**
165256**     * the RBU update contains any DELETE operations for which the specified
165257**       PK does not exist. In this case no operations are required on index
165258**       b-trees.
165259**
165260**     * the RBU update contains REPLACE operations. These are similar to
165261**       UPDATE operations.
165262**
165263**   nPhaseOneStep is updated to account for the conditions above during the
165264**   first pass of each source table. The updated nPhaseOneStep value is
165265**   stored in the rbu_state table if the RBU update is suspended.
165266*/
165267struct sqlite3rbu {
165268  int eStage;                     /* Value of RBU_STATE_STAGE field */
165269  sqlite3 *dbMain;                /* target database handle */
165270  sqlite3 *dbRbu;                 /* rbu database handle */
165271  char *zTarget;                  /* Path to target db */
165272  char *zRbu;                     /* Path to rbu db */
165273  char *zState;                   /* Path to state db (or NULL if zRbu) */
165274  char zStateDb[5];               /* Db name for state ("stat" or "main") */
165275  int rc;                         /* Value returned by last rbu_step() call */
165276  char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
165277  int nStep;                      /* Rows processed for current object */
165278  int nProgress;                  /* Rows processed for all objects */
165279  RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
165280  const char *zVfsName;           /* Name of automatically created rbu vfs */
165281  rbu_file *pTargetFd;            /* File handle open on target db */
165282  i64 iOalSz;
165283  i64 nPhaseOneStep;
165284
165285  /* The following state variables are used as part of the incremental
165286  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
165287  ** function rbuSetupCheckpoint() for details.  */
165288  u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
165289  u32 mLock;
165290  int nFrame;                     /* Entries in aFrame[] array */
165291  int nFrameAlloc;                /* Allocated size of aFrame[] array */
165292  RbuFrame *aFrame;
165293  int pgsz;
165294  u8 *aBuf;
165295  i64 iWalCksum;
165296
165297  /* Used in RBU vacuum mode only */
165298  int nRbu;                       /* Number of RBU VFS in the stack */
165299  rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
165300};
165301
165302/*
165303** An rbu VFS is implemented using an instance of this structure.
165304*/
165305struct rbu_vfs {
165306  sqlite3_vfs base;               /* rbu VFS shim methods */
165307  sqlite3_vfs *pRealVfs;          /* Underlying VFS */
165308  sqlite3_mutex *mutex;           /* Mutex to protect pMain */
165309  rbu_file *pMain;                /* Linked list of main db files */
165310};
165311
165312/*
165313** Each file opened by an rbu VFS is represented by an instance of
165314** the following structure.
165315*/
165316struct rbu_file {
165317  sqlite3_file base;              /* sqlite3_file methods */
165318  sqlite3_file *pReal;            /* Underlying file handle */
165319  rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
165320  sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
165321
165322  int openFlags;                  /* Flags this file was opened with */
165323  u32 iCookie;                    /* Cookie value for main db files */
165324  u8 iWriteVer;                   /* "write-version" value for main db files */
165325  u8 bNolock;                     /* True to fail EXCLUSIVE locks */
165326
165327  int nShm;                       /* Number of entries in apShm[] array */
165328  char **apShm;                   /* Array of mmap'd *-shm regions */
165329  char *zDel;                     /* Delete this when closing file */
165330
165331  const char *zWal;               /* Wal filename for this main db file */
165332  rbu_file *pWalFd;               /* Wal file descriptor for this main db */
165333  rbu_file *pMainNext;            /* Next MAIN_DB file */
165334};
165335
165336/*
165337** True for an RBU vacuum handle, or false otherwise.
165338*/
165339#define rbuIsVacuum(p) ((p)->zTarget==0)
165340
165341
165342/*************************************************************************
165343** The following three functions, found below:
165344**
165345**   rbuDeltaGetInt()
165346**   rbuDeltaChecksum()
165347**   rbuDeltaApply()
165348**
165349** are lifted from the fossil source code (http://fossil-scm.org). They
165350** are used to implement the scalar SQL function rbu_fossil_delta().
165351*/
165352
165353/*
165354** Read bytes from *pz and convert them into a positive integer.  When
165355** finished, leave *pz pointing to the first character past the end of
165356** the integer.  The *pLen parameter holds the length of the string
165357** in *pz and is decremented once for each character in the integer.
165358*/
165359static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
165360  static const signed char zValue[] = {
165361    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165362    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165363    -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165364     0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
165365    -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
165366    25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
165367    -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
165368    52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
165369  };
165370  unsigned int v = 0;
165371  int c;
165372  unsigned char *z = (unsigned char*)*pz;
165373  unsigned char *zStart = z;
165374  while( (c = zValue[0x7f&*(z++)])>=0 ){
165375     v = (v<<6) + c;
165376  }
165377  z--;
165378  *pLen -= z - zStart;
165379  *pz = (char*)z;
165380  return v;
165381}
165382
165383/*
165384** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
165385*/
165386static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
165387  const unsigned char *z = (const unsigned char *)zIn;
165388  unsigned sum0 = 0;
165389  unsigned sum1 = 0;
165390  unsigned sum2 = 0;
165391  unsigned sum3 = 0;
165392  while(N >= 16){
165393    sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
165394    sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
165395    sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
165396    sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
165397    z += 16;
165398    N -= 16;
165399  }
165400  while(N >= 4){
165401    sum0 += z[0];
165402    sum1 += z[1];
165403    sum2 += z[2];
165404    sum3 += z[3];
165405    z += 4;
165406    N -= 4;
165407  }
165408  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
165409  switch(N){
165410    case 3:   sum3 += (z[2] << 8);
165411    case 2:   sum3 += (z[1] << 16);
165412    case 1:   sum3 += (z[0] << 24);
165413    default:  ;
165414  }
165415  return sum3;
165416}
165417
165418/*
165419** Apply a delta.
165420**
165421** The output buffer should be big enough to hold the whole output
165422** file and a NUL terminator at the end.  The delta_output_size()
165423** routine will determine this size for you.
165424**
165425** The delta string should be null-terminated.  But the delta string
165426** may contain embedded NUL characters (if the input and output are
165427** binary files) so we also have to pass in the length of the delta in
165428** the lenDelta parameter.
165429**
165430** This function returns the size of the output file in bytes (excluding
165431** the final NUL terminator character).  Except, if the delta string is
165432** malformed or intended for use with a source file other than zSrc,
165433** then this routine returns -1.
165434**
165435** Refer to the delta_create() documentation above for a description
165436** of the delta file format.
165437*/
165438static int rbuDeltaApply(
165439  const char *zSrc,      /* The source or pattern file */
165440  int lenSrc,            /* Length of the source file */
165441  const char *zDelta,    /* Delta to apply to the pattern */
165442  int lenDelta,          /* Length of the delta */
165443  char *zOut             /* Write the output into this preallocated buffer */
165444){
165445  unsigned int limit;
165446  unsigned int total = 0;
165447#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
165448  char *zOrigOut = zOut;
165449#endif
165450
165451  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
165452  if( *zDelta!='\n' ){
165453    /* ERROR: size integer not terminated by "\n" */
165454    return -1;
165455  }
165456  zDelta++; lenDelta--;
165457  while( *zDelta && lenDelta>0 ){
165458    unsigned int cnt, ofst;
165459    cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
165460    switch( zDelta[0] ){
165461      case '@': {
165462        zDelta++; lenDelta--;
165463        ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
165464        if( lenDelta>0 && zDelta[0]!=',' ){
165465          /* ERROR: copy command not terminated by ',' */
165466          return -1;
165467        }
165468        zDelta++; lenDelta--;
165469        total += cnt;
165470        if( total>limit ){
165471          /* ERROR: copy exceeds output file size */
165472          return -1;
165473        }
165474        if( (int)(ofst+cnt) > lenSrc ){
165475          /* ERROR: copy extends past end of input */
165476          return -1;
165477        }
165478        memcpy(zOut, &zSrc[ofst], cnt);
165479        zOut += cnt;
165480        break;
165481      }
165482      case ':': {
165483        zDelta++; lenDelta--;
165484        total += cnt;
165485        if( total>limit ){
165486          /* ERROR:  insert command gives an output larger than predicted */
165487          return -1;
165488        }
165489        if( (int)cnt>lenDelta ){
165490          /* ERROR: insert count exceeds size of delta */
165491          return -1;
165492        }
165493        memcpy(zOut, zDelta, cnt);
165494        zOut += cnt;
165495        zDelta += cnt;
165496        lenDelta -= cnt;
165497        break;
165498      }
165499      case ';': {
165500        zDelta++; lenDelta--;
165501        zOut[0] = 0;
165502#ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
165503        if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
165504          /* ERROR:  bad checksum */
165505          return -1;
165506        }
165507#endif
165508        if( total!=limit ){
165509          /* ERROR: generated size does not match predicted size */
165510          return -1;
165511        }
165512        return total;
165513      }
165514      default: {
165515        /* ERROR: unknown delta operator */
165516        return -1;
165517      }
165518    }
165519  }
165520  /* ERROR: unterminated delta */
165521  return -1;
165522}
165523
165524static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
165525  int size;
165526  size = rbuDeltaGetInt(&zDelta, &lenDelta);
165527  if( *zDelta!='\n' ){
165528    /* ERROR: size integer not terminated by "\n" */
165529    return -1;
165530  }
165531  return size;
165532}
165533
165534/*
165535** End of code taken from fossil.
165536*************************************************************************/
165537
165538/*
165539** Implementation of SQL scalar function rbu_fossil_delta().
165540**
165541** This function applies a fossil delta patch to a blob. Exactly two
165542** arguments must be passed to this function. The first is the blob to
165543** patch and the second the patch to apply. If no error occurs, this
165544** function returns the patched blob.
165545*/
165546static void rbuFossilDeltaFunc(
165547  sqlite3_context *context,
165548  int argc,
165549  sqlite3_value **argv
165550){
165551  const char *aDelta;
165552  int nDelta;
165553  const char *aOrig;
165554  int nOrig;
165555
165556  int nOut;
165557  int nOut2;
165558  char *aOut;
165559
165560  assert( argc==2 );
165561
165562  nOrig = sqlite3_value_bytes(argv[0]);
165563  aOrig = (const char*)sqlite3_value_blob(argv[0]);
165564  nDelta = sqlite3_value_bytes(argv[1]);
165565  aDelta = (const char*)sqlite3_value_blob(argv[1]);
165566
165567  /* Figure out the size of the output */
165568  nOut = rbuDeltaOutputSize(aDelta, nDelta);
165569  if( nOut<0 ){
165570    sqlite3_result_error(context, "corrupt fossil delta", -1);
165571    return;
165572  }
165573
165574  aOut = sqlite3_malloc(nOut+1);
165575  if( aOut==0 ){
165576    sqlite3_result_error_nomem(context);
165577  }else{
165578    nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
165579    if( nOut2!=nOut ){
165580      sqlite3_result_error(context, "corrupt fossil delta", -1);
165581    }else{
165582      sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
165583    }
165584  }
165585}
165586
165587
165588/*
165589** Prepare the SQL statement in buffer zSql against database handle db.
165590** If successful, set *ppStmt to point to the new statement and return
165591** SQLITE_OK.
165592**
165593** Otherwise, if an error does occur, set *ppStmt to NULL and return
165594** an SQLite error code. Additionally, set output variable *pzErrmsg to
165595** point to a buffer containing an error message. It is the responsibility
165596** of the caller to (eventually) free this buffer using sqlite3_free().
165597*/
165598static int prepareAndCollectError(
165599  sqlite3 *db,
165600  sqlite3_stmt **ppStmt,
165601  char **pzErrmsg,
165602  const char *zSql
165603){
165604  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
165605  if( rc!=SQLITE_OK ){
165606    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
165607    *ppStmt = 0;
165608  }
165609  return rc;
165610}
165611
165612/*
165613** Reset the SQL statement passed as the first argument. Return a copy
165614** of the value returned by sqlite3_reset().
165615**
165616** If an error has occurred, then set *pzErrmsg to point to a buffer
165617** containing an error message. It is the responsibility of the caller
165618** to eventually free this buffer using sqlite3_free().
165619*/
165620static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
165621  int rc = sqlite3_reset(pStmt);
165622  if( rc!=SQLITE_OK ){
165623    *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
165624  }
165625  return rc;
165626}
165627
165628/*
165629** Unless it is NULL, argument zSql points to a buffer allocated using
165630** sqlite3_malloc containing an SQL statement. This function prepares the SQL
165631** statement against database db and frees the buffer. If statement
165632** compilation is successful, *ppStmt is set to point to the new statement
165633** handle and SQLITE_OK is returned.
165634**
165635** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
165636** returned. In this case, *pzErrmsg may also be set to point to an error
165637** message. It is the responsibility of the caller to free this error message
165638** buffer using sqlite3_free().
165639**
165640** If argument zSql is NULL, this function assumes that an OOM has occurred.
165641** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
165642*/
165643static int prepareFreeAndCollectError(
165644  sqlite3 *db,
165645  sqlite3_stmt **ppStmt,
165646  char **pzErrmsg,
165647  char *zSql
165648){
165649  int rc;
165650  assert( *pzErrmsg==0 );
165651  if( zSql==0 ){
165652    rc = SQLITE_NOMEM;
165653    *ppStmt = 0;
165654  }else{
165655    rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
165656    sqlite3_free(zSql);
165657  }
165658  return rc;
165659}
165660
165661/*
165662** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
165663** by an earlier call to rbuObjIterCacheTableInfo().
165664*/
165665static void rbuObjIterFreeCols(RbuObjIter *pIter){
165666  int i;
165667  for(i=0; i<pIter->nTblCol; i++){
165668    sqlite3_free(pIter->azTblCol[i]);
165669    sqlite3_free(pIter->azTblType[i]);
165670  }
165671  sqlite3_free(pIter->azTblCol);
165672  pIter->azTblCol = 0;
165673  pIter->azTblType = 0;
165674  pIter->aiSrcOrder = 0;
165675  pIter->abTblPk = 0;
165676  pIter->abNotNull = 0;
165677  pIter->nTblCol = 0;
165678  pIter->eType = 0;               /* Invalid value */
165679}
165680
165681/*
165682** Finalize all statements and free all allocations that are specific to
165683** the current object (table/index pair).
165684*/
165685static void rbuObjIterClearStatements(RbuObjIter *pIter){
165686  RbuUpdateStmt *pUp;
165687
165688  sqlite3_finalize(pIter->pSelect);
165689  sqlite3_finalize(pIter->pInsert);
165690  sqlite3_finalize(pIter->pDelete);
165691  sqlite3_finalize(pIter->pTmpInsert);
165692  pUp = pIter->pRbuUpdate;
165693  while( pUp ){
165694    RbuUpdateStmt *pTmp = pUp->pNext;
165695    sqlite3_finalize(pUp->pUpdate);
165696    sqlite3_free(pUp);
165697    pUp = pTmp;
165698  }
165699
165700  pIter->pSelect = 0;
165701  pIter->pInsert = 0;
165702  pIter->pDelete = 0;
165703  pIter->pRbuUpdate = 0;
165704  pIter->pTmpInsert = 0;
165705  pIter->nCol = 0;
165706}
165707
165708/*
165709** Clean up any resources allocated as part of the iterator object passed
165710** as the only argument.
165711*/
165712static void rbuObjIterFinalize(RbuObjIter *pIter){
165713  rbuObjIterClearStatements(pIter);
165714  sqlite3_finalize(pIter->pTblIter);
165715  sqlite3_finalize(pIter->pIdxIter);
165716  rbuObjIterFreeCols(pIter);
165717  memset(pIter, 0, sizeof(RbuObjIter));
165718}
165719
165720/*
165721** Advance the iterator to the next position.
165722**
165723** If no error occurs, SQLITE_OK is returned and the iterator is left
165724** pointing to the next entry. Otherwise, an error code and message is
165725** left in the RBU handle passed as the first argument. A copy of the
165726** error code is returned.
165727*/
165728static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
165729  int rc = p->rc;
165730  if( rc==SQLITE_OK ){
165731
165732    /* Free any SQLite statements used while processing the previous object */
165733    rbuObjIterClearStatements(pIter);
165734    if( pIter->zIdx==0 ){
165735      rc = sqlite3_exec(p->dbMain,
165736          "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
165737          "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
165738          "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
165739          "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
165740          , 0, 0, &p->zErrmsg
165741      );
165742    }
165743
165744    if( rc==SQLITE_OK ){
165745      if( pIter->bCleanup ){
165746        rbuObjIterFreeCols(pIter);
165747        pIter->bCleanup = 0;
165748        rc = sqlite3_step(pIter->pTblIter);
165749        if( rc!=SQLITE_ROW ){
165750          rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
165751          pIter->zTbl = 0;
165752        }else{
165753          pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
165754          pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
165755          rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
165756        }
165757      }else{
165758        if( pIter->zIdx==0 ){
165759          sqlite3_stmt *pIdx = pIter->pIdxIter;
165760          rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
165761        }
165762        if( rc==SQLITE_OK ){
165763          rc = sqlite3_step(pIter->pIdxIter);
165764          if( rc!=SQLITE_ROW ){
165765            rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
165766            pIter->bCleanup = 1;
165767            pIter->zIdx = 0;
165768          }else{
165769            pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
165770            pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
165771            pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
165772            rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
165773          }
165774        }
165775      }
165776    }
165777  }
165778
165779  if( rc!=SQLITE_OK ){
165780    rbuObjIterFinalize(pIter);
165781    p->rc = rc;
165782  }
165783  return rc;
165784}
165785
165786
165787/*
165788** The implementation of the rbu_target_name() SQL function. This function
165789** accepts one or two arguments. The first argument is the name of a table -
165790** the name of a table in the RBU database.  The second, if it is present, is 1
165791** for a view or 0 for a table.
165792**
165793** For a non-vacuum RBU handle, if the table name matches the pattern:
165794**
165795**     data[0-9]_<name>
165796**
165797** where <name> is any sequence of 1 or more characters, <name> is returned.
165798** Otherwise, if the only argument does not match the above pattern, an SQL
165799** NULL is returned.
165800**
165801**     "data_t1"     -> "t1"
165802**     "data0123_t2" -> "t2"
165803**     "dataAB_t3"   -> NULL
165804**
165805** For an rbu vacuum handle, a copy of the first argument is returned if
165806** the second argument is either missing or 0 (not a view).
165807*/
165808static void rbuTargetNameFunc(
165809  sqlite3_context *pCtx,
165810  int argc,
165811  sqlite3_value **argv
165812){
165813  sqlite3rbu *p = sqlite3_user_data(pCtx);
165814  const char *zIn;
165815  assert( argc==1 || argc==2 );
165816
165817  zIn = (const char*)sqlite3_value_text(argv[0]);
165818  if( zIn ){
165819    if( rbuIsVacuum(p) ){
165820      if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
165821        sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
165822      }
165823    }else{
165824      if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
165825        int i;
165826        for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
165827        if( zIn[i]=='_' && zIn[i+1] ){
165828          sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
165829        }
165830      }
165831    }
165832  }
165833}
165834
165835/*
165836** Initialize the iterator structure passed as the second argument.
165837**
165838** If no error occurs, SQLITE_OK is returned and the iterator is left
165839** pointing to the first entry. Otherwise, an error code and message is
165840** left in the RBU handle passed as the first argument. A copy of the
165841** error code is returned.
165842*/
165843static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
165844  int rc;
165845  memset(pIter, 0, sizeof(RbuObjIter));
165846
165847  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
165848    sqlite3_mprintf(
165849      "SELECT rbu_target_name(name, type='view') AS target, name "
165850      "FROM sqlite_master "
165851      "WHERE type IN ('table', 'view') AND target IS NOT NULL "
165852      " %s "
165853      "ORDER BY name"
165854  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
165855
165856  if( rc==SQLITE_OK ){
165857    rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
165858        "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
165859        "  FROM main.sqlite_master "
165860        "  WHERE type='index' AND tbl_name = ?"
165861    );
165862  }
165863
165864  pIter->bCleanup = 1;
165865  p->rc = rc;
165866  return rbuObjIterNext(p, pIter);
165867}
165868
165869/*
165870** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
165871** an error code is stored in the RBU handle passed as the first argument.
165872**
165873** If an error has already occurred (p->rc is already set to something other
165874** than SQLITE_OK), then this function returns NULL without modifying the
165875** stored error code. In this case it still calls sqlite3_free() on any
165876** printf() parameters associated with %z conversions.
165877*/
165878static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
165879  char *zSql = 0;
165880  va_list ap;
165881  va_start(ap, zFmt);
165882  zSql = sqlite3_vmprintf(zFmt, ap);
165883  if( p->rc==SQLITE_OK ){
165884    if( zSql==0 ) p->rc = SQLITE_NOMEM;
165885  }else{
165886    sqlite3_free(zSql);
165887    zSql = 0;
165888  }
165889  va_end(ap);
165890  return zSql;
165891}
165892
165893/*
165894** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
165895** arguments are the usual subsitution values. This function performs
165896** the printf() style substitutions and executes the result as an SQL
165897** statement on the RBU handles database.
165898**
165899** If an error occurs, an error code and error message is stored in the
165900** RBU handle. If an error has already occurred when this function is
165901** called, it is a no-op.
165902*/
165903static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
165904  va_list ap;
165905  char *zSql;
165906  va_start(ap, zFmt);
165907  zSql = sqlite3_vmprintf(zFmt, ap);
165908  if( p->rc==SQLITE_OK ){
165909    if( zSql==0 ){
165910      p->rc = SQLITE_NOMEM;
165911    }else{
165912      p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
165913    }
165914  }
165915  sqlite3_free(zSql);
165916  va_end(ap);
165917  return p->rc;
165918}
165919
165920/*
165921** Attempt to allocate and return a pointer to a zeroed block of nByte
165922** bytes.
165923**
165924** If an error (i.e. an OOM condition) occurs, return NULL and leave an
165925** error code in the rbu handle passed as the first argument. Or, if an
165926** error has already occurred when this function is called, return NULL
165927** immediately without attempting the allocation or modifying the stored
165928** error code.
165929*/
165930static void *rbuMalloc(sqlite3rbu *p, int nByte){
165931  void *pRet = 0;
165932  if( p->rc==SQLITE_OK ){
165933    assert( nByte>0 );
165934    pRet = sqlite3_malloc64(nByte);
165935    if( pRet==0 ){
165936      p->rc = SQLITE_NOMEM;
165937    }else{
165938      memset(pRet, 0, nByte);
165939    }
165940  }
165941  return pRet;
165942}
165943
165944
165945/*
165946** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
165947** there is room for at least nCol elements. If an OOM occurs, store an
165948** error code in the RBU handle passed as the first argument.
165949*/
165950static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
165951  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
165952  char **azNew;
165953
165954  azNew = (char**)rbuMalloc(p, nByte);
165955  if( azNew ){
165956    pIter->azTblCol = azNew;
165957    pIter->azTblType = &azNew[nCol];
165958    pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
165959    pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
165960    pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
165961    pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
165962  }
165963}
165964
165965/*
165966** The first argument must be a nul-terminated string. This function
165967** returns a copy of the string in memory obtained from sqlite3_malloc().
165968** It is the responsibility of the caller to eventually free this memory
165969** using sqlite3_free().
165970**
165971** If an OOM condition is encountered when attempting to allocate memory,
165972** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
165973** if the allocation succeeds, (*pRc) is left unchanged.
165974*/
165975static char *rbuStrndup(const char *zStr, int *pRc){
165976  char *zRet = 0;
165977
165978  assert( *pRc==SQLITE_OK );
165979  if( zStr ){
165980    size_t nCopy = strlen(zStr) + 1;
165981    zRet = (char*)sqlite3_malloc64(nCopy);
165982    if( zRet ){
165983      memcpy(zRet, zStr, nCopy);
165984    }else{
165985      *pRc = SQLITE_NOMEM;
165986    }
165987  }
165988
165989  return zRet;
165990}
165991
165992/*
165993** Finalize the statement passed as the second argument.
165994**
165995** If the sqlite3_finalize() call indicates that an error occurs, and the
165996** rbu handle error code is not already set, set the error code and error
165997** message accordingly.
165998*/
165999static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
166000  sqlite3 *db = sqlite3_db_handle(pStmt);
166001  int rc = sqlite3_finalize(pStmt);
166002  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
166003    p->rc = rc;
166004    p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166005  }
166006}
166007
166008/* Determine the type of a table.
166009**
166010**   peType is of type (int*), a pointer to an output parameter of type
166011**   (int). This call sets the output parameter as follows, depending
166012**   on the type of the table specified by parameters dbName and zTbl.
166013**
166014**     RBU_PK_NOTABLE:       No such table.
166015**     RBU_PK_NONE:          Table has an implicit rowid.
166016**     RBU_PK_IPK:           Table has an explicit IPK column.
166017**     RBU_PK_EXTERNAL:      Table has an external PK index.
166018**     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
166019**     RBU_PK_VTAB:          Table is a virtual table.
166020**
166021**   Argument *piPk is also of type (int*), and also points to an output
166022**   parameter. Unless the table has an external primary key index
166023**   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
166024**   if the table does have an external primary key index, then *piPk
166025**   is set to the root page number of the primary key index before
166026**   returning.
166027**
166028** ALGORITHM:
166029**
166030**   if( no entry exists in sqlite_master ){
166031**     return RBU_PK_NOTABLE
166032**   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
166033**     return RBU_PK_VTAB
166034**   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
166035**     if( the index that is the pk exists in sqlite_master ){
166036**       *piPK = rootpage of that index.
166037**       return RBU_PK_EXTERNAL
166038**     }else{
166039**       return RBU_PK_WITHOUT_ROWID
166040**     }
166041**   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
166042**     return RBU_PK_IPK
166043**   }else{
166044**     return RBU_PK_NONE
166045**   }
166046*/
166047static void rbuTableType(
166048  sqlite3rbu *p,
166049  const char *zTab,
166050  int *peType,
166051  int *piTnum,
166052  int *piPk
166053){
166054  /*
166055  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
166056  ** 1) PRAGMA index_list = ?
166057  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
166058  ** 3) PRAGMA table_info = ?
166059  */
166060  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
166061
166062  *peType = RBU_PK_NOTABLE;
166063  *piPk = 0;
166064
166065  assert( p->rc==SQLITE_OK );
166066  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
166067    sqlite3_mprintf(
166068          "SELECT (sql LIKE 'create virtual%%'), rootpage"
166069          "  FROM sqlite_master"
166070          " WHERE name=%Q", zTab
166071  ));
166072  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
166073    /* Either an error, or no such table. */
166074    goto rbuTableType_end;
166075  }
166076  if( sqlite3_column_int(aStmt[0], 0) ){
166077    *peType = RBU_PK_VTAB;                     /* virtual table */
166078    goto rbuTableType_end;
166079  }
166080  *piTnum = sqlite3_column_int(aStmt[0], 1);
166081
166082  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
166083    sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
166084  );
166085  if( p->rc ) goto rbuTableType_end;
166086  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
166087    const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
166088    const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
166089    if( zOrig && zIdx && zOrig[0]=='p' ){
166090      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
166091          sqlite3_mprintf(
166092            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
166093      ));
166094      if( p->rc==SQLITE_OK ){
166095        if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
166096          *piPk = sqlite3_column_int(aStmt[2], 0);
166097          *peType = RBU_PK_EXTERNAL;
166098        }else{
166099          *peType = RBU_PK_WITHOUT_ROWID;
166100        }
166101      }
166102      goto rbuTableType_end;
166103    }
166104  }
166105
166106  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
166107    sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
166108  );
166109  if( p->rc==SQLITE_OK ){
166110    while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
166111      if( sqlite3_column_int(aStmt[3],5)>0 ){
166112        *peType = RBU_PK_IPK;                /* explicit IPK column */
166113        goto rbuTableType_end;
166114      }
166115    }
166116    *peType = RBU_PK_NONE;
166117  }
166118
166119rbuTableType_end: {
166120    unsigned int i;
166121    for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
166122      rbuFinalize(p, aStmt[i]);
166123    }
166124  }
166125}
166126
166127/*
166128** This is a helper function for rbuObjIterCacheTableInfo(). It populates
166129** the pIter->abIndexed[] array.
166130*/
166131static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
166132  sqlite3_stmt *pList = 0;
166133  int bIndex = 0;
166134
166135  if( p->rc==SQLITE_OK ){
166136    memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
166137    p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
166138        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
166139    );
166140  }
166141
166142  pIter->nIndex = 0;
166143  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
166144    const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
166145    sqlite3_stmt *pXInfo = 0;
166146    if( zIdx==0 ) break;
166147    p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166148        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166149    );
166150    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166151      int iCid = sqlite3_column_int(pXInfo, 1);
166152      if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
166153    }
166154    rbuFinalize(p, pXInfo);
166155    bIndex = 1;
166156    pIter->nIndex++;
166157  }
166158
166159  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
166160    /* "PRAGMA index_list" includes the main PK b-tree */
166161    pIter->nIndex--;
166162  }
166163
166164  rbuFinalize(p, pList);
166165  if( bIndex==0 ) pIter->abIndexed = 0;
166166}
166167
166168
166169/*
166170** If they are not already populated, populate the pIter->azTblCol[],
166171** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
166172** the table (not index) that the iterator currently points to.
166173**
166174** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
166175** an error does occur, an error code and error message are also left in
166176** the RBU handle.
166177*/
166178static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
166179  if( pIter->azTblCol==0 ){
166180    sqlite3_stmt *pStmt = 0;
166181    int nCol = 0;
166182    int i;                        /* for() loop iterator variable */
166183    int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
166184    int iOrder = 0;
166185    int iTnum = 0;
166186
166187    /* Figure out the type of table this step will deal with. */
166188    assert( pIter->eType==0 );
166189    rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
166190    if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
166191      p->rc = SQLITE_ERROR;
166192      p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
166193    }
166194    if( p->rc ) return p->rc;
166195    if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
166196
166197    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
166198         || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
166199         || pIter->eType==RBU_PK_VTAB
166200    );
166201
166202    /* Populate the azTblCol[] and nTblCol variables based on the columns
166203    ** of the input table. Ignore any input table columns that begin with
166204    ** "rbu_".  */
166205    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
166206        sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
166207    );
166208    if( p->rc==SQLITE_OK ){
166209      nCol = sqlite3_column_count(pStmt);
166210      rbuAllocateIterArrays(p, pIter, nCol);
166211    }
166212    for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
166213      const char *zName = (const char*)sqlite3_column_name(pStmt, i);
166214      if( sqlite3_strnicmp("rbu_", zName, 4) ){
166215        char *zCopy = rbuStrndup(zName, &p->rc);
166216        pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
166217        pIter->azTblCol[pIter->nTblCol++] = zCopy;
166218      }
166219      else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
166220        bRbuRowid = 1;
166221      }
166222    }
166223    sqlite3_finalize(pStmt);
166224    pStmt = 0;
166225
166226    if( p->rc==SQLITE_OK
166227     && rbuIsVacuum(p)==0
166228     && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
166229    ){
166230      p->rc = SQLITE_ERROR;
166231      p->zErrmsg = sqlite3_mprintf(
166232          "table %q %s rbu_rowid column", pIter->zDataTbl,
166233          (bRbuRowid ? "may not have" : "requires")
166234      );
166235    }
166236
166237    /* Check that all non-HIDDEN columns in the destination table are also
166238    ** present in the input table. Populate the abTblPk[], azTblType[] and
166239    ** aiTblOrder[] arrays at the same time.  */
166240    if( p->rc==SQLITE_OK ){
166241      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
166242          sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
166243      );
166244    }
166245    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
166246      const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
166247      if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
166248      for(i=iOrder; i<pIter->nTblCol; i++){
166249        if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
166250      }
166251      if( i==pIter->nTblCol ){
166252        p->rc = SQLITE_ERROR;
166253        p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
166254            pIter->zDataTbl, zName
166255        );
166256      }else{
166257        int iPk = sqlite3_column_int(pStmt, 5);
166258        int bNotNull = sqlite3_column_int(pStmt, 3);
166259        const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
166260
166261        if( i!=iOrder ){
166262          SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
166263          SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
166264        }
166265
166266        pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
166267        pIter->abTblPk[iOrder] = (iPk!=0);
166268        pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
166269        iOrder++;
166270      }
166271    }
166272
166273    rbuFinalize(p, pStmt);
166274    rbuObjIterCacheIndexedCols(p, pIter);
166275    assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
166276    assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
166277  }
166278
166279  return p->rc;
166280}
166281
166282/*
166283** This function constructs and returns a pointer to a nul-terminated
166284** string containing some SQL clause or list based on one or more of the
166285** column names currently stored in the pIter->azTblCol[] array.
166286*/
166287static char *rbuObjIterGetCollist(
166288  sqlite3rbu *p,                  /* RBU object */
166289  RbuObjIter *pIter               /* Object iterator for column names */
166290){
166291  char *zList = 0;
166292  const char *zSep = "";
166293  int i;
166294  for(i=0; i<pIter->nTblCol; i++){
166295    const char *z = pIter->azTblCol[i];
166296    zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
166297    zSep = ", ";
166298  }
166299  return zList;
166300}
166301
166302/*
166303** This function is used to create a SELECT list (the list of SQL
166304** expressions that follows a SELECT keyword) for a SELECT statement
166305** used to read from an data_xxx or rbu_tmp_xxx table while updating the
166306** index object currently indicated by the iterator object passed as the
166307** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
166308** to obtain the required information.
166309**
166310** If the index is of the following form:
166311**
166312**   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
166313**
166314** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
166315** "ipk", the returned string is:
166316**
166317**   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
166318**
166319** As well as the returned string, three other malloc'd strings are
166320** returned via output parameters. As follows:
166321**
166322**   pzImposterCols: ...
166323**   pzImposterPk: ...
166324**   pzWhere: ...
166325*/
166326static char *rbuObjIterGetIndexCols(
166327  sqlite3rbu *p,                  /* RBU object */
166328  RbuObjIter *pIter,              /* Object iterator for column names */
166329  char **pzImposterCols,          /* OUT: Columns for imposter table */
166330  char **pzImposterPk,            /* OUT: Imposter PK clause */
166331  char **pzWhere,                 /* OUT: WHERE clause */
166332  int *pnBind                     /* OUT: Trbul number of columns */
166333){
166334  int rc = p->rc;                 /* Error code */
166335  int rc2;                        /* sqlite3_finalize() return code */
166336  char *zRet = 0;                 /* String to return */
166337  char *zImpCols = 0;             /* String to return via *pzImposterCols */
166338  char *zImpPK = 0;               /* String to return via *pzImposterPK */
166339  char *zWhere = 0;               /* String to return via *pzWhere */
166340  int nBind = 0;                  /* Value to return via *pnBind */
166341  const char *zCom = "";          /* Set to ", " later on */
166342  const char *zAnd = "";          /* Set to " AND " later on */
166343  sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
166344
166345  if( rc==SQLITE_OK ){
166346    assert( p->zErrmsg==0 );
166347    rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166348        sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
166349    );
166350  }
166351
166352  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166353    int iCid = sqlite3_column_int(pXInfo, 1);
166354    int bDesc = sqlite3_column_int(pXInfo, 3);
166355    const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
166356    const char *zCol;
166357    const char *zType;
166358
166359    if( iCid<0 ){
166360      /* An integer primary key. If the table has an explicit IPK, use
166361      ** its name. Otherwise, use "rbu_rowid".  */
166362      if( pIter->eType==RBU_PK_IPK ){
166363        int i;
166364        for(i=0; pIter->abTblPk[i]==0; i++);
166365        assert( i<pIter->nTblCol );
166366        zCol = pIter->azTblCol[i];
166367      }else if( rbuIsVacuum(p) ){
166368        zCol = "_rowid_";
166369      }else{
166370        zCol = "rbu_rowid";
166371      }
166372      zType = "INTEGER";
166373    }else{
166374      zCol = pIter->azTblCol[iCid];
166375      zType = pIter->azTblType[iCid];
166376    }
166377
166378    zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
166379    if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
166380      const char *zOrder = (bDesc ? " DESC" : "");
166381      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
166382          zImpPK, zCom, nBind, zCol, zOrder
166383      );
166384    }
166385    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
166386        zImpCols, zCom, nBind, zCol, zType, zCollate
166387    );
166388    zWhere = sqlite3_mprintf(
166389        "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
166390    );
166391    if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
166392    zCom = ", ";
166393    zAnd = " AND ";
166394    nBind++;
166395  }
166396
166397  rc2 = sqlite3_finalize(pXInfo);
166398  if( rc==SQLITE_OK ) rc = rc2;
166399
166400  if( rc!=SQLITE_OK ){
166401    sqlite3_free(zRet);
166402    sqlite3_free(zImpCols);
166403    sqlite3_free(zImpPK);
166404    sqlite3_free(zWhere);
166405    zRet = 0;
166406    zImpCols = 0;
166407    zImpPK = 0;
166408    zWhere = 0;
166409    p->rc = rc;
166410  }
166411
166412  *pzImposterCols = zImpCols;
166413  *pzImposterPk = zImpPK;
166414  *pzWhere = zWhere;
166415  *pnBind = nBind;
166416  return zRet;
166417}
166418
166419/*
166420** Assuming the current table columns are "a", "b" and "c", and the zObj
166421** paramter is passed "old", return a string of the form:
166422**
166423**     "old.a, old.b, old.b"
166424**
166425** With the column names escaped.
166426**
166427** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
166428** the text ", old._rowid_" to the returned value.
166429*/
166430static char *rbuObjIterGetOldlist(
166431  sqlite3rbu *p,
166432  RbuObjIter *pIter,
166433  const char *zObj
166434){
166435  char *zList = 0;
166436  if( p->rc==SQLITE_OK && pIter->abIndexed ){
166437    const char *zS = "";
166438    int i;
166439    for(i=0; i<pIter->nTblCol; i++){
166440      if( pIter->abIndexed[i] ){
166441        const char *zCol = pIter->azTblCol[i];
166442        zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
166443      }else{
166444        zList = sqlite3_mprintf("%z%sNULL", zList, zS);
166445      }
166446      zS = ", ";
166447      if( zList==0 ){
166448        p->rc = SQLITE_NOMEM;
166449        break;
166450      }
166451    }
166452
166453    /* For a table with implicit rowids, append "old._rowid_" to the list. */
166454    if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166455      zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
166456    }
166457  }
166458  return zList;
166459}
166460
166461/*
166462** Return an expression that can be used in a WHERE clause to match the
166463** primary key of the current table. For example, if the table is:
166464**
166465**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
166466**
166467** Return the string:
166468**
166469**   "b = ?1 AND c = ?2"
166470*/
166471static char *rbuObjIterGetWhere(
166472  sqlite3rbu *p,
166473  RbuObjIter *pIter
166474){
166475  char *zList = 0;
166476  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
166477    zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
166478  }else if( pIter->eType==RBU_PK_EXTERNAL ){
166479    const char *zSep = "";
166480    int i;
166481    for(i=0; i<pIter->nTblCol; i++){
166482      if( pIter->abTblPk[i] ){
166483        zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
166484        zSep = " AND ";
166485      }
166486    }
166487    zList = rbuMPrintf(p,
166488        "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
166489    );
166490
166491  }else{
166492    const char *zSep = "";
166493    int i;
166494    for(i=0; i<pIter->nTblCol; i++){
166495      if( pIter->abTblPk[i] ){
166496        const char *zCol = pIter->azTblCol[i];
166497        zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
166498        zSep = " AND ";
166499      }
166500    }
166501  }
166502  return zList;
166503}
166504
166505/*
166506** The SELECT statement iterating through the keys for the current object
166507** (p->objiter.pSelect) currently points to a valid row. However, there
166508** is something wrong with the rbu_control value in the rbu_control value
166509** stored in the (p->nCol+1)'th column. Set the error code and error message
166510** of the RBU handle to something reflecting this.
166511*/
166512static void rbuBadControlError(sqlite3rbu *p){
166513  p->rc = SQLITE_ERROR;
166514  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
166515}
166516
166517
166518/*
166519** Return a nul-terminated string containing the comma separated list of
166520** assignments that should be included following the "SET" keyword of
166521** an UPDATE statement used to update the table object that the iterator
166522** passed as the second argument currently points to if the rbu_control
166523** column of the data_xxx table entry is set to zMask.
166524**
166525** The memory for the returned string is obtained from sqlite3_malloc().
166526** It is the responsibility of the caller to eventually free it using
166527** sqlite3_free().
166528**
166529** If an OOM error is encountered when allocating space for the new
166530** string, an error code is left in the rbu handle passed as the first
166531** argument and NULL is returned. Or, if an error has already occurred
166532** when this function is called, NULL is returned immediately, without
166533** attempting the allocation or modifying the stored error code.
166534*/
166535static char *rbuObjIterGetSetlist(
166536  sqlite3rbu *p,
166537  RbuObjIter *pIter,
166538  const char *zMask
166539){
166540  char *zList = 0;
166541  if( p->rc==SQLITE_OK ){
166542    int i;
166543
166544    if( (int)strlen(zMask)!=pIter->nTblCol ){
166545      rbuBadControlError(p);
166546    }else{
166547      const char *zSep = "";
166548      for(i=0; i<pIter->nTblCol; i++){
166549        char c = zMask[pIter->aiSrcOrder[i]];
166550        if( c=='x' ){
166551          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
166552              zList, zSep, pIter->azTblCol[i], i+1
166553          );
166554          zSep = ", ";
166555        }
166556        else if( c=='d' ){
166557          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
166558              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
166559          );
166560          zSep = ", ";
166561        }
166562        else if( c=='f' ){
166563          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
166564              zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
166565          );
166566          zSep = ", ";
166567        }
166568      }
166569    }
166570  }
166571  return zList;
166572}
166573
166574/*
166575** Return a nul-terminated string consisting of nByte comma separated
166576** "?" expressions. For example, if nByte is 3, return a pointer to
166577** a buffer containing the string "?,?,?".
166578**
166579** The memory for the returned string is obtained from sqlite3_malloc().
166580** It is the responsibility of the caller to eventually free it using
166581** sqlite3_free().
166582**
166583** If an OOM error is encountered when allocating space for the new
166584** string, an error code is left in the rbu handle passed as the first
166585** argument and NULL is returned. Or, if an error has already occurred
166586** when this function is called, NULL is returned immediately, without
166587** attempting the allocation or modifying the stored error code.
166588*/
166589static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
166590  char *zRet = 0;
166591  int nByte = nBind*2 + 1;
166592
166593  zRet = (char*)rbuMalloc(p, nByte);
166594  if( zRet ){
166595    int i;
166596    for(i=0; i<nBind; i++){
166597      zRet[i*2] = '?';
166598      zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
166599    }
166600  }
166601  return zRet;
166602}
166603
166604/*
166605** The iterator currently points to a table (not index) of type
166606** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
166607** declaration for the corresponding imposter table. For example,
166608** if the iterator points to a table created as:
166609**
166610**   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
166611**
166612** this function returns:
166613**
166614**   PRIMARY KEY("b", "a" DESC)
166615*/
166616static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
166617  char *z = 0;
166618  assert( pIter->zIdx==0 );
166619  if( p->rc==SQLITE_OK ){
166620    const char *zSep = "PRIMARY KEY(";
166621    sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
166622    sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
166623
166624    p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
166625        sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
166626    );
166627    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
166628      const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
166629      if( zOrig && strcmp(zOrig, "pk")==0 ){
166630        const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
166631        if( zIdx ){
166632          p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166633              sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166634          );
166635        }
166636        break;
166637      }
166638    }
166639    rbuFinalize(p, pXList);
166640
166641    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166642      if( sqlite3_column_int(pXInfo, 5) ){
166643        /* int iCid = sqlite3_column_int(pXInfo, 0); */
166644        const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
166645        const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
166646        z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
166647        zSep = ", ";
166648      }
166649    }
166650    z = rbuMPrintf(p, "%z)", z);
166651    rbuFinalize(p, pXInfo);
166652  }
166653  return z;
166654}
166655
166656/*
166657** This function creates the second imposter table used when writing to
166658** a table b-tree where the table has an external primary key. If the
166659** iterator passed as the second argument does not currently point to
166660** a table (not index) with an external primary key, this function is a
166661** no-op.
166662**
166663** Assuming the iterator does point to a table with an external PK, this
166664** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
166665** used to access that PK index. For example, if the target table is
166666** declared as follows:
166667**
166668**   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
166669**
166670** then the imposter table schema is:
166671**
166672**   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
166673**
166674*/
166675static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
166676  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
166677    int tnum = pIter->iPkTnum;    /* Root page of PK index */
166678    sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
166679    const char *zIdx = 0;         /* Name of PK index */
166680    sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
166681    const char *zComma = "";
166682    char *zCols = 0;              /* Used to build up list of table cols */
166683    char *zPk = 0;                /* Used to build up table PK declaration */
166684
166685    /* Figure out the name of the primary key index for the current table.
166686    ** This is needed for the argument to "PRAGMA index_xinfo". Set
166687    ** zIdx to point to a nul-terminated string containing this name. */
166688    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
166689        "SELECT name FROM sqlite_master WHERE rootpage = ?"
166690    );
166691    if( p->rc==SQLITE_OK ){
166692      sqlite3_bind_int(pQuery, 1, tnum);
166693      if( SQLITE_ROW==sqlite3_step(pQuery) ){
166694        zIdx = (const char*)sqlite3_column_text(pQuery, 0);
166695      }
166696    }
166697    if( zIdx ){
166698      p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166699          sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166700      );
166701    }
166702    rbuFinalize(p, pQuery);
166703
166704    while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166705      int bKey = sqlite3_column_int(pXInfo, 5);
166706      if( bKey ){
166707        int iCid = sqlite3_column_int(pXInfo, 1);
166708        int bDesc = sqlite3_column_int(pXInfo, 3);
166709        const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
166710        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
166711            iCid, pIter->azTblType[iCid], zCollate
166712        );
166713        zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
166714        zComma = ", ";
166715      }
166716    }
166717    zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
166718    rbuFinalize(p, pXInfo);
166719
166720    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
166721    rbuMPrintfExec(p, p->dbMain,
166722        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
166723        zCols, zPk
166724    );
166725    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166726  }
166727}
166728
166729/*
166730** If an error has already occurred when this function is called, it
166731** immediately returns zero (without doing any work). Or, if an error
166732** occurs during the execution of this function, it sets the error code
166733** in the sqlite3rbu object indicated by the first argument and returns
166734** zero.
166735**
166736** The iterator passed as the second argument is guaranteed to point to
166737** a table (not an index) when this function is called. This function
166738** attempts to create any imposter table required to write to the main
166739** table b-tree of the table before returning. Non-zero is returned if
166740** an imposter table are created, or zero otherwise.
166741**
166742** An imposter table is required in all cases except RBU_PK_VTAB. Only
166743** virtual tables are written to directly. The imposter table has the
166744** same schema as the actual target table (less any UNIQUE constraints).
166745** More precisely, the "same schema" means the same columns, types,
166746** collation sequences. For tables that do not have an external PRIMARY
166747** KEY, it also means the same PRIMARY KEY declaration.
166748*/
166749static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
166750  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
166751    int tnum = pIter->iTnum;
166752    const char *zComma = "";
166753    char *zSql = 0;
166754    int iCol;
166755    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
166756
166757    for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
166758      const char *zPk = "";
166759      const char *zCol = pIter->azTblCol[iCol];
166760      const char *zColl = 0;
166761
166762      p->rc = sqlite3_table_column_metadata(
166763          p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
166764      );
166765
166766      if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
166767        /* If the target table column is an "INTEGER PRIMARY KEY", add
166768        ** "PRIMARY KEY" to the imposter table column declaration. */
166769        zPk = "PRIMARY KEY ";
166770      }
166771      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
166772          zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
166773          (pIter->abNotNull[iCol] ? " NOT NULL" : "")
166774      );
166775      zComma = ", ";
166776    }
166777
166778    if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
166779      char *zPk = rbuWithoutRowidPK(p, pIter);
166780      if( zPk ){
166781        zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
166782      }
166783    }
166784
166785    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
166786    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
166787        pIter->zTbl, zSql,
166788        (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
166789    );
166790    sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166791  }
166792}
166793
166794/*
166795** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
166796** Specifically a statement of the form:
166797**
166798**     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
166799**
166800** The number of bound variables is equal to the number of columns in
166801** the target table, plus one (for the rbu_control column), plus one more
166802** (for the rbu_rowid column) if the target table is an implicit IPK or
166803** virtual table.
166804*/
166805static void rbuObjIterPrepareTmpInsert(
166806  sqlite3rbu *p,
166807  RbuObjIter *pIter,
166808  const char *zCollist,
166809  const char *zRbuRowid
166810){
166811  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
166812  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
166813  if( zBind ){
166814    assert( pIter->pTmpInsert==0 );
166815    p->rc = prepareFreeAndCollectError(
166816        p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
166817          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
166818          p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
166819    ));
166820  }
166821}
166822
166823static void rbuTmpInsertFunc(
166824  sqlite3_context *pCtx,
166825  int nVal,
166826  sqlite3_value **apVal
166827){
166828  sqlite3rbu *p = sqlite3_user_data(pCtx);
166829  int rc = SQLITE_OK;
166830  int i;
166831
166832  assert( sqlite3_value_int(apVal[0])!=0
166833      || p->objiter.eType==RBU_PK_EXTERNAL
166834      || p->objiter.eType==RBU_PK_NONE
166835  );
166836  if( sqlite3_value_int(apVal[0])!=0 ){
166837    p->nPhaseOneStep += p->objiter.nIndex;
166838  }
166839
166840  for(i=0; rc==SQLITE_OK && i<nVal; i++){
166841    rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
166842  }
166843  if( rc==SQLITE_OK ){
166844    sqlite3_step(p->objiter.pTmpInsert);
166845    rc = sqlite3_reset(p->objiter.pTmpInsert);
166846  }
166847
166848  if( rc!=SQLITE_OK ){
166849    sqlite3_result_error_code(pCtx, rc);
166850  }
166851}
166852
166853/*
166854** Ensure that the SQLite statement handles required to update the
166855** target database object currently indicated by the iterator passed
166856** as the second argument are available.
166857*/
166858static int rbuObjIterPrepareAll(
166859  sqlite3rbu *p,
166860  RbuObjIter *pIter,
166861  int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
166862){
166863  assert( pIter->bCleanup==0 );
166864  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
166865    const int tnum = pIter->iTnum;
166866    char *zCollist = 0;           /* List of indexed columns */
166867    char **pz = &p->zErrmsg;
166868    const char *zIdx = pIter->zIdx;
166869    char *zLimit = 0;
166870
166871    if( nOffset ){
166872      zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
166873      if( !zLimit ) p->rc = SQLITE_NOMEM;
166874    }
166875
166876    if( zIdx ){
166877      const char *zTbl = pIter->zTbl;
166878      char *zImposterCols = 0;    /* Columns for imposter table */
166879      char *zImposterPK = 0;      /* Primary key declaration for imposter */
166880      char *zWhere = 0;           /* WHERE clause on PK columns */
166881      char *zBind = 0;
166882      int nBind = 0;
166883
166884      assert( pIter->eType!=RBU_PK_VTAB );
166885      zCollist = rbuObjIterGetIndexCols(
166886          p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
166887      );
166888      zBind = rbuObjIterGetBindlist(p, nBind);
166889
166890      /* Create the imposter table used to write to this index. */
166891      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
166892      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
166893      rbuMPrintfExec(p, p->dbMain,
166894          "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
166895          zTbl, zImposterCols, zImposterPK
166896      );
166897      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166898
166899      /* Create the statement to insert index entries */
166900      pIter->nCol = nBind;
166901      if( p->rc==SQLITE_OK ){
166902        p->rc = prepareFreeAndCollectError(
166903            p->dbMain, &pIter->pInsert, &p->zErrmsg,
166904          sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
166905        );
166906      }
166907
166908      /* And to delete index entries */
166909      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
166910        p->rc = prepareFreeAndCollectError(
166911            p->dbMain, &pIter->pDelete, &p->zErrmsg,
166912          sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
166913        );
166914      }
166915
166916      /* Create the SELECT statement to read keys in sorted order */
166917      if( p->rc==SQLITE_OK ){
166918        char *zSql;
166919        if( rbuIsVacuum(p) ){
166920          zSql = sqlite3_mprintf(
166921              "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
166922              zCollist,
166923              pIter->zDataTbl,
166924              zCollist, zLimit
166925          );
166926        }else
166927
166928        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166929          zSql = sqlite3_mprintf(
166930              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
166931              zCollist, p->zStateDb, pIter->zDataTbl,
166932              zCollist, zLimit
166933          );
166934        }else{
166935          zSql = sqlite3_mprintf(
166936              "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
166937              "UNION ALL "
166938              "SELECT %s, rbu_control FROM '%q' "
166939              "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
166940              "ORDER BY %s%s",
166941              zCollist, p->zStateDb, pIter->zDataTbl,
166942              zCollist, pIter->zDataTbl,
166943              zCollist, zLimit
166944          );
166945        }
166946        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
166947      }
166948
166949      sqlite3_free(zImposterCols);
166950      sqlite3_free(zImposterPK);
166951      sqlite3_free(zWhere);
166952      sqlite3_free(zBind);
166953    }else{
166954      int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
166955                    ||(pIter->eType==RBU_PK_NONE)
166956                    ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
166957      const char *zTbl = pIter->zTbl;       /* Table this step applies to */
166958      const char *zWrite;                   /* Imposter table name */
166959
166960      char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
166961      char *zWhere = rbuObjIterGetWhere(p, pIter);
166962      char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
166963      char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
166964
166965      zCollist = rbuObjIterGetCollist(p, pIter);
166966      pIter->nCol = pIter->nTblCol;
166967
166968      /* Create the imposter table or tables (if required). */
166969      rbuCreateImposterTable(p, pIter);
166970      rbuCreateImposterTable2(p, pIter);
166971      zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
166972
166973      /* Create the INSERT statement to write to the target PK b-tree */
166974      if( p->rc==SQLITE_OK ){
166975        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
166976            sqlite3_mprintf(
166977              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
166978              zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
166979            )
166980        );
166981      }
166982
166983      /* Create the DELETE statement to write to the target PK b-tree.
166984      ** Because it only performs INSERT operations, this is not required for
166985      ** an rbu vacuum handle.  */
166986      if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
166987        p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
166988            sqlite3_mprintf(
166989              "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
166990            )
166991        );
166992      }
166993
166994      if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
166995        const char *zRbuRowid = "";
166996        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166997          zRbuRowid = ", rbu_rowid";
166998        }
166999
167000        /* Create the rbu_tmp_xxx table and the triggers to populate it. */
167001        rbuMPrintfExec(p, p->dbRbu,
167002            "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
167003            "SELECT *%s FROM '%q' WHERE 0;"
167004            , p->zStateDb, pIter->zDataTbl
167005            , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
167006            , pIter->zDataTbl
167007        );
167008
167009        rbuMPrintfExec(p, p->dbMain,
167010            "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
167011            "BEGIN "
167012            "  SELECT rbu_tmp_insert(3, %s);"
167013            "END;"
167014
167015            "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
167016            "BEGIN "
167017            "  SELECT rbu_tmp_insert(3, %s);"
167018            "END;"
167019
167020            "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
167021            "BEGIN "
167022            "  SELECT rbu_tmp_insert(4, %s);"
167023            "END;",
167024            zWrite, zTbl, zOldlist,
167025            zWrite, zTbl, zOldlist,
167026            zWrite, zTbl, zNewlist
167027        );
167028
167029        if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
167030          rbuMPrintfExec(p, p->dbMain,
167031              "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
167032              "BEGIN "
167033              "  SELECT rbu_tmp_insert(0, %s);"
167034              "END;",
167035              zWrite, zTbl, zNewlist
167036          );
167037        }
167038
167039        rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
167040      }
167041
167042      /* Create the SELECT statement to read keys from data_xxx */
167043      if( p->rc==SQLITE_OK ){
167044        const char *zRbuRowid = "";
167045        if( bRbuRowid ){
167046          zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
167047        }
167048        p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
167049            sqlite3_mprintf(
167050              "SELECT %s,%s rbu_control%s FROM '%q'%s",
167051              zCollist,
167052              (rbuIsVacuum(p) ? "0 AS " : ""),
167053              zRbuRowid,
167054              pIter->zDataTbl, zLimit
167055            )
167056        );
167057      }
167058
167059      sqlite3_free(zWhere);
167060      sqlite3_free(zOldlist);
167061      sqlite3_free(zNewlist);
167062      sqlite3_free(zBindings);
167063    }
167064    sqlite3_free(zCollist);
167065    sqlite3_free(zLimit);
167066  }
167067
167068  return p->rc;
167069}
167070
167071/*
167072** Set output variable *ppStmt to point to an UPDATE statement that may
167073** be used to update the imposter table for the main table b-tree of the
167074** table object that pIter currently points to, assuming that the
167075** rbu_control column of the data_xyz table contains zMask.
167076**
167077** If the zMask string does not specify any columns to update, then this
167078** is not an error. Output variable *ppStmt is set to NULL in this case.
167079*/
167080static int rbuGetUpdateStmt(
167081  sqlite3rbu *p,                  /* RBU handle */
167082  RbuObjIter *pIter,              /* Object iterator */
167083  const char *zMask,              /* rbu_control value ('x.x.') */
167084  sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
167085){
167086  RbuUpdateStmt **pp;
167087  RbuUpdateStmt *pUp = 0;
167088  int nUp = 0;
167089
167090  /* In case an error occurs */
167091  *ppStmt = 0;
167092
167093  /* Search for an existing statement. If one is found, shift it to the front
167094  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
167095  ** to the number of statements currently in the cache and pUp to the
167096  ** last object in the list.  */
167097  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
167098    pUp = *pp;
167099    if( strcmp(pUp->zMask, zMask)==0 ){
167100      *pp = pUp->pNext;
167101      pUp->pNext = pIter->pRbuUpdate;
167102      pIter->pRbuUpdate = pUp;
167103      *ppStmt = pUp->pUpdate;
167104      return SQLITE_OK;
167105    }
167106    nUp++;
167107  }
167108  assert( pUp==0 || pUp->pNext==0 );
167109
167110  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
167111    for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
167112    *pp = 0;
167113    sqlite3_finalize(pUp->pUpdate);
167114    pUp->pUpdate = 0;
167115  }else{
167116    pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
167117  }
167118
167119  if( pUp ){
167120    char *zWhere = rbuObjIterGetWhere(p, pIter);
167121    char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
167122    char *zUpdate = 0;
167123
167124    pUp->zMask = (char*)&pUp[1];
167125    memcpy(pUp->zMask, zMask, pIter->nTblCol);
167126    pUp->pNext = pIter->pRbuUpdate;
167127    pIter->pRbuUpdate = pUp;
167128
167129    if( zSet ){
167130      const char *zPrefix = "";
167131
167132      if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
167133      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
167134          zPrefix, pIter->zTbl, zSet, zWhere
167135      );
167136      p->rc = prepareFreeAndCollectError(
167137          p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
167138      );
167139      *ppStmt = pUp->pUpdate;
167140    }
167141    sqlite3_free(zWhere);
167142    sqlite3_free(zSet);
167143  }
167144
167145  return p->rc;
167146}
167147
167148static sqlite3 *rbuOpenDbhandle(
167149  sqlite3rbu *p,
167150  const char *zName,
167151  int bUseVfs
167152){
167153  sqlite3 *db = 0;
167154  if( p->rc==SQLITE_OK ){
167155    const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
167156    p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
167157    if( p->rc ){
167158      p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
167159      sqlite3_close(db);
167160      db = 0;
167161    }
167162  }
167163  return db;
167164}
167165
167166/*
167167** Free an RbuState object allocated by rbuLoadState().
167168*/
167169static void rbuFreeState(RbuState *p){
167170  if( p ){
167171    sqlite3_free(p->zTbl);
167172    sqlite3_free(p->zIdx);
167173    sqlite3_free(p);
167174  }
167175}
167176
167177/*
167178** Allocate an RbuState object and load the contents of the rbu_state
167179** table into it. Return a pointer to the new object. It is the
167180** responsibility of the caller to eventually free the object using
167181** sqlite3_free().
167182**
167183** If an error occurs, leave an error code and message in the rbu handle
167184** and return NULL.
167185*/
167186static RbuState *rbuLoadState(sqlite3rbu *p){
167187  RbuState *pRet = 0;
167188  sqlite3_stmt *pStmt = 0;
167189  int rc;
167190  int rc2;
167191
167192  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
167193  if( pRet==0 ) return 0;
167194
167195  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
167196      sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
167197  );
167198  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
167199    switch( sqlite3_column_int(pStmt, 0) ){
167200      case RBU_STATE_STAGE:
167201        pRet->eStage = sqlite3_column_int(pStmt, 1);
167202        if( pRet->eStage!=RBU_STAGE_OAL
167203         && pRet->eStage!=RBU_STAGE_MOVE
167204         && pRet->eStage!=RBU_STAGE_CKPT
167205        ){
167206          p->rc = SQLITE_CORRUPT;
167207        }
167208        break;
167209
167210      case RBU_STATE_TBL:
167211        pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
167212        break;
167213
167214      case RBU_STATE_IDX:
167215        pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
167216        break;
167217
167218      case RBU_STATE_ROW:
167219        pRet->nRow = sqlite3_column_int(pStmt, 1);
167220        break;
167221
167222      case RBU_STATE_PROGRESS:
167223        pRet->nProgress = sqlite3_column_int64(pStmt, 1);
167224        break;
167225
167226      case RBU_STATE_CKPT:
167227        pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
167228        break;
167229
167230      case RBU_STATE_COOKIE:
167231        pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
167232        break;
167233
167234      case RBU_STATE_OALSZ:
167235        pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
167236        break;
167237
167238      case RBU_STATE_PHASEONESTEP:
167239        pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
167240        break;
167241
167242      default:
167243        rc = SQLITE_CORRUPT;
167244        break;
167245    }
167246  }
167247  rc2 = sqlite3_finalize(pStmt);
167248  if( rc==SQLITE_OK ) rc = rc2;
167249
167250  p->rc = rc;
167251  return pRet;
167252}
167253
167254
167255/*
167256** Open the database handle and attach the RBU database as "rbu". If an
167257** error occurs, leave an error code and message in the RBU handle.
167258*/
167259static void rbuOpenDatabase(sqlite3rbu *p){
167260  assert( p->rc==SQLITE_OK );
167261  assert( p->dbMain==0 && p->dbRbu==0 );
167262  assert( rbuIsVacuum(p) || p->zTarget!=0 );
167263
167264  /* Open the RBU database */
167265  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
167266
167267  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167268    sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
167269  }
167270
167271  /* If using separate RBU and state databases, attach the state database to
167272  ** the RBU db handle now.  */
167273  if( p->zState ){
167274    rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
167275    memcpy(p->zStateDb, "stat", 4);
167276  }else{
167277    memcpy(p->zStateDb, "main", 4);
167278  }
167279
167280#if 0
167281  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167282    p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
167283  }
167284#endif
167285
167286  /* If it has not already been created, create the rbu_state table */
167287  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
167288
167289#if 0
167290  if( rbuIsVacuum(p) ){
167291    if( p->rc==SQLITE_OK ){
167292      int rc2;
167293      int bOk = 0;
167294      sqlite3_stmt *pCnt = 0;
167295      p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
167296          "SELECT count(*) FROM stat.sqlite_master"
167297      );
167298      if( p->rc==SQLITE_OK
167299       && sqlite3_step(pCnt)==SQLITE_ROW
167300       && 1==sqlite3_column_int(pCnt, 0)
167301      ){
167302        bOk = 1;
167303      }
167304      rc2 = sqlite3_finalize(pCnt);
167305      if( p->rc==SQLITE_OK ) p->rc = rc2;
167306
167307      if( p->rc==SQLITE_OK && bOk==0 ){
167308        p->rc = SQLITE_ERROR;
167309        p->zErrmsg = sqlite3_mprintf("invalid state database");
167310      }
167311
167312      if( p->rc==SQLITE_OK ){
167313        p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
167314      }
167315    }
167316  }
167317#endif
167318
167319  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167320    int bOpen = 0;
167321    int rc;
167322    p->nRbu = 0;
167323    p->pRbuFd = 0;
167324    rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
167325    if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
167326    if( p->eStage>=RBU_STAGE_MOVE ){
167327      bOpen = 1;
167328    }else{
167329      RbuState *pState = rbuLoadState(p);
167330      if( pState ){
167331        bOpen = (pState->eStage>RBU_STAGE_MOVE);
167332        rbuFreeState(pState);
167333      }
167334    }
167335    if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
167336  }
167337
167338  p->eStage = 0;
167339  if( p->rc==SQLITE_OK && p->dbMain==0 ){
167340    if( !rbuIsVacuum(p) ){
167341      p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
167342    }else if( p->pRbuFd->pWalFd ){
167343      p->rc = SQLITE_ERROR;
167344      p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
167345    }else{
167346      char *zTarget;
167347      char *zExtra = 0;
167348      if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
167349        zExtra = &p->zRbu[5];
167350        while( *zExtra ){
167351          if( *zExtra++=='?' ) break;
167352        }
167353        if( *zExtra=='\0' ) zExtra = 0;
167354      }
167355
167356      zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
167357          sqlite3_db_filename(p->dbRbu, "main"),
167358          (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
167359      );
167360
167361      if( zTarget==0 ){
167362        p->rc = SQLITE_NOMEM;
167363        return;
167364      }
167365      p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
167366      sqlite3_free(zTarget);
167367    }
167368  }
167369
167370  if( p->rc==SQLITE_OK ){
167371    p->rc = sqlite3_create_function(p->dbMain,
167372        "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
167373    );
167374  }
167375
167376  if( p->rc==SQLITE_OK ){
167377    p->rc = sqlite3_create_function(p->dbMain,
167378        "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
167379    );
167380  }
167381
167382  if( p->rc==SQLITE_OK ){
167383    p->rc = sqlite3_create_function(p->dbRbu,
167384        "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
167385    );
167386  }
167387
167388  if( p->rc==SQLITE_OK ){
167389    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
167390  }
167391  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
167392
167393  /* Mark the database file just opened as an RBU target database. If
167394  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
167395  ** This is an error.  */
167396  if( p->rc==SQLITE_OK ){
167397    p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
167398  }
167399
167400  if( p->rc==SQLITE_NOTFOUND ){
167401    p->rc = SQLITE_ERROR;
167402    p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
167403  }
167404}
167405
167406/*
167407** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
167408** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
167409**
167410** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
167411** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
167412** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
167413** three characters, then shorten the suffix on z[] to be the last three
167414** characters of the original suffix.
167415**
167416** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
167417** do the suffix shortening regardless of URI parameter.
167418**
167419** Examples:
167420**
167421**     test.db-journal    =>   test.nal
167422**     test.db-wal        =>   test.wal
167423**     test.db-shm        =>   test.shm
167424**     test.db-mj7f3319fa =>   test.9fa
167425*/
167426static void rbuFileSuffix3(const char *zBase, char *z){
167427#ifdef SQLITE_ENABLE_8_3_NAMES
167428#if SQLITE_ENABLE_8_3_NAMES<2
167429  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
167430#endif
167431  {
167432    int i, sz;
167433    sz = (int)strlen(z)&0xffffff;
167434    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
167435    if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
167436  }
167437#endif
167438}
167439
167440/*
167441** Return the current wal-index header checksum for the target database
167442** as a 64-bit integer.
167443**
167444** The checksum is store in the first page of xShmMap memory as an 8-byte
167445** blob starting at byte offset 40.
167446*/
167447static i64 rbuShmChecksum(sqlite3rbu *p){
167448  i64 iRet = 0;
167449  if( p->rc==SQLITE_OK ){
167450    sqlite3_file *pDb = p->pTargetFd->pReal;
167451    u32 volatile *ptr;
167452    p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
167453    if( p->rc==SQLITE_OK ){
167454      iRet = ((i64)ptr[10] << 32) + ptr[11];
167455    }
167456  }
167457  return iRet;
167458}
167459
167460/*
167461** This function is called as part of initializing or reinitializing an
167462** incremental checkpoint.
167463**
167464** It populates the sqlite3rbu.aFrame[] array with the set of
167465** (wal frame -> db page) copy operations required to checkpoint the
167466** current wal file, and obtains the set of shm locks required to safely
167467** perform the copy operations directly on the file-system.
167468**
167469** If argument pState is not NULL, then the incremental checkpoint is
167470** being resumed. In this case, if the checksum of the wal-index-header
167471** following recovery is not the same as the checksum saved in the RbuState
167472** object, then the rbu handle is set to DONE state. This occurs if some
167473** other client appends a transaction to the wal file in the middle of
167474** an incremental checkpoint.
167475*/
167476static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
167477
167478  /* If pState is NULL, then the wal file may not have been opened and
167479  ** recovered. Running a read-statement here to ensure that doing so
167480  ** does not interfere with the "capture" process below.  */
167481  if( pState==0 ){
167482    p->eStage = 0;
167483    if( p->rc==SQLITE_OK ){
167484      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
167485    }
167486  }
167487
167488  /* Assuming no error has occurred, run a "restart" checkpoint with the
167489  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
167490  ** special behaviour in the rbu VFS:
167491  **
167492  **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
167493  **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
167494  **     proceed with running a passive checkpoint instead of failing).
167495  **
167496  **   * Attempts to read from the *-wal file or write to the database file
167497  **     do not perform any IO. Instead, the frame/page combinations that
167498  **     would be read/written are recorded in the sqlite3rbu.aFrame[]
167499  **     array.
167500  **
167501  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
167502  **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
167503  **     no-ops. These locks will not be released until the connection
167504  **     is closed.
167505  **
167506  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
167507  **     error.
167508  **
167509  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
167510  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
167511  ** array populated with a set of (frame -> page) mappings. Because the
167512  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
167513  ** data from the wal file into the database file according to the
167514  ** contents of aFrame[].
167515  */
167516  if( p->rc==SQLITE_OK ){
167517    int rc2;
167518    p->eStage = RBU_STAGE_CAPTURE;
167519    rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
167520    if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
167521  }
167522
167523  if( p->rc==SQLITE_OK ){
167524    p->eStage = RBU_STAGE_CKPT;
167525    p->nStep = (pState ? pState->nRow : 0);
167526    p->aBuf = rbuMalloc(p, p->pgsz);
167527    p->iWalCksum = rbuShmChecksum(p);
167528  }
167529
167530  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
167531    p->rc = SQLITE_DONE;
167532    p->eStage = RBU_STAGE_DONE;
167533  }
167534}
167535
167536/*
167537** Called when iAmt bytes are read from offset iOff of the wal file while
167538** the rbu object is in capture mode. Record the frame number of the frame
167539** being read in the aFrame[] array.
167540*/
167541static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
167542  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
167543  u32 iFrame;
167544
167545  if( pRbu->mLock!=mReq ){
167546    pRbu->rc = SQLITE_BUSY;
167547    return SQLITE_INTERNAL;
167548  }
167549
167550  pRbu->pgsz = iAmt;
167551  if( pRbu->nFrame==pRbu->nFrameAlloc ){
167552    int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
167553    RbuFrame *aNew;
167554    aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
167555    if( aNew==0 ) return SQLITE_NOMEM;
167556    pRbu->aFrame = aNew;
167557    pRbu->nFrameAlloc = nNew;
167558  }
167559
167560  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
167561  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
167562  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
167563  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
167564  pRbu->nFrame++;
167565  return SQLITE_OK;
167566}
167567
167568/*
167569** Called when a page of data is written to offset iOff of the database
167570** file while the rbu handle is in capture mode. Record the page number
167571** of the page being written in the aFrame[] array.
167572*/
167573static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
167574  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
167575  return SQLITE_OK;
167576}
167577
167578/*
167579** This is called as part of an incremental checkpoint operation. Copy
167580** a single frame of data from the wal file into the database file, as
167581** indicated by the RbuFrame object.
167582*/
167583static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
167584  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
167585  sqlite3_file *pDb = p->pTargetFd->pReal;
167586  i64 iOff;
167587
167588  assert( p->rc==SQLITE_OK );
167589  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
167590  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
167591  if( p->rc ) return;
167592
167593  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
167594  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
167595}
167596
167597
167598/*
167599** Take an EXCLUSIVE lock on the database file.
167600*/
167601static void rbuLockDatabase(sqlite3rbu *p){
167602  sqlite3_file *pReal = p->pTargetFd->pReal;
167603  assert( p->rc==SQLITE_OK );
167604  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
167605  if( p->rc==SQLITE_OK ){
167606    p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
167607  }
167608}
167609
167610#if defined(_WIN32_WCE)
167611static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
167612  int nChar;
167613  LPWSTR zWideFilename;
167614
167615  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
167616  if( nChar==0 ){
167617    return 0;
167618  }
167619  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
167620  if( zWideFilename==0 ){
167621    return 0;
167622  }
167623  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
167624  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
167625                                nChar);
167626  if( nChar==0 ){
167627    sqlite3_free(zWideFilename);
167628    zWideFilename = 0;
167629  }
167630  return zWideFilename;
167631}
167632#endif
167633
167634/*
167635** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
167636** on the database file. This proc moves the *-oal file to the *-wal path,
167637** then reopens the database file (this time in vanilla, non-oal, WAL mode).
167638** If an error occurs, leave an error code and error message in the rbu
167639** handle.
167640*/
167641static void rbuMoveOalFile(sqlite3rbu *p){
167642  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
167643  const char *zMove = zBase;
167644  char *zOal;
167645  char *zWal;
167646
167647  if( rbuIsVacuum(p) ){
167648    zMove = sqlite3_db_filename(p->dbRbu, "main");
167649  }
167650  zOal = sqlite3_mprintf("%s-oal", zMove);
167651  zWal = sqlite3_mprintf("%s-wal", zMove);
167652
167653  assert( p->eStage==RBU_STAGE_MOVE );
167654  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
167655  if( zWal==0 || zOal==0 ){
167656    p->rc = SQLITE_NOMEM;
167657  }else{
167658    /* Move the *-oal file to *-wal. At this point connection p->db is
167659    ** holding a SHARED lock on the target database file (because it is
167660    ** in WAL mode). So no other connection may be writing the db.
167661    **
167662    ** In order to ensure that there are no database readers, an EXCLUSIVE
167663    ** lock is obtained here before the *-oal is moved to *-wal.
167664    */
167665    rbuLockDatabase(p);
167666    if( p->rc==SQLITE_OK ){
167667      rbuFileSuffix3(zBase, zWal);
167668      rbuFileSuffix3(zBase, zOal);
167669
167670      /* Re-open the databases. */
167671      rbuObjIterFinalize(&p->objiter);
167672      sqlite3_close(p->dbRbu);
167673      sqlite3_close(p->dbMain);
167674      p->dbMain = 0;
167675      p->dbRbu = 0;
167676
167677#if defined(_WIN32_WCE)
167678      {
167679        LPWSTR zWideOal;
167680        LPWSTR zWideWal;
167681
167682        zWideOal = rbuWinUtf8ToUnicode(zOal);
167683        if( zWideOal ){
167684          zWideWal = rbuWinUtf8ToUnicode(zWal);
167685          if( zWideWal ){
167686            if( MoveFileW(zWideOal, zWideWal) ){
167687              p->rc = SQLITE_OK;
167688            }else{
167689              p->rc = SQLITE_IOERR;
167690            }
167691            sqlite3_free(zWideWal);
167692          }else{
167693            p->rc = SQLITE_IOERR_NOMEM;
167694          }
167695          sqlite3_free(zWideOal);
167696        }else{
167697          p->rc = SQLITE_IOERR_NOMEM;
167698        }
167699      }
167700#else
167701      p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
167702#endif
167703
167704      if( p->rc==SQLITE_OK ){
167705        rbuOpenDatabase(p);
167706        rbuSetupCheckpoint(p, 0);
167707      }
167708    }
167709  }
167710
167711  sqlite3_free(zWal);
167712  sqlite3_free(zOal);
167713}
167714
167715/*
167716** The SELECT statement iterating through the keys for the current object
167717** (p->objiter.pSelect) currently points to a valid row. This function
167718** determines the type of operation requested by this row and returns
167719** one of the following values to indicate the result:
167720**
167721**     * RBU_INSERT
167722**     * RBU_DELETE
167723**     * RBU_IDX_DELETE
167724**     * RBU_UPDATE
167725**
167726** If RBU_UPDATE is returned, then output variable *pzMask is set to
167727** point to the text value indicating the columns to update.
167728**
167729** If the rbu_control field contains an invalid value, an error code and
167730** message are left in the RBU handle and zero returned.
167731*/
167732static int rbuStepType(sqlite3rbu *p, const char **pzMask){
167733  int iCol = p->objiter.nCol;     /* Index of rbu_control column */
167734  int res = 0;                    /* Return value */
167735
167736  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
167737    case SQLITE_INTEGER: {
167738      int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
167739      switch( iVal ){
167740        case 0: res = RBU_INSERT;     break;
167741        case 1: res = RBU_DELETE;     break;
167742        case 2: res = RBU_REPLACE;    break;
167743        case 3: res = RBU_IDX_DELETE; break;
167744        case 4: res = RBU_IDX_INSERT; break;
167745      }
167746      break;
167747    }
167748
167749    case SQLITE_TEXT: {
167750      const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
167751      if( z==0 ){
167752        p->rc = SQLITE_NOMEM;
167753      }else{
167754        *pzMask = (const char*)z;
167755      }
167756      res = RBU_UPDATE;
167757
167758      break;
167759    }
167760
167761    default:
167762      break;
167763  }
167764
167765  if( res==0 ){
167766    rbuBadControlError(p);
167767  }
167768  return res;
167769}
167770
167771#ifdef SQLITE_DEBUG
167772/*
167773** Assert that column iCol of statement pStmt is named zName.
167774*/
167775static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
167776  const char *zCol = sqlite3_column_name(pStmt, iCol);
167777  assert( 0==sqlite3_stricmp(zName, zCol) );
167778}
167779#else
167780# define assertColumnName(x,y,z)
167781#endif
167782
167783/*
167784** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
167785** RBU_IDX_DELETE. This function performs the work of a single
167786** sqlite3rbu_step() call for the type of operation specified by eType.
167787*/
167788static void rbuStepOneOp(sqlite3rbu *p, int eType){
167789  RbuObjIter *pIter = &p->objiter;
167790  sqlite3_value *pVal;
167791  sqlite3_stmt *pWriter;
167792  int i;
167793
167794  assert( p->rc==SQLITE_OK );
167795  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
167796  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
167797       || eType==RBU_INSERT || eType==RBU_IDX_INSERT
167798  );
167799
167800  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
167801  ** statement below does actually delete a row, nPhaseOneStep will be
167802  ** incremented by the same amount when SQL function rbu_tmp_insert()
167803  ** is invoked by the trigger.  */
167804  if( eType==RBU_DELETE ){
167805    p->nPhaseOneStep -= p->objiter.nIndex;
167806  }
167807
167808  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
167809    pWriter = pIter->pDelete;
167810  }else{
167811    pWriter = pIter->pInsert;
167812  }
167813
167814  for(i=0; i<pIter->nCol; i++){
167815    /* If this is an INSERT into a table b-tree and the table has an
167816    ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
167817    ** to write a NULL into the IPK column. That is not permitted.  */
167818    if( eType==RBU_INSERT
167819     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
167820     && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
167821    ){
167822      p->rc = SQLITE_MISMATCH;
167823      p->zErrmsg = sqlite3_mprintf("datatype mismatch");
167824      return;
167825    }
167826
167827    if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
167828      continue;
167829    }
167830
167831    pVal = sqlite3_column_value(pIter->pSelect, i);
167832    p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
167833    if( p->rc ) return;
167834  }
167835  if( pIter->zIdx==0 ){
167836    if( pIter->eType==RBU_PK_VTAB
167837     || pIter->eType==RBU_PK_NONE
167838     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
167839    ){
167840      /* For a virtual table, or a table with no primary key, the
167841      ** SELECT statement is:
167842      **
167843      **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
167844      **
167845      ** Hence column_value(pIter->nCol+1).
167846      */
167847      assertColumnName(pIter->pSelect, pIter->nCol+1,
167848          rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
167849      );
167850      pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
167851      p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
167852    }
167853  }
167854  if( p->rc==SQLITE_OK ){
167855    sqlite3_step(pWriter);
167856    p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
167857  }
167858}
167859
167860/*
167861** This function does the work for an sqlite3rbu_step() call.
167862**
167863** The object-iterator (p->objiter) currently points to a valid object,
167864** and the input cursor (p->objiter.pSelect) currently points to a valid
167865** input row. Perform whatever processing is required and return.
167866**
167867** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
167868** and message is left in the RBU handle and a copy of the error code
167869** returned.
167870*/
167871static int rbuStep(sqlite3rbu *p){
167872  RbuObjIter *pIter = &p->objiter;
167873  const char *zMask = 0;
167874  int eType = rbuStepType(p, &zMask);
167875
167876  if( eType ){
167877    assert( eType==RBU_INSERT     || eType==RBU_DELETE
167878         || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
167879         || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
167880    );
167881    assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
167882
167883    if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
167884      rbuBadControlError(p);
167885    }
167886    else if( eType==RBU_REPLACE ){
167887      if( pIter->zIdx==0 ){
167888        p->nPhaseOneStep += p->objiter.nIndex;
167889        rbuStepOneOp(p, RBU_DELETE);
167890      }
167891      if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
167892    }
167893    else if( eType!=RBU_UPDATE ){
167894      rbuStepOneOp(p, eType);
167895    }
167896    else{
167897      sqlite3_value *pVal;
167898      sqlite3_stmt *pUpdate = 0;
167899      assert( eType==RBU_UPDATE );
167900      p->nPhaseOneStep -= p->objiter.nIndex;
167901      rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
167902      if( pUpdate ){
167903        int i;
167904        for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
167905          char c = zMask[pIter->aiSrcOrder[i]];
167906          pVal = sqlite3_column_value(pIter->pSelect, i);
167907          if( pIter->abTblPk[i] || c!='.' ){
167908            p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
167909          }
167910        }
167911        if( p->rc==SQLITE_OK
167912         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
167913        ){
167914          /* Bind the rbu_rowid value to column _rowid_ */
167915          assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
167916          pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
167917          p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
167918        }
167919        if( p->rc==SQLITE_OK ){
167920          sqlite3_step(pUpdate);
167921          p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
167922        }
167923      }
167924    }
167925  }
167926  return p->rc;
167927}
167928
167929/*
167930** Increment the schema cookie of the main database opened by p->dbMain.
167931**
167932** Or, if this is an RBU vacuum, set the schema cookie of the main db
167933** opened by p->dbMain to one more than the schema cookie of the main
167934** db opened by p->dbRbu.
167935*/
167936static void rbuIncrSchemaCookie(sqlite3rbu *p){
167937  if( p->rc==SQLITE_OK ){
167938    sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
167939    int iCookie = 1000000;
167940    sqlite3_stmt *pStmt;
167941
167942    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
167943        "PRAGMA schema_version"
167944    );
167945    if( p->rc==SQLITE_OK ){
167946      /* Coverage: it may be that this sqlite3_step() cannot fail. There
167947      ** is already a transaction open, so the prepared statement cannot
167948      ** throw an SQLITE_SCHEMA exception. The only database page the
167949      ** statement reads is page 1, which is guaranteed to be in the cache.
167950      ** And no memory allocations are required.  */
167951      if( SQLITE_ROW==sqlite3_step(pStmt) ){
167952        iCookie = sqlite3_column_int(pStmt, 0);
167953      }
167954      rbuFinalize(p, pStmt);
167955    }
167956    if( p->rc==SQLITE_OK ){
167957      rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
167958    }
167959  }
167960}
167961
167962/*
167963** Update the contents of the rbu_state table within the rbu database. The
167964** value stored in the RBU_STATE_STAGE column is eStage. All other values
167965** are determined by inspecting the rbu handle passed as the first argument.
167966*/
167967static void rbuSaveState(sqlite3rbu *p, int eStage){
167968  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
167969    sqlite3_stmt *pInsert = 0;
167970    rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
167971    int rc;
167972
167973    assert( p->zErrmsg==0 );
167974    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
167975        sqlite3_mprintf(
167976          "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
167977          "(%d, %d), "
167978          "(%d, %Q), "
167979          "(%d, %Q), "
167980          "(%d, %d), "
167981          "(%d, %d), "
167982          "(%d, %lld), "
167983          "(%d, %lld), "
167984          "(%d, %lld), "
167985          "(%d, %lld) ",
167986          p->zStateDb,
167987          RBU_STATE_STAGE, eStage,
167988          RBU_STATE_TBL, p->objiter.zTbl,
167989          RBU_STATE_IDX, p->objiter.zIdx,
167990          RBU_STATE_ROW, p->nStep,
167991          RBU_STATE_PROGRESS, p->nProgress,
167992          RBU_STATE_CKPT, p->iWalCksum,
167993          RBU_STATE_COOKIE, (i64)pFd->iCookie,
167994          RBU_STATE_OALSZ, p->iOalSz,
167995          RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
167996      )
167997    );
167998    assert( pInsert==0 || rc==SQLITE_OK );
167999
168000    if( rc==SQLITE_OK ){
168001      sqlite3_step(pInsert);
168002      rc = sqlite3_finalize(pInsert);
168003    }
168004    if( rc!=SQLITE_OK ) p->rc = rc;
168005  }
168006}
168007
168008
168009/*
168010** The second argument passed to this function is the name of a PRAGMA
168011** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
168012** This function executes the following on sqlite3rbu.dbRbu:
168013**
168014**   "PRAGMA main.$zPragma"
168015**
168016** where $zPragma is the string passed as the second argument, then
168017** on sqlite3rbu.dbMain:
168018**
168019**   "PRAGMA main.$zPragma = $val"
168020**
168021** where $val is the value returned by the first PRAGMA invocation.
168022**
168023** In short, it copies the value  of the specified PRAGMA setting from
168024** dbRbu to dbMain.
168025*/
168026static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
168027  if( p->rc==SQLITE_OK ){
168028    sqlite3_stmt *pPragma = 0;
168029    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
168030        sqlite3_mprintf("PRAGMA main.%s", zPragma)
168031    );
168032    if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
168033      p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
168034          zPragma, sqlite3_column_int(pPragma, 0)
168035      );
168036    }
168037    rbuFinalize(p, pPragma);
168038  }
168039}
168040
168041/*
168042** The RBU handle passed as the only argument has just been opened and
168043** the state database is empty. If this RBU handle was opened for an
168044** RBU vacuum operation, create the schema in the target db.
168045*/
168046static void rbuCreateTargetSchema(sqlite3rbu *p){
168047  sqlite3_stmt *pSql = 0;
168048  sqlite3_stmt *pInsert = 0;
168049
168050  assert( rbuIsVacuum(p) );
168051  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
168052  if( p->rc==SQLITE_OK ){
168053    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
168054      "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
168055      " AND name!='sqlite_sequence' "
168056      " ORDER BY type DESC"
168057    );
168058  }
168059
168060  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
168061    const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
168062    p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
168063  }
168064  rbuFinalize(p, pSql);
168065  if( p->rc!=SQLITE_OK ) return;
168066
168067  if( p->rc==SQLITE_OK ){
168068    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
168069        "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
168070    );
168071  }
168072
168073  if( p->rc==SQLITE_OK ){
168074    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
168075        "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
168076    );
168077  }
168078
168079  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
168080    int i;
168081    for(i=0; i<5; i++){
168082      sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
168083    }
168084    sqlite3_step(pInsert);
168085    p->rc = sqlite3_reset(pInsert);
168086  }
168087  if( p->rc==SQLITE_OK ){
168088    p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
168089  }
168090
168091  rbuFinalize(p, pSql);
168092  rbuFinalize(p, pInsert);
168093}
168094
168095/*
168096** Step the RBU object.
168097*/
168098SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
168099  if( p ){
168100    switch( p->eStage ){
168101      case RBU_STAGE_OAL: {
168102        RbuObjIter *pIter = &p->objiter;
168103
168104        /* If this is an RBU vacuum operation and the state table was empty
168105        ** when this handle was opened, create the target database schema. */
168106        if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
168107          rbuCreateTargetSchema(p);
168108          rbuCopyPragma(p, "user_version");
168109          rbuCopyPragma(p, "application_id");
168110        }
168111
168112        while( p->rc==SQLITE_OK && pIter->zTbl ){
168113
168114          if( pIter->bCleanup ){
168115            /* Clean up the rbu_tmp_xxx table for the previous table. It
168116            ** cannot be dropped as there are currently active SQL statements.
168117            ** But the contents can be deleted.  */
168118            if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
168119              rbuMPrintfExec(p, p->dbRbu,
168120                  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
168121              );
168122            }
168123          }else{
168124            rbuObjIterPrepareAll(p, pIter, 0);
168125
168126            /* Advance to the next row to process. */
168127            if( p->rc==SQLITE_OK ){
168128              int rc = sqlite3_step(pIter->pSelect);
168129              if( rc==SQLITE_ROW ){
168130                p->nProgress++;
168131                p->nStep++;
168132                return rbuStep(p);
168133              }
168134              p->rc = sqlite3_reset(pIter->pSelect);
168135              p->nStep = 0;
168136            }
168137          }
168138
168139          rbuObjIterNext(p, pIter);
168140        }
168141
168142        if( p->rc==SQLITE_OK ){
168143          assert( pIter->zTbl==0 );
168144          rbuSaveState(p, RBU_STAGE_MOVE);
168145          rbuIncrSchemaCookie(p);
168146          if( p->rc==SQLITE_OK ){
168147            p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
168148          }
168149          if( p->rc==SQLITE_OK ){
168150            p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
168151          }
168152          p->eStage = RBU_STAGE_MOVE;
168153        }
168154        break;
168155      }
168156
168157      case RBU_STAGE_MOVE: {
168158        if( p->rc==SQLITE_OK ){
168159          rbuMoveOalFile(p);
168160          p->nProgress++;
168161        }
168162        break;
168163      }
168164
168165      case RBU_STAGE_CKPT: {
168166        if( p->rc==SQLITE_OK ){
168167          if( p->nStep>=p->nFrame ){
168168            sqlite3_file *pDb = p->pTargetFd->pReal;
168169
168170            /* Sync the db file */
168171            p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
168172
168173            /* Update nBackfill */
168174            if( p->rc==SQLITE_OK ){
168175              void volatile *ptr;
168176              p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
168177              if( p->rc==SQLITE_OK ){
168178                ((u32 volatile*)ptr)[24] = p->iMaxFrame;
168179              }
168180            }
168181
168182            if( p->rc==SQLITE_OK ){
168183              p->eStage = RBU_STAGE_DONE;
168184              p->rc = SQLITE_DONE;
168185            }
168186          }else{
168187            RbuFrame *pFrame = &p->aFrame[p->nStep];
168188            rbuCheckpointFrame(p, pFrame);
168189            p->nStep++;
168190          }
168191          p->nProgress++;
168192        }
168193        break;
168194      }
168195
168196      default:
168197        break;
168198    }
168199    return p->rc;
168200  }else{
168201    return SQLITE_NOMEM;
168202  }
168203}
168204
168205/*
168206** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
168207** otherwise. Either or both argument may be NULL. Two NULL values are
168208** considered equal, and NULL is considered distinct from all other values.
168209*/
168210static int rbuStrCompare(const char *z1, const char *z2){
168211  if( z1==0 && z2==0 ) return 0;
168212  if( z1==0 || z2==0 ) return 1;
168213  return (sqlite3_stricmp(z1, z2)!=0);
168214}
168215
168216/*
168217** This function is called as part of sqlite3rbu_open() when initializing
168218** an rbu handle in OAL stage. If the rbu update has not started (i.e.
168219** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
168220** things so that the next call to sqlite3rbu_step() continues on from
168221** where the previous rbu handle left off.
168222**
168223** If an error occurs, an error code and error message are left in the
168224** rbu handle passed as the first argument.
168225*/
168226static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
168227  assert( p->rc==SQLITE_OK );
168228  if( pState->zTbl ){
168229    RbuObjIter *pIter = &p->objiter;
168230    int rc = SQLITE_OK;
168231
168232    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
168233       || rbuStrCompare(pIter->zIdx, pState->zIdx)
168234       || rbuStrCompare(pIter->zTbl, pState->zTbl)
168235    )){
168236      rc = rbuObjIterNext(p, pIter);
168237    }
168238
168239    if( rc==SQLITE_OK && !pIter->zTbl ){
168240      rc = SQLITE_ERROR;
168241      p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
168242    }
168243
168244    if( rc==SQLITE_OK ){
168245      p->nStep = pState->nRow;
168246      rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
168247    }
168248
168249    p->rc = rc;
168250  }
168251}
168252
168253/*
168254** If there is a "*-oal" file in the file-system corresponding to the
168255** target database in the file-system, delete it. If an error occurs,
168256** leave an error code and error message in the rbu handle.
168257*/
168258static void rbuDeleteOalFile(sqlite3rbu *p){
168259  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
168260  if( zOal ){
168261    sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
168262    assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
168263    pVfs->xDelete(pVfs, zOal, 0);
168264    sqlite3_free(zOal);
168265  }
168266}
168267
168268/*
168269** Allocate a private rbu VFS for the rbu handle passed as the only
168270** argument. This VFS will be used unless the call to sqlite3rbu_open()
168271** specified a URI with a vfs=? option in place of a target database
168272** file name.
168273*/
168274static void rbuCreateVfs(sqlite3rbu *p){
168275  int rnd;
168276  char zRnd[64];
168277
168278  assert( p->rc==SQLITE_OK );
168279  sqlite3_randomness(sizeof(int), (void*)&rnd);
168280  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
168281  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
168282  if( p->rc==SQLITE_OK ){
168283    sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
168284    assert( pVfs );
168285    p->zVfsName = pVfs->zName;
168286  }
168287}
168288
168289/*
168290** Destroy the private VFS created for the rbu handle passed as the only
168291** argument by an earlier call to rbuCreateVfs().
168292*/
168293static void rbuDeleteVfs(sqlite3rbu *p){
168294  if( p->zVfsName ){
168295    sqlite3rbu_destroy_vfs(p->zVfsName);
168296    p->zVfsName = 0;
168297  }
168298}
168299
168300/*
168301** This user-defined SQL function is invoked with a single argument - the
168302** name of a table expected to appear in the target database. It returns
168303** the number of auxilliary indexes on the table.
168304*/
168305static void rbuIndexCntFunc(
168306  sqlite3_context *pCtx,
168307  int nVal,
168308  sqlite3_value **apVal
168309){
168310  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
168311  sqlite3_stmt *pStmt = 0;
168312  char *zErrmsg = 0;
168313  int rc;
168314
168315  assert( nVal==1 );
168316
168317  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
168318      sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
168319        "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
168320  );
168321  if( rc!=SQLITE_OK ){
168322    sqlite3_result_error(pCtx, zErrmsg, -1);
168323  }else{
168324    int nIndex = 0;
168325    if( SQLITE_ROW==sqlite3_step(pStmt) ){
168326      nIndex = sqlite3_column_int(pStmt, 0);
168327    }
168328    rc = sqlite3_finalize(pStmt);
168329    if( rc==SQLITE_OK ){
168330      sqlite3_result_int(pCtx, nIndex);
168331    }else{
168332      sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
168333    }
168334  }
168335
168336  sqlite3_free(zErrmsg);
168337}
168338
168339/*
168340** If the RBU database contains the rbu_count table, use it to initialize
168341** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
168342** is assumed to contain the same columns as:
168343**
168344**   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
168345**
168346** There should be one row in the table for each data_xxx table in the
168347** database. The 'tbl' column should contain the name of a data_xxx table,
168348** and the cnt column the number of rows it contains.
168349**
168350** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
168351** for all rows in the rbu_count table, where nIndex is the number of
168352** indexes on the corresponding target database table.
168353*/
168354static void rbuInitPhaseOneSteps(sqlite3rbu *p){
168355  if( p->rc==SQLITE_OK ){
168356    sqlite3_stmt *pStmt = 0;
168357    int bExists = 0;                /* True if rbu_count exists */
168358
168359    p->nPhaseOneStep = -1;
168360
168361    p->rc = sqlite3_create_function(p->dbRbu,
168362        "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
168363    );
168364
168365    /* Check for the rbu_count table. If it does not exist, or if an error
168366    ** occurs, nPhaseOneStep will be left set to -1. */
168367    if( p->rc==SQLITE_OK ){
168368      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168369          "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
168370      );
168371    }
168372    if( p->rc==SQLITE_OK ){
168373      if( SQLITE_ROW==sqlite3_step(pStmt) ){
168374        bExists = 1;
168375      }
168376      p->rc = sqlite3_finalize(pStmt);
168377    }
168378
168379    if( p->rc==SQLITE_OK && bExists ){
168380      p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168381          "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
168382          "FROM rbu_count"
168383      );
168384      if( p->rc==SQLITE_OK ){
168385        if( SQLITE_ROW==sqlite3_step(pStmt) ){
168386          p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
168387        }
168388        p->rc = sqlite3_finalize(pStmt);
168389      }
168390    }
168391  }
168392}
168393
168394
168395static sqlite3rbu *openRbuHandle(
168396  const char *zTarget,
168397  const char *zRbu,
168398  const char *zState
168399){
168400  sqlite3rbu *p;
168401  size_t nTarget = zTarget ? strlen(zTarget) : 0;
168402  size_t nRbu = strlen(zRbu);
168403  size_t nState = zState ? strlen(zState) : 0;
168404  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
168405
168406  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
168407  if( p ){
168408    RbuState *pState = 0;
168409
168410    /* Create the custom VFS. */
168411    memset(p, 0, sizeof(sqlite3rbu));
168412    rbuCreateVfs(p);
168413
168414    /* Open the target, RBU and state databases */
168415    if( p->rc==SQLITE_OK ){
168416      char *pCsr = (char*)&p[1];
168417      if( zTarget ){
168418        p->zTarget = pCsr;
168419        memcpy(p->zTarget, zTarget, nTarget+1);
168420        pCsr += nTarget+1;
168421      }
168422      p->zRbu = pCsr;
168423      memcpy(p->zRbu, zRbu, nRbu+1);
168424      pCsr += nRbu+1;
168425      if( zState ){
168426        p->zState = pCsr;
168427        memcpy(p->zState, zState, nState+1);
168428      }
168429      rbuOpenDatabase(p);
168430    }
168431
168432    if( p->rc==SQLITE_OK ){
168433      pState = rbuLoadState(p);
168434      assert( pState || p->rc!=SQLITE_OK );
168435      if( p->rc==SQLITE_OK ){
168436
168437        if( pState->eStage==0 ){
168438          rbuDeleteOalFile(p);
168439          rbuInitPhaseOneSteps(p);
168440          p->eStage = RBU_STAGE_OAL;
168441        }else{
168442          p->eStage = pState->eStage;
168443          p->nPhaseOneStep = pState->nPhaseOneStep;
168444        }
168445        p->nProgress = pState->nProgress;
168446        p->iOalSz = pState->iOalSz;
168447      }
168448    }
168449    assert( p->rc!=SQLITE_OK || p->eStage!=0 );
168450
168451    if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
168452      if( p->eStage==RBU_STAGE_OAL ){
168453        p->rc = SQLITE_ERROR;
168454        p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
168455      }else if( p->eStage==RBU_STAGE_MOVE ){
168456        p->eStage = RBU_STAGE_CKPT;
168457        p->nStep = 0;
168458      }
168459    }
168460
168461    if( p->rc==SQLITE_OK
168462     && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
168463     && pState->eStage!=0
168464    ){
168465      rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
168466      if( pFd->iCookie!=pState->iCookie ){
168467        /* At this point (pTargetFd->iCookie) contains the value of the
168468        ** change-counter cookie (the thing that gets incremented when a
168469        ** transaction is committed in rollback mode) currently stored on
168470        ** page 1 of the database file. */
168471        p->rc = SQLITE_BUSY;
168472        p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
168473            (rbuIsVacuum(p) ? "vacuum" : "update")
168474        );
168475      }
168476    }
168477
168478    if( p->rc==SQLITE_OK ){
168479      if( p->eStage==RBU_STAGE_OAL ){
168480        sqlite3 *db = p->dbMain;
168481        p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
168482
168483        /* Point the object iterator at the first object */
168484        if( p->rc==SQLITE_OK ){
168485          p->rc = rbuObjIterFirst(p, &p->objiter);
168486        }
168487
168488        /* If the RBU database contains no data_xxx tables, declare the RBU
168489        ** update finished.  */
168490        if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
168491          p->rc = SQLITE_DONE;
168492          p->eStage = RBU_STAGE_DONE;
168493        }else{
168494          if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
168495            rbuCopyPragma(p, "page_size");
168496            rbuCopyPragma(p, "auto_vacuum");
168497          }
168498
168499          /* Open transactions both databases. The *-oal file is opened or
168500          ** created at this point. */
168501          if( p->rc==SQLITE_OK ){
168502            p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
168503          }
168504
168505          /* Check if the main database is a zipvfs db. If it is, set the upper
168506          ** level pager to use "journal_mode=off". This prevents it from
168507          ** generating a large journal using a temp file.  */
168508          if( p->rc==SQLITE_OK ){
168509            int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
168510            if( frc==SQLITE_OK ){
168511              p->rc = sqlite3_exec(
168512                db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
168513            }
168514          }
168515
168516          if( p->rc==SQLITE_OK ){
168517            rbuSetupOal(p, pState);
168518          }
168519        }
168520      }else if( p->eStage==RBU_STAGE_MOVE ){
168521        /* no-op */
168522      }else if( p->eStage==RBU_STAGE_CKPT ){
168523        rbuSetupCheckpoint(p, pState);
168524      }else if( p->eStage==RBU_STAGE_DONE ){
168525        p->rc = SQLITE_DONE;
168526      }else{
168527        p->rc = SQLITE_CORRUPT;
168528      }
168529    }
168530
168531    rbuFreeState(pState);
168532  }
168533
168534  return p;
168535}
168536
168537/*
168538** Open and return a new RBU handle.
168539*/
168540SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
168541  const char *zTarget,
168542  const char *zRbu,
168543  const char *zState
168544){
168545  /* TODO: Check that zTarget and zRbu are non-NULL */
168546  return openRbuHandle(zTarget, zRbu, zState);
168547}
168548
168549/*
168550** Open a handle to begin or resume an RBU VACUUM operation.
168551*/
168552SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
168553  const char *zTarget,
168554  const char *zState
168555){
168556  /* TODO: Check that both arguments are non-NULL */
168557  return openRbuHandle(0, zTarget, zState);
168558}
168559
168560/*
168561** Return the database handle used by pRbu.
168562*/
168563SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
168564  sqlite3 *db = 0;
168565  if( pRbu ){
168566    db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
168567  }
168568  return db;
168569}
168570
168571
168572/*
168573** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
168574** then edit any error message string so as to remove all occurrences of
168575** the pattern "rbu_imp_[0-9]*".
168576*/
168577static void rbuEditErrmsg(sqlite3rbu *p){
168578  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
168579    unsigned int i;
168580    size_t nErrmsg = strlen(p->zErrmsg);
168581    for(i=0; i<(nErrmsg-8); i++){
168582      if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
168583        int nDel = 8;
168584        while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
168585        memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
168586        nErrmsg -= nDel;
168587      }
168588    }
168589  }
168590}
168591
168592/*
168593** Close the RBU handle.
168594*/
168595SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
168596  int rc;
168597  if( p ){
168598
168599    /* Commit the transaction to the *-oal file. */
168600    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
168601      p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
168602    }
168603
168604    rbuSaveState(p, p->eStage);
168605
168606    if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
168607      p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
168608    }
168609
168610    /* Close any open statement handles. */
168611    rbuObjIterFinalize(&p->objiter);
168612
168613    /* If this is an RBU vacuum handle and the vacuum has either finished
168614    ** successfully or encountered an error, delete the contents of the
168615    ** state table. This causes the next call to sqlite3rbu_vacuum()
168616    ** specifying the current target and state databases to start a new
168617    ** vacuum from scratch.  */
168618    if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
168619      int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
168620      if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
168621    }
168622
168623    /* Close the open database handle and VFS object. */
168624    sqlite3_close(p->dbRbu);
168625    sqlite3_close(p->dbMain);
168626    rbuDeleteVfs(p);
168627    sqlite3_free(p->aBuf);
168628    sqlite3_free(p->aFrame);
168629
168630    rbuEditErrmsg(p);
168631    rc = p->rc;
168632    *pzErrmsg = p->zErrmsg;
168633    sqlite3_free(p);
168634  }else{
168635    rc = SQLITE_NOMEM;
168636    *pzErrmsg = 0;
168637  }
168638  return rc;
168639}
168640
168641/*
168642** Return the total number of key-value operations (inserts, deletes or
168643** updates) that have been performed on the target database since the
168644** current RBU update was started.
168645*/
168646SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
168647  return pRbu->nProgress;
168648}
168649
168650/*
168651** Return permyriadage progress indications for the two main stages of
168652** an RBU update.
168653*/
168654SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
168655  const int MAX_PROGRESS = 10000;
168656  switch( p->eStage ){
168657    case RBU_STAGE_OAL:
168658      if( p->nPhaseOneStep>0 ){
168659        *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
168660      }else{
168661        *pnOne = -1;
168662      }
168663      *pnTwo = 0;
168664      break;
168665
168666    case RBU_STAGE_MOVE:
168667      *pnOne = MAX_PROGRESS;
168668      *pnTwo = 0;
168669      break;
168670
168671    case RBU_STAGE_CKPT:
168672      *pnOne = MAX_PROGRESS;
168673      *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
168674      break;
168675
168676    case RBU_STAGE_DONE:
168677      *pnOne = MAX_PROGRESS;
168678      *pnTwo = MAX_PROGRESS;
168679      break;
168680
168681    default:
168682      assert( 0 );
168683  }
168684}
168685
168686/*
168687** Return the current state of the RBU vacuum or update operation.
168688*/
168689SQLITE_API int SQLITE_STDCALL sqlite3rbu_state(sqlite3rbu *p){
168690  int aRes[] = {
168691    0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
168692    0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
168693  };
168694
168695  assert( RBU_STAGE_OAL==1 );
168696  assert( RBU_STAGE_MOVE==2 );
168697  assert( RBU_STAGE_CKPT==4 );
168698  assert( RBU_STAGE_DONE==5 );
168699  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
168700  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
168701  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
168702  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
168703
168704  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
168705    return SQLITE_RBU_STATE_ERROR;
168706  }else{
168707    assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
168708    assert( p->eStage==RBU_STAGE_OAL
168709         || p->eStage==RBU_STAGE_MOVE
168710         || p->eStage==RBU_STAGE_CKPT
168711         || p->eStage==RBU_STAGE_DONE
168712    );
168713    return aRes[p->eStage];
168714  }
168715}
168716
168717SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
168718  int rc = p->rc;
168719  if( rc==SQLITE_DONE ) return SQLITE_OK;
168720
168721  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
168722  if( p->eStage==RBU_STAGE_OAL ){
168723    assert( rc!=SQLITE_DONE );
168724    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
168725  }
168726
168727  p->rc = rc;
168728  rbuSaveState(p, p->eStage);
168729  rc = p->rc;
168730
168731  if( p->eStage==RBU_STAGE_OAL ){
168732    assert( rc!=SQLITE_DONE );
168733    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
168734    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
168735    if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
168736  }
168737
168738  p->rc = rc;
168739  return rc;
168740}
168741
168742/**************************************************************************
168743** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
168744** of a standard VFS in the following ways:
168745**
168746** 1. Whenever the first page of a main database file is read or
168747**    written, the value of the change-counter cookie is stored in
168748**    rbu_file.iCookie. Similarly, the value of the "write-version"
168749**    database header field is stored in rbu_file.iWriteVer. This ensures
168750**    that the values are always trustworthy within an open transaction.
168751**
168752** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
168753**    member variable of the associated database file descriptor is set
168754**    to point to the new file. A mutex protected linked list of all main
168755**    db fds opened using a particular RBU VFS is maintained at
168756**    rbu_vfs.pMain to facilitate this.
168757**
168758** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
168759**    object can be marked as the target database of an RBU update. This
168760**    turns on the following extra special behaviour:
168761**
168762** 3a. If xAccess() is called to check if there exists a *-wal file
168763**     associated with an RBU target database currently in RBU_STAGE_OAL
168764**     stage (preparing the *-oal file), the following special handling
168765**     applies:
168766**
168767**      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
168768**        target database may not be in wal mode already.
168769**
168770**      * if the *-wal file does not exist, set the output parameter to
168771**        non-zero (to tell SQLite that it does exist) anyway.
168772**
168773**     Then, when xOpen() is called to open the *-wal file associated with
168774**     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
168775**     file, the rbu vfs opens the corresponding *-oal file instead.
168776**
168777** 3b. The *-shm pages returned by xShmMap() for a target db file in
168778**     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
168779**     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
168780**     are no-ops on target database files in RBU_STAGE_OAL mode. This is
168781**     because assert() statements in some VFS implementations fail if
168782**     xShmLock() is called before xShmMap().
168783**
168784** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
168785**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
168786**     fails with an SQLITE_BUSY error. This is to stop RBU connections
168787**     from automatically checkpointing a *-wal (or *-oal) file from within
168788**     sqlite3_close().
168789**
168790** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
168791**     all xWrite() calls on the target database file perform no IO.
168792**     Instead the frame and page numbers that would be read and written
168793**     are recorded. Additionally, successful attempts to obtain exclusive
168794**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
168795**     database file are recorded. xShmLock() calls to unlock the same
168796**     locks are no-ops (so that once obtained, these locks are never
168797**     relinquished). Finally, calls to xSync() on the target database
168798**     file fail with SQLITE_INTERNAL errors.
168799*/
168800
168801static void rbuUnlockShm(rbu_file *p){
168802  if( p->pRbu ){
168803    int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
168804    int i;
168805    for(i=0; i<SQLITE_SHM_NLOCK;i++){
168806      if( (1<<i) & p->pRbu->mLock ){
168807        xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
168808      }
168809    }
168810    p->pRbu->mLock = 0;
168811  }
168812}
168813
168814/*
168815** Close an rbu file.
168816*/
168817static int rbuVfsClose(sqlite3_file *pFile){
168818  rbu_file *p = (rbu_file*)pFile;
168819  int rc;
168820  int i;
168821
168822  /* Free the contents of the apShm[] array. And the array itself. */
168823  for(i=0; i<p->nShm; i++){
168824    sqlite3_free(p->apShm[i]);
168825  }
168826  sqlite3_free(p->apShm);
168827  p->apShm = 0;
168828  sqlite3_free(p->zDel);
168829
168830  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
168831    rbu_file **pp;
168832    sqlite3_mutex_enter(p->pRbuVfs->mutex);
168833    for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
168834    *pp = p->pMainNext;
168835    sqlite3_mutex_leave(p->pRbuVfs->mutex);
168836    rbuUnlockShm(p);
168837    p->pReal->pMethods->xShmUnmap(p->pReal, 0);
168838  }
168839
168840  /* Close the underlying file handle */
168841  rc = p->pReal->pMethods->xClose(p->pReal);
168842  return rc;
168843}
168844
168845
168846/*
168847** Read and return an unsigned 32-bit big-endian integer from the buffer
168848** passed as the only argument.
168849*/
168850static u32 rbuGetU32(u8 *aBuf){
168851  return ((u32)aBuf[0] << 24)
168852       + ((u32)aBuf[1] << 16)
168853       + ((u32)aBuf[2] <<  8)
168854       + ((u32)aBuf[3]);
168855}
168856
168857/*
168858** Write an unsigned 32-bit value in big-endian format to the supplied
168859** buffer.
168860*/
168861static void rbuPutU32(u8 *aBuf, u32 iVal){
168862  aBuf[0] = (iVal >> 24) & 0xFF;
168863  aBuf[1] = (iVal >> 16) & 0xFF;
168864  aBuf[2] = (iVal >>  8) & 0xFF;
168865  aBuf[3] = (iVal >>  0) & 0xFF;
168866}
168867
168868static void rbuPutU16(u8 *aBuf, u16 iVal){
168869  aBuf[0] = (iVal >>  8) & 0xFF;
168870  aBuf[1] = (iVal >>  0) & 0xFF;
168871}
168872
168873/*
168874** Read data from an rbuVfs-file.
168875*/
168876static int rbuVfsRead(
168877  sqlite3_file *pFile,
168878  void *zBuf,
168879  int iAmt,
168880  sqlite_int64 iOfst
168881){
168882  rbu_file *p = (rbu_file*)pFile;
168883  sqlite3rbu *pRbu = p->pRbu;
168884  int rc;
168885
168886  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
168887    assert( p->openFlags & SQLITE_OPEN_WAL );
168888    rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
168889  }else{
168890    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
168891     && (p->openFlags & SQLITE_OPEN_WAL)
168892     && iOfst>=pRbu->iOalSz
168893    ){
168894      rc = SQLITE_OK;
168895      memset(zBuf, 0, iAmt);
168896    }else{
168897      rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
168898#if 1
168899      /* If this is being called to read the first page of the target
168900      ** database as part of an rbu vacuum operation, synthesize the
168901      ** contents of the first page if it does not yet exist. Otherwise,
168902      ** SQLite will not check for a *-wal file.  */
168903      if( pRbu && rbuIsVacuum(pRbu)
168904          && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
168905          && (p->openFlags & SQLITE_OPEN_MAIN_DB)
168906          && pRbu->rc==SQLITE_OK
168907      ){
168908        sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
168909        rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
168910        if( rc==SQLITE_OK ){
168911          u8 *aBuf = (u8*)zBuf;
168912          u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
168913          rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
168914          rbuPutU32(&aBuf[36], 0);          /* number of free pages */
168915          rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
168916          rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
168917          rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
168918
168919          if( iAmt>100 ){
168920            memset(&aBuf[100], 0, iAmt-100);
168921            rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
168922            aBuf[100] = 0x0D;
168923          }
168924        }
168925      }
168926#endif
168927    }
168928    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
168929      /* These look like magic numbers. But they are stable, as they are part
168930       ** of the definition of the SQLite file format, which may not change. */
168931      u8 *pBuf = (u8*)zBuf;
168932      p->iCookie = rbuGetU32(&pBuf[24]);
168933      p->iWriteVer = pBuf[19];
168934    }
168935  }
168936  return rc;
168937}
168938
168939/*
168940** Write data to an rbuVfs-file.
168941*/
168942static int rbuVfsWrite(
168943  sqlite3_file *pFile,
168944  const void *zBuf,
168945  int iAmt,
168946  sqlite_int64 iOfst
168947){
168948  rbu_file *p = (rbu_file*)pFile;
168949  sqlite3rbu *pRbu = p->pRbu;
168950  int rc;
168951
168952  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
168953    assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
168954    rc = rbuCaptureDbWrite(p->pRbu, iOfst);
168955  }else{
168956    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
168957     && (p->openFlags & SQLITE_OPEN_WAL)
168958     && iOfst>=pRbu->iOalSz
168959    ){
168960      pRbu->iOalSz = iAmt + iOfst;
168961    }
168962    rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
168963    if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
168964      /* These look like magic numbers. But they are stable, as they are part
168965      ** of the definition of the SQLite file format, which may not change. */
168966      u8 *pBuf = (u8*)zBuf;
168967      p->iCookie = rbuGetU32(&pBuf[24]);
168968      p->iWriteVer = pBuf[19];
168969    }
168970  }
168971  return rc;
168972}
168973
168974/*
168975** Truncate an rbuVfs-file.
168976*/
168977static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
168978  rbu_file *p = (rbu_file*)pFile;
168979  return p->pReal->pMethods->xTruncate(p->pReal, size);
168980}
168981
168982/*
168983** Sync an rbuVfs-file.
168984*/
168985static int rbuVfsSync(sqlite3_file *pFile, int flags){
168986  rbu_file *p = (rbu_file *)pFile;
168987  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
168988    if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
168989      return SQLITE_INTERNAL;
168990    }
168991    return SQLITE_OK;
168992  }
168993  return p->pReal->pMethods->xSync(p->pReal, flags);
168994}
168995
168996/*
168997** Return the current file-size of an rbuVfs-file.
168998*/
168999static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
169000  rbu_file *p = (rbu_file *)pFile;
169001  int rc;
169002  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
169003
169004  /* If this is an RBU vacuum operation and this is the target database,
169005  ** pretend that it has at least one page. Otherwise, SQLite will not
169006  ** check for the existance of a *-wal file. rbuVfsRead() contains
169007  ** similar logic.  */
169008  if( rc==SQLITE_OK && *pSize==0
169009   && p->pRbu && rbuIsVacuum(p->pRbu)
169010   && (p->openFlags & SQLITE_OPEN_MAIN_DB)
169011  ){
169012    *pSize = 1024;
169013  }
169014  return rc;
169015}
169016
169017/*
169018** Lock an rbuVfs-file.
169019*/
169020static int rbuVfsLock(sqlite3_file *pFile, int eLock){
169021  rbu_file *p = (rbu_file*)pFile;
169022  sqlite3rbu *pRbu = p->pRbu;
169023  int rc = SQLITE_OK;
169024
169025  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169026  if( eLock==SQLITE_LOCK_EXCLUSIVE
169027   && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
169028  ){
169029    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
169030    ** prevents it from checkpointing the database from sqlite3_close(). */
169031    rc = SQLITE_BUSY;
169032  }else{
169033    rc = p->pReal->pMethods->xLock(p->pReal, eLock);
169034  }
169035
169036  return rc;
169037}
169038
169039/*
169040** Unlock an rbuVfs-file.
169041*/
169042static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
169043  rbu_file *p = (rbu_file *)pFile;
169044  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
169045}
169046
169047/*
169048** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
169049*/
169050static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
169051  rbu_file *p = (rbu_file *)pFile;
169052  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
169053}
169054
169055/*
169056** File control method. For custom operations on an rbuVfs-file.
169057*/
169058static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
169059  rbu_file *p = (rbu_file *)pFile;
169060  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
169061  int rc;
169062
169063  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
169064       || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
169065  );
169066  if( op==SQLITE_FCNTL_RBU ){
169067    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
169068
169069    /* First try to find another RBU vfs lower down in the vfs stack. If
169070    ** one is found, this vfs will operate in pass-through mode. The lower
169071    ** level vfs will do the special RBU handling.  */
169072    rc = xControl(p->pReal, op, pArg);
169073
169074    if( rc==SQLITE_NOTFOUND ){
169075      /* Now search for a zipvfs instance lower down in the VFS stack. If
169076      ** one is found, this is an error.  */
169077      void *dummy = 0;
169078      rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
169079      if( rc==SQLITE_OK ){
169080        rc = SQLITE_ERROR;
169081        pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
169082      }else if( rc==SQLITE_NOTFOUND ){
169083        pRbu->pTargetFd = p;
169084        p->pRbu = pRbu;
169085        if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
169086        rc = SQLITE_OK;
169087      }
169088    }
169089    return rc;
169090  }
169091  else if( op==SQLITE_FCNTL_RBUCNT ){
169092    sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
169093    pRbu->nRbu++;
169094    pRbu->pRbuFd = p;
169095    p->bNolock = 1;
169096  }
169097
169098  rc = xControl(p->pReal, op, pArg);
169099  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
169100    rbu_vfs *pRbuVfs = p->pRbuVfs;
169101    char *zIn = *(char**)pArg;
169102    char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
169103    *(char**)pArg = zOut;
169104    if( zOut==0 ) rc = SQLITE_NOMEM;
169105  }
169106
169107  return rc;
169108}
169109
169110/*
169111** Return the sector-size in bytes for an rbuVfs-file.
169112*/
169113static int rbuVfsSectorSize(sqlite3_file *pFile){
169114  rbu_file *p = (rbu_file *)pFile;
169115  return p->pReal->pMethods->xSectorSize(p->pReal);
169116}
169117
169118/*
169119** Return the device characteristic flags supported by an rbuVfs-file.
169120*/
169121static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
169122  rbu_file *p = (rbu_file *)pFile;
169123  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
169124}
169125
169126/*
169127** Take or release a shared-memory lock.
169128*/
169129static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
169130  rbu_file *p = (rbu_file*)pFile;
169131  sqlite3rbu *pRbu = p->pRbu;
169132  int rc = SQLITE_OK;
169133
169134#ifdef SQLITE_AMALGAMATION
169135    assert( WAL_CKPT_LOCK==1 );
169136#endif
169137
169138  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169139  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
169140    /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
169141    ** taking this lock also prevents any checkpoints from occurring.
169142    ** todo: really, it's not clear why this might occur, as
169143    ** wal_autocheckpoint ought to be turned off.  */
169144    if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
169145  }else{
169146    int bCapture = 0;
169147    if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
169148     && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
169149     && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
169150    ){
169151      bCapture = 1;
169152    }
169153
169154    if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
169155      rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
169156      if( bCapture && rc==SQLITE_OK ){
169157        pRbu->mLock |= (1 << ofst);
169158      }
169159    }
169160  }
169161
169162  return rc;
169163}
169164
169165/*
169166** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
169167*/
169168static int rbuVfsShmMap(
169169  sqlite3_file *pFile,
169170  int iRegion,
169171  int szRegion,
169172  int isWrite,
169173  void volatile **pp
169174){
169175  rbu_file *p = (rbu_file*)pFile;
169176  int rc = SQLITE_OK;
169177  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
169178
169179  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
169180  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
169181  ** instead of a file on disk.  */
169182  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169183  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
169184    if( iRegion<=p->nShm ){
169185      int nByte = (iRegion+1) * sizeof(char*);
169186      char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
169187      if( apNew==0 ){
169188        rc = SQLITE_NOMEM;
169189      }else{
169190        memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
169191        p->apShm = apNew;
169192        p->nShm = iRegion+1;
169193      }
169194    }
169195
169196    if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
169197      char *pNew = (char*)sqlite3_malloc64(szRegion);
169198      if( pNew==0 ){
169199        rc = SQLITE_NOMEM;
169200      }else{
169201        memset(pNew, 0, szRegion);
169202        p->apShm[iRegion] = pNew;
169203      }
169204    }
169205
169206    if( rc==SQLITE_OK ){
169207      *pp = p->apShm[iRegion];
169208    }else{
169209      *pp = 0;
169210    }
169211  }else{
169212    assert( p->apShm==0 );
169213    rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
169214  }
169215
169216  return rc;
169217}
169218
169219/*
169220** Memory barrier.
169221*/
169222static void rbuVfsShmBarrier(sqlite3_file *pFile){
169223  rbu_file *p = (rbu_file *)pFile;
169224  p->pReal->pMethods->xShmBarrier(p->pReal);
169225}
169226
169227/*
169228** The xShmUnmap method.
169229*/
169230static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
169231  rbu_file *p = (rbu_file*)pFile;
169232  int rc = SQLITE_OK;
169233  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
169234
169235  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169236  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
169237    /* no-op */
169238  }else{
169239    /* Release the checkpointer and writer locks */
169240    rbuUnlockShm(p);
169241    rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
169242  }
169243  return rc;
169244}
169245
169246/*
169247** Given that zWal points to a buffer containing a wal file name passed to
169248** either the xOpen() or xAccess() VFS method, return a pointer to the
169249** file-handle opened by the same database connection on the corresponding
169250** database file.
169251*/
169252static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
169253  rbu_file *pDb;
169254  sqlite3_mutex_enter(pRbuVfs->mutex);
169255  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
169256  sqlite3_mutex_leave(pRbuVfs->mutex);
169257  return pDb;
169258}
169259
169260/*
169261** A main database named zName has just been opened. The following
169262** function returns a pointer to a buffer owned by SQLite that contains
169263** the name of the *-wal file this db connection will use. SQLite
169264** happens to pass a pointer to this buffer when using xAccess()
169265** or xOpen() to operate on the *-wal file.
169266*/
169267static const char *rbuMainToWal(const char *zName, int flags){
169268  int n = (int)strlen(zName);
169269  const char *z = &zName[n];
169270  if( flags & SQLITE_OPEN_URI ){
169271    int odd = 0;
169272    while( 1 ){
169273      if( z[0]==0 ){
169274        odd = 1 - odd;
169275        if( odd && z[1]==0 ) break;
169276      }
169277      z++;
169278    }
169279    z += 2;
169280  }else{
169281    while( *z==0 ) z++;
169282  }
169283  z += (n + 8 + 1);
169284  return z;
169285}
169286
169287/*
169288** Open an rbu file handle.
169289*/
169290static int rbuVfsOpen(
169291  sqlite3_vfs *pVfs,
169292  const char *zName,
169293  sqlite3_file *pFile,
169294  int flags,
169295  int *pOutFlags
169296){
169297  static sqlite3_io_methods rbuvfs_io_methods = {
169298    2,                            /* iVersion */
169299    rbuVfsClose,                  /* xClose */
169300    rbuVfsRead,                   /* xRead */
169301    rbuVfsWrite,                  /* xWrite */
169302    rbuVfsTruncate,               /* xTruncate */
169303    rbuVfsSync,                   /* xSync */
169304    rbuVfsFileSize,               /* xFileSize */
169305    rbuVfsLock,                   /* xLock */
169306    rbuVfsUnlock,                 /* xUnlock */
169307    rbuVfsCheckReservedLock,      /* xCheckReservedLock */
169308    rbuVfsFileControl,            /* xFileControl */
169309    rbuVfsSectorSize,             /* xSectorSize */
169310    rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
169311    rbuVfsShmMap,                 /* xShmMap */
169312    rbuVfsShmLock,                /* xShmLock */
169313    rbuVfsShmBarrier,             /* xShmBarrier */
169314    rbuVfsShmUnmap,               /* xShmUnmap */
169315    0, 0                          /* xFetch, xUnfetch */
169316  };
169317  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
169318  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
169319  rbu_file *pFd = (rbu_file *)pFile;
169320  int rc = SQLITE_OK;
169321  const char *zOpen = zName;
169322  int oflags = flags;
169323
169324  memset(pFd, 0, sizeof(rbu_file));
169325  pFd->pReal = (sqlite3_file*)&pFd[1];
169326  pFd->pRbuVfs = pRbuVfs;
169327  pFd->openFlags = flags;
169328  if( zName ){
169329    if( flags & SQLITE_OPEN_MAIN_DB ){
169330      /* A main database has just been opened. The following block sets
169331      ** (pFd->zWal) to point to a buffer owned by SQLite that contains
169332      ** the name of the *-wal file this db connection will use. SQLite
169333      ** happens to pass a pointer to this buffer when using xAccess()
169334      ** or xOpen() to operate on the *-wal file.  */
169335      pFd->zWal = rbuMainToWal(zName, flags);
169336    }
169337    else if( flags & SQLITE_OPEN_WAL ){
169338      rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
169339      if( pDb ){
169340        if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
169341          /* This call is to open a *-wal file. Intead, open the *-oal. This
169342          ** code ensures that the string passed to xOpen() is terminated by a
169343          ** pair of '\0' bytes in case the VFS attempts to extract a URI
169344          ** parameter from it.  */
169345          const char *zBase = zName;
169346          size_t nCopy;
169347          char *zCopy;
169348          if( rbuIsVacuum(pDb->pRbu) ){
169349            zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
169350            zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
169351          }
169352          nCopy = strlen(zBase);
169353          zCopy = sqlite3_malloc64(nCopy+2);
169354          if( zCopy ){
169355            memcpy(zCopy, zBase, nCopy);
169356            zCopy[nCopy-3] = 'o';
169357            zCopy[nCopy] = '\0';
169358            zCopy[nCopy+1] = '\0';
169359            zOpen = (const char*)(pFd->zDel = zCopy);
169360          }else{
169361            rc = SQLITE_NOMEM;
169362          }
169363          pFd->pRbu = pDb->pRbu;
169364        }
169365        pDb->pWalFd = pFd;
169366      }
169367    }
169368  }
169369
169370  if( oflags & SQLITE_OPEN_MAIN_DB
169371   && sqlite3_uri_boolean(zName, "rbu_memory", 0)
169372  ){
169373    assert( oflags & SQLITE_OPEN_MAIN_DB );
169374    oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
169375              SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
169376    zOpen = 0;
169377  }
169378
169379  if( rc==SQLITE_OK ){
169380    rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
169381  }
169382  if( pFd->pReal->pMethods ){
169383    /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
169384    ** pointer and, if the file is a main database file, link it into the
169385    ** mutex protected linked list of all such files.  */
169386    pFile->pMethods = &rbuvfs_io_methods;
169387    if( flags & SQLITE_OPEN_MAIN_DB ){
169388      sqlite3_mutex_enter(pRbuVfs->mutex);
169389      pFd->pMainNext = pRbuVfs->pMain;
169390      pRbuVfs->pMain = pFd;
169391      sqlite3_mutex_leave(pRbuVfs->mutex);
169392    }
169393  }else{
169394    sqlite3_free(pFd->zDel);
169395  }
169396
169397  return rc;
169398}
169399
169400/*
169401** Delete the file located at zPath.
169402*/
169403static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
169404  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169405  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
169406}
169407
169408/*
169409** Test for access permissions. Return true if the requested permission
169410** is available, or false otherwise.
169411*/
169412static int rbuVfsAccess(
169413  sqlite3_vfs *pVfs,
169414  const char *zPath,
169415  int flags,
169416  int *pResOut
169417){
169418  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
169419  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
169420  int rc;
169421
169422  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
169423
169424  /* If this call is to check if a *-wal file associated with an RBU target
169425  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
169426  ** the following special handling is activated:
169427  **
169428  **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
169429  **      ensures that the RBU extension never tries to update a database
169430  **      in wal mode, even if the first page of the database file has
169431  **      been damaged.
169432  **
169433  **   b) if the *-wal file does not exist, claim that it does anyway,
169434  **      causing SQLite to call xOpen() to open it. This call will also
169435  **      be intercepted (see the rbuVfsOpen() function) and the *-oal
169436  **      file opened instead.
169437  */
169438  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
169439    rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
169440    if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
169441      if( *pResOut ){
169442        rc = SQLITE_CANTOPEN;
169443      }else{
169444        *pResOut = 1;
169445      }
169446    }
169447  }
169448
169449  return rc;
169450}
169451
169452/*
169453** Populate buffer zOut with the full canonical pathname corresponding
169454** to the pathname in zPath. zOut is guaranteed to point to a buffer
169455** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
169456*/
169457static int rbuVfsFullPathname(
169458  sqlite3_vfs *pVfs,
169459  const char *zPath,
169460  int nOut,
169461  char *zOut
169462){
169463  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169464  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
169465}
169466
169467#ifndef SQLITE_OMIT_LOAD_EXTENSION
169468/*
169469** Open the dynamic library located at zPath and return a handle.
169470*/
169471static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
169472  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169473  return pRealVfs->xDlOpen(pRealVfs, zPath);
169474}
169475
169476/*
169477** Populate the buffer zErrMsg (size nByte bytes) with a human readable
169478** utf-8 string describing the most recent error encountered associated
169479** with dynamic libraries.
169480*/
169481static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
169482  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169483  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
169484}
169485
169486/*
169487** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
169488*/
169489static void (*rbuVfsDlSym(
169490  sqlite3_vfs *pVfs,
169491  void *pArg,
169492  const char *zSym
169493))(void){
169494  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169495  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
169496}
169497
169498/*
169499** Close the dynamic library handle pHandle.
169500*/
169501static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
169502  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169503  pRealVfs->xDlClose(pRealVfs, pHandle);
169504}
169505#endif /* SQLITE_OMIT_LOAD_EXTENSION */
169506
169507/*
169508** Populate the buffer pointed to by zBufOut with nByte bytes of
169509** random data.
169510*/
169511static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
169512  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169513  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
169514}
169515
169516/*
169517** Sleep for nMicro microseconds. Return the number of microseconds
169518** actually slept.
169519*/
169520static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
169521  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169522  return pRealVfs->xSleep(pRealVfs, nMicro);
169523}
169524
169525/*
169526** Return the current time as a Julian Day number in *pTimeOut.
169527*/
169528static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
169529  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169530  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
169531}
169532
169533/*
169534** No-op.
169535*/
169536static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
169537  return 0;
169538}
169539
169540/*
169541** Deregister and destroy an RBU vfs created by an earlier call to
169542** sqlite3rbu_create_vfs().
169543*/
169544SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
169545  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
169546  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
169547    sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
169548    sqlite3_vfs_unregister(pVfs);
169549    sqlite3_free(pVfs);
169550  }
169551}
169552
169553/*
169554** Create an RBU VFS named zName that accesses the underlying file-system
169555** via existing VFS zParent. The new object is registered as a non-default
169556** VFS with SQLite before returning.
169557*/
169558SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
169559
169560  /* Template for VFS */
169561  static sqlite3_vfs vfs_template = {
169562    1,                            /* iVersion */
169563    0,                            /* szOsFile */
169564    0,                            /* mxPathname */
169565    0,                            /* pNext */
169566    0,                            /* zName */
169567    0,                            /* pAppData */
169568    rbuVfsOpen,                   /* xOpen */
169569    rbuVfsDelete,                 /* xDelete */
169570    rbuVfsAccess,                 /* xAccess */
169571    rbuVfsFullPathname,           /* xFullPathname */
169572
169573#ifndef SQLITE_OMIT_LOAD_EXTENSION
169574    rbuVfsDlOpen,                 /* xDlOpen */
169575    rbuVfsDlError,                /* xDlError */
169576    rbuVfsDlSym,                  /* xDlSym */
169577    rbuVfsDlClose,                /* xDlClose */
169578#else
169579    0, 0, 0, 0,
169580#endif
169581
169582    rbuVfsRandomness,             /* xRandomness */
169583    rbuVfsSleep,                  /* xSleep */
169584    rbuVfsCurrentTime,            /* xCurrentTime */
169585    rbuVfsGetLastError,           /* xGetLastError */
169586    0,                            /* xCurrentTimeInt64 (version 2) */
169587    0, 0, 0                       /* Unimplemented version 3 methods */
169588  };
169589
169590  rbu_vfs *pNew = 0;              /* Newly allocated VFS */
169591  int rc = SQLITE_OK;
169592  size_t nName;
169593  size_t nByte;
169594
169595  nName = strlen(zName);
169596  nByte = sizeof(rbu_vfs) + nName + 1;
169597  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
169598  if( pNew==0 ){
169599    rc = SQLITE_NOMEM;
169600  }else{
169601    sqlite3_vfs *pParent;           /* Parent VFS */
169602    memset(pNew, 0, nByte);
169603    pParent = sqlite3_vfs_find(zParent);
169604    if( pParent==0 ){
169605      rc = SQLITE_NOTFOUND;
169606    }else{
169607      char *zSpace;
169608      memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
169609      pNew->base.mxPathname = pParent->mxPathname;
169610      pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
169611      pNew->pRealVfs = pParent;
169612      pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
169613      memcpy(zSpace, zName, nName);
169614
169615      /* Allocate the mutex and register the new VFS (not as the default) */
169616      pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
169617      if( pNew->mutex==0 ){
169618        rc = SQLITE_NOMEM;
169619      }else{
169620        rc = sqlite3_vfs_register(&pNew->base, 0);
169621      }
169622    }
169623
169624    if( rc!=SQLITE_OK ){
169625      sqlite3_mutex_free(pNew->mutex);
169626      sqlite3_free(pNew);
169627    }
169628  }
169629
169630  return rc;
169631}
169632
169633
169634/**************************************************************************/
169635
169636#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
169637
169638/************** End of sqlite3rbu.c ******************************************/
169639/************** Begin file dbstat.c ******************************************/
169640/*
169641** 2010 July 12
169642**
169643** The author disclaims copyright to this source code.  In place of
169644** a legal notice, here is a blessing:
169645**
169646**    May you do good and not evil.
169647**    May you find forgiveness for yourself and forgive others.
169648**    May you share freely, never taking more than you give.
169649**
169650******************************************************************************
169651**
169652** This file contains an implementation of the "dbstat" virtual table.
169653**
169654** The dbstat virtual table is used to extract low-level formatting
169655** information from an SQLite database in order to implement the
169656** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
169657** for an example implementation.
169658**
169659** Additional information is available on the "dbstat.html" page of the
169660** official SQLite documentation.
169661*/
169662
169663/* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
169664#if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
169665    && !defined(SQLITE_OMIT_VIRTUALTABLE)
169666
169667/*
169668** Page paths:
169669**
169670**   The value of the 'path' column describes the path taken from the
169671**   root-node of the b-tree structure to each page. The value of the
169672**   root-node path is '/'.
169673**
169674**   The value of the path for the left-most child page of the root of
169675**   a b-tree is '/000/'. (Btrees store content ordered from left to right
169676**   so the pages to the left have smaller keys than the pages to the right.)
169677**   The next to left-most child of the root page is
169678**   '/001', and so on, each sibling page identified by a 3-digit hex
169679**   value. The children of the 451st left-most sibling have paths such
169680**   as '/1c2/000/, '/1c2/001/' etc.
169681**
169682**   Overflow pages are specified by appending a '+' character and a
169683**   six-digit hexadecimal value to the path to the cell they are linked
169684**   from. For example, the three overflow pages in a chain linked from
169685**   the left-most cell of the 450th child of the root page are identified
169686**   by the paths:
169687**
169688**      '/1c2/000+000000'         // First page in overflow chain
169689**      '/1c2/000+000001'         // Second page in overflow chain
169690**      '/1c2/000+000002'         // Third page in overflow chain
169691**
169692**   If the paths are sorted using the BINARY collation sequence, then
169693**   the overflow pages associated with a cell will appear earlier in the
169694**   sort-order than its child page:
169695**
169696**      '/1c2/000/'               // Left-most child of 451st child of root
169697*/
169698#define VTAB_SCHEMA                                                         \
169699  "CREATE TABLE xx( "                                                       \
169700  "  name       TEXT,             /* Name of table or index */"             \
169701  "  path       TEXT,             /* Path to page from root */"             \
169702  "  pageno     INTEGER,          /* Page number */"                        \
169703  "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
169704  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
169705  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
169706  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
169707  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
169708  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
169709  "  pgsize     INTEGER,          /* Size of the page */"                   \
169710  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
169711  ");"
169712
169713
169714typedef struct StatTable StatTable;
169715typedef struct StatCursor StatCursor;
169716typedef struct StatPage StatPage;
169717typedef struct StatCell StatCell;
169718
169719struct StatCell {
169720  int nLocal;                     /* Bytes of local payload */
169721  u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
169722  int nOvfl;                      /* Entries in aOvfl[] */
169723  u32 *aOvfl;                     /* Array of overflow page numbers */
169724  int nLastOvfl;                  /* Bytes of payload on final overflow page */
169725  int iOvfl;                      /* Iterates through aOvfl[] */
169726};
169727
169728struct StatPage {
169729  u32 iPgno;
169730  DbPage *pPg;
169731  int iCell;
169732
169733  char *zPath;                    /* Path to this page */
169734
169735  /* Variables populated by statDecodePage(): */
169736  u8 flags;                       /* Copy of flags byte */
169737  int nCell;                      /* Number of cells on page */
169738  int nUnused;                    /* Number of unused bytes on page */
169739  StatCell *aCell;                /* Array of parsed cells */
169740  u32 iRightChildPg;              /* Right-child page number (or 0) */
169741  int nMxPayload;                 /* Largest payload of any cell on this page */
169742};
169743
169744struct StatCursor {
169745  sqlite3_vtab_cursor base;
169746  sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
169747  int isEof;                      /* After pStmt has returned SQLITE_DONE */
169748  int iDb;                        /* Schema used for this query */
169749
169750  StatPage aPage[32];
169751  int iPage;                      /* Current entry in aPage[] */
169752
169753  /* Values to return. */
169754  char *zName;                    /* Value of 'name' column */
169755  char *zPath;                    /* Value of 'path' column */
169756  u32 iPageno;                    /* Value of 'pageno' column */
169757  char *zPagetype;                /* Value of 'pagetype' column */
169758  int nCell;                      /* Value of 'ncell' column */
169759  int nPayload;                   /* Value of 'payload' column */
169760  int nUnused;                    /* Value of 'unused' column */
169761  int nMxPayload;                 /* Value of 'mx_payload' column */
169762  i64 iOffset;                    /* Value of 'pgOffset' column */
169763  int szPage;                     /* Value of 'pgSize' column */
169764};
169765
169766struct StatTable {
169767  sqlite3_vtab base;
169768  sqlite3 *db;
169769  int iDb;                        /* Index of database to analyze */
169770};
169771
169772#ifndef get2byte
169773# define get2byte(x)   ((x)[0]<<8 | (x)[1])
169774#endif
169775
169776/*
169777** Connect to or create a statvfs virtual table.
169778*/
169779static int statConnect(
169780  sqlite3 *db,
169781  void *pAux,
169782  int argc, const char *const*argv,
169783  sqlite3_vtab **ppVtab,
169784  char **pzErr
169785){
169786  StatTable *pTab = 0;
169787  int rc = SQLITE_OK;
169788  int iDb;
169789
169790  if( argc>=4 ){
169791    Token nm;
169792    sqlite3TokenInit(&nm, (char*)argv[3]);
169793    iDb = sqlite3FindDb(db, &nm);
169794    if( iDb<0 ){
169795      *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
169796      return SQLITE_ERROR;
169797    }
169798  }else{
169799    iDb = 0;
169800  }
169801  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
169802  if( rc==SQLITE_OK ){
169803    pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
169804    if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
169805  }
169806
169807  assert( rc==SQLITE_OK || pTab==0 );
169808  if( rc==SQLITE_OK ){
169809    memset(pTab, 0, sizeof(StatTable));
169810    pTab->db = db;
169811    pTab->iDb = iDb;
169812  }
169813
169814  *ppVtab = (sqlite3_vtab*)pTab;
169815  return rc;
169816}
169817
169818/*
169819** Disconnect from or destroy a statvfs virtual table.
169820*/
169821static int statDisconnect(sqlite3_vtab *pVtab){
169822  sqlite3_free(pVtab);
169823  return SQLITE_OK;
169824}
169825
169826/*
169827** There is no "best-index". This virtual table always does a linear
169828** scan.  However, a schema=? constraint should cause this table to
169829** operate on a different database schema, so check for it.
169830**
169831** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
169832*/
169833static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
169834  int i;
169835
169836  pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
169837
169838  /* Look for a valid schema=? constraint.  If found, change the idxNum to
169839  ** 1 and request the value of that constraint be sent to xFilter.  And
169840  ** lower the cost estimate to encourage the constrained version to be
169841  ** used.
169842  */
169843  for(i=0; i<pIdxInfo->nConstraint; i++){
169844    if( pIdxInfo->aConstraint[i].usable==0 ) continue;
169845    if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
169846    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
169847    pIdxInfo->idxNum = 1;
169848    pIdxInfo->estimatedCost = 1.0;
169849    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
169850    pIdxInfo->aConstraintUsage[i].omit = 1;
169851    break;
169852  }
169853
169854
169855  /* Records are always returned in ascending order of (name, path).
169856  ** If this will satisfy the client, set the orderByConsumed flag so that
169857  ** SQLite does not do an external sort.
169858  */
169859  if( ( pIdxInfo->nOrderBy==1
169860     && pIdxInfo->aOrderBy[0].iColumn==0
169861     && pIdxInfo->aOrderBy[0].desc==0
169862     ) ||
169863      ( pIdxInfo->nOrderBy==2
169864     && pIdxInfo->aOrderBy[0].iColumn==0
169865     && pIdxInfo->aOrderBy[0].desc==0
169866     && pIdxInfo->aOrderBy[1].iColumn==1
169867     && pIdxInfo->aOrderBy[1].desc==0
169868     )
169869  ){
169870    pIdxInfo->orderByConsumed = 1;
169871  }
169872
169873  return SQLITE_OK;
169874}
169875
169876/*
169877** Open a new statvfs cursor.
169878*/
169879static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
169880  StatTable *pTab = (StatTable *)pVTab;
169881  StatCursor *pCsr;
169882
169883  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
169884  if( pCsr==0 ){
169885    return SQLITE_NOMEM_BKPT;
169886  }else{
169887    memset(pCsr, 0, sizeof(StatCursor));
169888    pCsr->base.pVtab = pVTab;
169889    pCsr->iDb = pTab->iDb;
169890  }
169891
169892  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
169893  return SQLITE_OK;
169894}
169895
169896static void statClearPage(StatPage *p){
169897  int i;
169898  if( p->aCell ){
169899    for(i=0; i<p->nCell; i++){
169900      sqlite3_free(p->aCell[i].aOvfl);
169901    }
169902    sqlite3_free(p->aCell);
169903  }
169904  sqlite3PagerUnref(p->pPg);
169905  sqlite3_free(p->zPath);
169906  memset(p, 0, sizeof(StatPage));
169907}
169908
169909static void statResetCsr(StatCursor *pCsr){
169910  int i;
169911  sqlite3_reset(pCsr->pStmt);
169912  for(i=0; i<ArraySize(pCsr->aPage); i++){
169913    statClearPage(&pCsr->aPage[i]);
169914  }
169915  pCsr->iPage = 0;
169916  sqlite3_free(pCsr->zPath);
169917  pCsr->zPath = 0;
169918  pCsr->isEof = 0;
169919}
169920
169921/*
169922** Close a statvfs cursor.
169923*/
169924static int statClose(sqlite3_vtab_cursor *pCursor){
169925  StatCursor *pCsr = (StatCursor *)pCursor;
169926  statResetCsr(pCsr);
169927  sqlite3_finalize(pCsr->pStmt);
169928  sqlite3_free(pCsr);
169929  return SQLITE_OK;
169930}
169931
169932static void getLocalPayload(
169933  int nUsable,                    /* Usable bytes per page */
169934  u8 flags,                       /* Page flags */
169935  int nTotal,                     /* Total record (payload) size */
169936  int *pnLocal                    /* OUT: Bytes stored locally */
169937){
169938  int nLocal;
169939  int nMinLocal;
169940  int nMaxLocal;
169941
169942  if( flags==0x0D ){              /* Table leaf node */
169943    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
169944    nMaxLocal = nUsable - 35;
169945  }else{                          /* Index interior and leaf nodes */
169946    nMinLocal = (nUsable - 12) * 32 / 255 - 23;
169947    nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
169948  }
169949
169950  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
169951  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
169952  *pnLocal = nLocal;
169953}
169954
169955static int statDecodePage(Btree *pBt, StatPage *p){
169956  int nUnused;
169957  int iOff;
169958  int nHdr;
169959  int isLeaf;
169960  int szPage;
169961
169962  u8 *aData = sqlite3PagerGetData(p->pPg);
169963  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
169964
169965  p->flags = aHdr[0];
169966  p->nCell = get2byte(&aHdr[3]);
169967  p->nMxPayload = 0;
169968
169969  isLeaf = (p->flags==0x0A || p->flags==0x0D);
169970  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
169971
169972  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
169973  nUnused += (int)aHdr[7];
169974  iOff = get2byte(&aHdr[1]);
169975  while( iOff ){
169976    nUnused += get2byte(&aData[iOff+2]);
169977    iOff = get2byte(&aData[iOff]);
169978  }
169979  p->nUnused = nUnused;
169980  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
169981  szPage = sqlite3BtreeGetPageSize(pBt);
169982
169983  if( p->nCell ){
169984    int i;                        /* Used to iterate through cells */
169985    int nUsable;                  /* Usable bytes per page */
169986
169987    sqlite3BtreeEnter(pBt);
169988    nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
169989    sqlite3BtreeLeave(pBt);
169990    p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
169991    if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
169992    memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
169993
169994    for(i=0; i<p->nCell; i++){
169995      StatCell *pCell = &p->aCell[i];
169996
169997      iOff = get2byte(&aData[nHdr+i*2]);
169998      if( !isLeaf ){
169999        pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
170000        iOff += 4;
170001      }
170002      if( p->flags==0x05 ){
170003        /* A table interior node. nPayload==0. */
170004      }else{
170005        u32 nPayload;             /* Bytes of payload total (local+overflow) */
170006        int nLocal;               /* Bytes of payload stored locally */
170007        iOff += getVarint32(&aData[iOff], nPayload);
170008        if( p->flags==0x0D ){
170009          u64 dummy;
170010          iOff += sqlite3GetVarint(&aData[iOff], &dummy);
170011        }
170012        if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
170013        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
170014        pCell->nLocal = nLocal;
170015        assert( nLocal>=0 );
170016        assert( nPayload>=(u32)nLocal );
170017        assert( nLocal<=(nUsable-35) );
170018        if( nPayload>(u32)nLocal ){
170019          int j;
170020          int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
170021          pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
170022          pCell->nOvfl = nOvfl;
170023          pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
170024          if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
170025          pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
170026          for(j=1; j<nOvfl; j++){
170027            int rc;
170028            u32 iPrev = pCell->aOvfl[j-1];
170029            DbPage *pPg = 0;
170030            rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
170031            if( rc!=SQLITE_OK ){
170032              assert( pPg==0 );
170033              return rc;
170034            }
170035            pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
170036            sqlite3PagerUnref(pPg);
170037          }
170038        }
170039      }
170040    }
170041  }
170042
170043  return SQLITE_OK;
170044}
170045
170046/*
170047** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
170048** the current value of pCsr->iPageno.
170049*/
170050static void statSizeAndOffset(StatCursor *pCsr){
170051  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
170052  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
170053  Pager *pPager = sqlite3BtreePager(pBt);
170054  sqlite3_file *fd;
170055  sqlite3_int64 x[2];
170056
170057  /* The default page size and offset */
170058  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
170059  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
170060
170061  /* If connected to a ZIPVFS backend, override the page size and
170062  ** offset with actual values obtained from ZIPVFS.
170063  */
170064  fd = sqlite3PagerFile(pPager);
170065  x[0] = pCsr->iPageno;
170066  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
170067    pCsr->iOffset = x[0];
170068    pCsr->szPage = (int)x[1];
170069  }
170070}
170071
170072/*
170073** Move a statvfs cursor to the next entry in the file.
170074*/
170075static int statNext(sqlite3_vtab_cursor *pCursor){
170076  int rc;
170077  int nPayload;
170078  char *z;
170079  StatCursor *pCsr = (StatCursor *)pCursor;
170080  StatTable *pTab = (StatTable *)pCursor->pVtab;
170081  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
170082  Pager *pPager = sqlite3BtreePager(pBt);
170083
170084  sqlite3_free(pCsr->zPath);
170085  pCsr->zPath = 0;
170086
170087statNextRestart:
170088  if( pCsr->aPage[0].pPg==0 ){
170089    rc = sqlite3_step(pCsr->pStmt);
170090    if( rc==SQLITE_ROW ){
170091      int nPage;
170092      u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
170093      sqlite3PagerPagecount(pPager, &nPage);
170094      if( nPage==0 ){
170095        pCsr->isEof = 1;
170096        return sqlite3_reset(pCsr->pStmt);
170097      }
170098      rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
170099      pCsr->aPage[0].iPgno = iRoot;
170100      pCsr->aPage[0].iCell = 0;
170101      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
170102      pCsr->iPage = 0;
170103      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170104    }else{
170105      pCsr->isEof = 1;
170106      return sqlite3_reset(pCsr->pStmt);
170107    }
170108  }else{
170109
170110    /* Page p itself has already been visited. */
170111    StatPage *p = &pCsr->aPage[pCsr->iPage];
170112
170113    while( p->iCell<p->nCell ){
170114      StatCell *pCell = &p->aCell[p->iCell];
170115      if( pCell->iOvfl<pCell->nOvfl ){
170116        int nUsable;
170117        sqlite3BtreeEnter(pBt);
170118        nUsable = sqlite3BtreeGetPageSize(pBt) -
170119                        sqlite3BtreeGetReserveNoMutex(pBt);
170120        sqlite3BtreeLeave(pBt);
170121        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
170122        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
170123        pCsr->zPagetype = "overflow";
170124        pCsr->nCell = 0;
170125        pCsr->nMxPayload = 0;
170126        pCsr->zPath = z = sqlite3_mprintf(
170127            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
170128        );
170129        if( pCell->iOvfl<pCell->nOvfl-1 ){
170130          pCsr->nUnused = 0;
170131          pCsr->nPayload = nUsable - 4;
170132        }else{
170133          pCsr->nPayload = pCell->nLastOvfl;
170134          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
170135        }
170136        pCell->iOvfl++;
170137        statSizeAndOffset(pCsr);
170138        return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
170139      }
170140      if( p->iRightChildPg ) break;
170141      p->iCell++;
170142    }
170143
170144    if( !p->iRightChildPg || p->iCell>p->nCell ){
170145      statClearPage(p);
170146      if( pCsr->iPage==0 ) return statNext(pCursor);
170147      pCsr->iPage--;
170148      goto statNextRestart; /* Tail recursion */
170149    }
170150    pCsr->iPage++;
170151    assert( p==&pCsr->aPage[pCsr->iPage-1] );
170152
170153    if( p->iCell==p->nCell ){
170154      p[1].iPgno = p->iRightChildPg;
170155    }else{
170156      p[1].iPgno = p->aCell[p->iCell].iChildPg;
170157    }
170158    rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
170159    p[1].iCell = 0;
170160    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
170161    p->iCell++;
170162    if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170163  }
170164
170165
170166  /* Populate the StatCursor fields with the values to be returned
170167  ** by the xColumn() and xRowid() methods.
170168  */
170169  if( rc==SQLITE_OK ){
170170    int i;
170171    StatPage *p = &pCsr->aPage[pCsr->iPage];
170172    pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
170173    pCsr->iPageno = p->iPgno;
170174
170175    rc = statDecodePage(pBt, p);
170176    if( rc==SQLITE_OK ){
170177      statSizeAndOffset(pCsr);
170178
170179      switch( p->flags ){
170180        case 0x05:             /* table internal */
170181        case 0x02:             /* index internal */
170182          pCsr->zPagetype = "internal";
170183          break;
170184        case 0x0D:             /* table leaf */
170185        case 0x0A:             /* index leaf */
170186          pCsr->zPagetype = "leaf";
170187          break;
170188        default:
170189          pCsr->zPagetype = "corrupted";
170190          break;
170191      }
170192      pCsr->nCell = p->nCell;
170193      pCsr->nUnused = p->nUnused;
170194      pCsr->nMxPayload = p->nMxPayload;
170195      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
170196      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170197      nPayload = 0;
170198      for(i=0; i<p->nCell; i++){
170199        nPayload += p->aCell[i].nLocal;
170200      }
170201      pCsr->nPayload = nPayload;
170202    }
170203  }
170204
170205  return rc;
170206}
170207
170208static int statEof(sqlite3_vtab_cursor *pCursor){
170209  StatCursor *pCsr = (StatCursor *)pCursor;
170210  return pCsr->isEof;
170211}
170212
170213static int statFilter(
170214  sqlite3_vtab_cursor *pCursor,
170215  int idxNum, const char *idxStr,
170216  int argc, sqlite3_value **argv
170217){
170218  StatCursor *pCsr = (StatCursor *)pCursor;
170219  StatTable *pTab = (StatTable*)(pCursor->pVtab);
170220  char *zSql;
170221  int rc = SQLITE_OK;
170222  char *zMaster;
170223
170224  if( idxNum==1 ){
170225    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
170226    pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
170227    if( pCsr->iDb<0 ){
170228      sqlite3_free(pCursor->pVtab->zErrMsg);
170229      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
170230      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
170231    }
170232  }else{
170233    pCsr->iDb = pTab->iDb;
170234  }
170235  statResetCsr(pCsr);
170236  sqlite3_finalize(pCsr->pStmt);
170237  pCsr->pStmt = 0;
170238  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
170239  zSql = sqlite3_mprintf(
170240      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
170241      "  UNION ALL  "
170242      "SELECT name, rootpage, type"
170243      "  FROM \"%w\".%s WHERE rootpage!=0"
170244      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
170245  if( zSql==0 ){
170246    return SQLITE_NOMEM_BKPT;
170247  }else{
170248    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
170249    sqlite3_free(zSql);
170250  }
170251
170252  if( rc==SQLITE_OK ){
170253    rc = statNext(pCursor);
170254  }
170255  return rc;
170256}
170257
170258static int statColumn(
170259  sqlite3_vtab_cursor *pCursor,
170260  sqlite3_context *ctx,
170261  int i
170262){
170263  StatCursor *pCsr = (StatCursor *)pCursor;
170264  switch( i ){
170265    case 0:            /* name */
170266      sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
170267      break;
170268    case 1:            /* path */
170269      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
170270      break;
170271    case 2:            /* pageno */
170272      sqlite3_result_int64(ctx, pCsr->iPageno);
170273      break;
170274    case 3:            /* pagetype */
170275      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
170276      break;
170277    case 4:            /* ncell */
170278      sqlite3_result_int(ctx, pCsr->nCell);
170279      break;
170280    case 5:            /* payload */
170281      sqlite3_result_int(ctx, pCsr->nPayload);
170282      break;
170283    case 6:            /* unused */
170284      sqlite3_result_int(ctx, pCsr->nUnused);
170285      break;
170286    case 7:            /* mx_payload */
170287      sqlite3_result_int(ctx, pCsr->nMxPayload);
170288      break;
170289    case 8:            /* pgoffset */
170290      sqlite3_result_int64(ctx, pCsr->iOffset);
170291      break;
170292    case 9:            /* pgsize */
170293      sqlite3_result_int(ctx, pCsr->szPage);
170294      break;
170295    default: {          /* schema */
170296      sqlite3 *db = sqlite3_context_db_handle(ctx);
170297      int iDb = pCsr->iDb;
170298      sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
170299      break;
170300    }
170301  }
170302  return SQLITE_OK;
170303}
170304
170305static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
170306  StatCursor *pCsr = (StatCursor *)pCursor;
170307  *pRowid = pCsr->iPageno;
170308  return SQLITE_OK;
170309}
170310
170311/*
170312** Invoke this routine to register the "dbstat" virtual table module
170313*/
170314SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
170315  static sqlite3_module dbstat_module = {
170316    0,                            /* iVersion */
170317    statConnect,                  /* xCreate */
170318    statConnect,                  /* xConnect */
170319    statBestIndex,                /* xBestIndex */
170320    statDisconnect,               /* xDisconnect */
170321    statDisconnect,               /* xDestroy */
170322    statOpen,                     /* xOpen - open a cursor */
170323    statClose,                    /* xClose - close a cursor */
170324    statFilter,                   /* xFilter - configure scan constraints */
170325    statNext,                     /* xNext - advance a cursor */
170326    statEof,                      /* xEof - check for end of scan */
170327    statColumn,                   /* xColumn - read data */
170328    statRowid,                    /* xRowid - read data */
170329    0,                            /* xUpdate */
170330    0,                            /* xBegin */
170331    0,                            /* xSync */
170332    0,                            /* xCommit */
170333    0,                            /* xRollback */
170334    0,                            /* xFindMethod */
170335    0,                            /* xRename */
170336  };
170337  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
170338}
170339#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
170340SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
170341#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
170342
170343/************** End of dbstat.c **********************************************/
170344/************** Begin file sqlite3session.c **********************************/
170345
170346#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
170347/* #include "sqlite3session.h" */
170348/* #include <assert.h> */
170349/* #include <string.h> */
170350
170351#ifndef SQLITE_AMALGAMATION
170352/* # include "sqliteInt.h" */
170353/* # include "vdbeInt.h" */
170354#endif
170355
170356typedef struct SessionTable SessionTable;
170357typedef struct SessionChange SessionChange;
170358typedef struct SessionBuffer SessionBuffer;
170359typedef struct SessionInput SessionInput;
170360
170361/*
170362** Minimum chunk size used by streaming versions of functions.
170363*/
170364#ifndef SESSIONS_STRM_CHUNK_SIZE
170365# ifdef SQLITE_TEST
170366#   define SESSIONS_STRM_CHUNK_SIZE 64
170367# else
170368#   define SESSIONS_STRM_CHUNK_SIZE 1024
170369# endif
170370#endif
170371
170372typedef struct SessionHook SessionHook;
170373struct SessionHook {
170374  void *pCtx;
170375  int (*xOld)(void*,int,sqlite3_value**);
170376  int (*xNew)(void*,int,sqlite3_value**);
170377  int (*xCount)(void*);
170378  int (*xDepth)(void*);
170379};
170380
170381/*
170382** Session handle structure.
170383*/
170384struct sqlite3_session {
170385  sqlite3 *db;                    /* Database handle session is attached to */
170386  char *zDb;                      /* Name of database session is attached to */
170387  int bEnable;                    /* True if currently recording */
170388  int bIndirect;                  /* True if all changes are indirect */
170389  int bAutoAttach;                /* True to auto-attach tables */
170390  int rc;                         /* Non-zero if an error has occurred */
170391  void *pFilterCtx;               /* First argument to pass to xTableFilter */
170392  int (*xTableFilter)(void *pCtx, const char *zTab);
170393  sqlite3_session *pNext;         /* Next session object on same db. */
170394  SessionTable *pTable;           /* List of attached tables */
170395  SessionHook hook;               /* APIs to grab new and old data with */
170396};
170397
170398/*
170399** Instances of this structure are used to build strings or binary records.
170400*/
170401struct SessionBuffer {
170402  u8 *aBuf;                       /* Pointer to changeset buffer */
170403  int nBuf;                       /* Size of buffer aBuf */
170404  int nAlloc;                     /* Size of allocation containing aBuf */
170405};
170406
170407/*
170408** An object of this type is used internally as an abstraction for
170409** input data. Input data may be supplied either as a single large buffer
170410** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
170411**  sqlite3changeset_start_strm()).
170412*/
170413struct SessionInput {
170414  int bNoDiscard;                 /* If true, discard no data */
170415  int iCurrent;                   /* Offset in aData[] of current change */
170416  int iNext;                      /* Offset in aData[] of next change */
170417  u8 *aData;                      /* Pointer to buffer containing changeset */
170418  int nData;                      /* Number of bytes in aData */
170419
170420  SessionBuffer buf;              /* Current read buffer */
170421  int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
170422  void *pIn;                                /* First argument to xInput */
170423  int bEof;                       /* Set to true after xInput finished */
170424};
170425
170426/*
170427** Structure for changeset iterators.
170428*/
170429struct sqlite3_changeset_iter {
170430  SessionInput in;                /* Input buffer or stream */
170431  SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
170432  int bPatchset;                  /* True if this is a patchset */
170433  int rc;                         /* Iterator error code */
170434  sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
170435  char *zTab;                     /* Current table */
170436  int nCol;                       /* Number of columns in zTab */
170437  int op;                         /* Current operation */
170438  int bIndirect;                  /* True if current change was indirect */
170439  u8 *abPK;                       /* Primary key array */
170440  sqlite3_value **apValue;        /* old.* and new.* values */
170441};
170442
170443/*
170444** Each session object maintains a set of the following structures, one
170445** for each table the session object is monitoring. The structures are
170446** stored in a linked list starting at sqlite3_session.pTable.
170447**
170448** The keys of the SessionTable.aChange[] hash table are all rows that have
170449** been modified in any way since the session object was attached to the
170450** table.
170451**
170452** The data associated with each hash-table entry is a structure containing
170453** a subset of the initial values that the modified row contained at the
170454** start of the session. Or no initial values if the row was inserted.
170455*/
170456struct SessionTable {
170457  SessionTable *pNext;
170458  char *zName;                    /* Local name of table */
170459  int nCol;                       /* Number of columns in table zName */
170460  const char **azCol;             /* Column names */
170461  u8 *abPK;                       /* Array of primary key flags */
170462  int nEntry;                     /* Total number of entries in hash table */
170463  int nChange;                    /* Size of apChange[] array */
170464  SessionChange **apChange;       /* Hash table buckets */
170465};
170466
170467/*
170468** RECORD FORMAT:
170469**
170470** The following record format is similar to (but not compatible with) that
170471** used in SQLite database files. This format is used as part of the
170472** change-set binary format, and so must be architecture independent.
170473**
170474** Unlike the SQLite database record format, each field is self-contained -
170475** there is no separation of header and data. Each field begins with a
170476** single byte describing its type, as follows:
170477**
170478**       0x00: Undefined value.
170479**       0x01: Integer value.
170480**       0x02: Real value.
170481**       0x03: Text value.
170482**       0x04: Blob value.
170483**       0x05: SQL NULL value.
170484**
170485** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
170486** and so on in sqlite3.h. For undefined and NULL values, the field consists
170487** only of the single type byte. For other types of values, the type byte
170488** is followed by:
170489**
170490**   Text values:
170491**     A varint containing the number of bytes in the value (encoded using
170492**     UTF-8). Followed by a buffer containing the UTF-8 representation
170493**     of the text value. There is no nul terminator.
170494**
170495**   Blob values:
170496**     A varint containing the number of bytes in the value, followed by
170497**     a buffer containing the value itself.
170498**
170499**   Integer values:
170500**     An 8-byte big-endian integer value.
170501**
170502**   Real values:
170503**     An 8-byte big-endian IEEE 754-2008 real value.
170504**
170505** Varint values are encoded in the same way as varints in the SQLite
170506** record format.
170507**
170508** CHANGESET FORMAT:
170509**
170510** A changeset is a collection of DELETE, UPDATE and INSERT operations on
170511** one or more tables. Operations on a single table are grouped together,
170512** but may occur in any order (i.e. deletes, updates and inserts are all
170513** mixed together).
170514**
170515** Each group of changes begins with a table header:
170516**
170517**   1 byte: Constant 0x54 (capital 'T')
170518**   Varint: Number of columns in the table.
170519**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
170520**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
170521**
170522** Followed by one or more changes to the table.
170523**
170524**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
170525**   1 byte: The "indirect-change" flag.
170526**   old.* record: (delete and update only)
170527**   new.* record: (insert and update only)
170528**
170529** The "old.*" and "new.*" records, if present, are N field records in the
170530** format described above under "RECORD FORMAT", where N is the number of
170531** columns in the table. The i'th field of each record is associated with
170532** the i'th column of the table, counting from left to right in the order
170533** in which columns were declared in the CREATE TABLE statement.
170534**
170535** The new.* record that is part of each INSERT change contains the values
170536** that make up the new row. Similarly, the old.* record that is part of each
170537** DELETE change contains the values that made up the row that was deleted
170538** from the database. In the changeset format, the records that are part
170539** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
170540** fields.
170541**
170542** Within the old.* record associated with an UPDATE change, all fields
170543** associated with table columns that are not PRIMARY KEY columns and are
170544** not modified by the UPDATE change are set to "undefined". Other fields
170545** are set to the values that made up the row before the UPDATE that the
170546** change records took place. Within the new.* record, fields associated
170547** with table columns modified by the UPDATE change contain the new
170548** values. Fields associated with table columns that are not modified
170549** are set to "undefined".
170550**
170551** PATCHSET FORMAT:
170552**
170553** A patchset is also a collection of changes. It is similar to a changeset,
170554** but leaves undefined those fields that are not useful if no conflict
170555** resolution is required when applying the changeset.
170556**
170557** Each group of changes begins with a table header:
170558**
170559**   1 byte: Constant 0x50 (capital 'P')
170560**   Varint: Number of columns in the table.
170561**   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
170562**   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
170563**
170564** Followed by one or more changes to the table.
170565**
170566**   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
170567**   1 byte: The "indirect-change" flag.
170568**   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
170569**                   full record for INSERT).
170570**
170571** As in the changeset format, each field of the single record that is part
170572** of a patchset change is associated with the correspondingly positioned
170573** table column, counting from left to right within the CREATE TABLE
170574** statement.
170575**
170576** For a DELETE change, all fields within the record except those associated
170577** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
170578** contain the values identifying the row to delete.
170579**
170580** For an UPDATE change, all fields except those associated with PRIMARY KEY
170581** columns and columns that are modified by the UPDATE are set to "undefined".
170582** PRIMARY KEY fields contain the values identifying the table row to update,
170583** and fields associated with modified columns contain the new column values.
170584**
170585** The records associated with INSERT changes are in the same format as for
170586** changesets. It is not possible for a record associated with an INSERT
170587** change to contain a field set to "undefined".
170588*/
170589
170590/*
170591** For each row modified during a session, there exists a single instance of
170592** this structure stored in a SessionTable.aChange[] hash table.
170593*/
170594struct SessionChange {
170595  int op;                         /* One of UPDATE, DELETE, INSERT */
170596  int bIndirect;                  /* True if this change is "indirect" */
170597  int nRecord;                    /* Number of bytes in buffer aRecord[] */
170598  u8 *aRecord;                    /* Buffer containing old.* record */
170599  SessionChange *pNext;           /* For hash-table collisions */
170600};
170601
170602/*
170603** Write a varint with value iVal into the buffer at aBuf. Return the
170604** number of bytes written.
170605*/
170606static int sessionVarintPut(u8 *aBuf, int iVal){
170607  return putVarint32(aBuf, iVal);
170608}
170609
170610/*
170611** Return the number of bytes required to store value iVal as a varint.
170612*/
170613static int sessionVarintLen(int iVal){
170614  return sqlite3VarintLen(iVal);
170615}
170616
170617/*
170618** Read a varint value from aBuf[] into *piVal. Return the number of
170619** bytes read.
170620*/
170621static int sessionVarintGet(u8 *aBuf, int *piVal){
170622  return getVarint32(aBuf, *piVal);
170623}
170624
170625/* Load an unaligned and unsigned 32-bit integer */
170626#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
170627
170628/*
170629** Read a 64-bit big-endian integer value from buffer aRec[]. Return
170630** the value read.
170631*/
170632static sqlite3_int64 sessionGetI64(u8 *aRec){
170633  u64 x = SESSION_UINT32(aRec);
170634  u32 y = SESSION_UINT32(aRec+4);
170635  x = (x<<32) + y;
170636  return (sqlite3_int64)x;
170637}
170638
170639/*
170640** Write a 64-bit big-endian integer value to the buffer aBuf[].
170641*/
170642static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
170643  aBuf[0] = (i>>56) & 0xFF;
170644  aBuf[1] = (i>>48) & 0xFF;
170645  aBuf[2] = (i>>40) & 0xFF;
170646  aBuf[3] = (i>>32) & 0xFF;
170647  aBuf[4] = (i>>24) & 0xFF;
170648  aBuf[5] = (i>>16) & 0xFF;
170649  aBuf[6] = (i>> 8) & 0xFF;
170650  aBuf[7] = (i>> 0) & 0xFF;
170651}
170652
170653/*
170654** This function is used to serialize the contents of value pValue (see
170655** comment titled "RECORD FORMAT" above).
170656**
170657** If it is non-NULL, the serialized form of the value is written to
170658** buffer aBuf. *pnWrite is set to the number of bytes written before
170659** returning. Or, if aBuf is NULL, the only thing this function does is
170660** set *pnWrite.
170661**
170662** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
170663** within a call to sqlite3_value_text() (may fail if the db is utf-16))
170664** SQLITE_NOMEM is returned.
170665*/
170666static int sessionSerializeValue(
170667  u8 *aBuf,                       /* If non-NULL, write serialized value here */
170668  sqlite3_value *pValue,          /* Value to serialize */
170669  int *pnWrite                    /* IN/OUT: Increment by bytes written */
170670){
170671  int nByte;                      /* Size of serialized value in bytes */
170672
170673  if( pValue ){
170674    int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
170675
170676    eType = sqlite3_value_type(pValue);
170677    if( aBuf ) aBuf[0] = eType;
170678
170679    switch( eType ){
170680      case SQLITE_NULL:
170681        nByte = 1;
170682        break;
170683
170684      case SQLITE_INTEGER:
170685      case SQLITE_FLOAT:
170686        if( aBuf ){
170687          /* TODO: SQLite does something special to deal with mixed-endian
170688          ** floating point values (e.g. ARM7). This code probably should
170689          ** too.  */
170690          u64 i;
170691          if( eType==SQLITE_INTEGER ){
170692            i = (u64)sqlite3_value_int64(pValue);
170693          }else{
170694            double r;
170695            assert( sizeof(double)==8 && sizeof(u64)==8 );
170696            r = sqlite3_value_double(pValue);
170697            memcpy(&i, &r, 8);
170698          }
170699          sessionPutI64(&aBuf[1], i);
170700        }
170701        nByte = 9;
170702        break;
170703
170704      default: {
170705        u8 *z;
170706        int n;
170707        int nVarint;
170708
170709        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
170710        if( eType==SQLITE_TEXT ){
170711          z = (u8 *)sqlite3_value_text(pValue);
170712        }else{
170713          z = (u8 *)sqlite3_value_blob(pValue);
170714        }
170715        n = sqlite3_value_bytes(pValue);
170716        if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
170717        nVarint = sessionVarintLen(n);
170718
170719        if( aBuf ){
170720          sessionVarintPut(&aBuf[1], n);
170721          memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
170722              sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
170723          );
170724        }
170725
170726        nByte = 1 + nVarint + n;
170727        break;
170728      }
170729    }
170730  }else{
170731    nByte = 1;
170732    if( aBuf ) aBuf[0] = '\0';
170733  }
170734
170735  if( pnWrite ) *pnWrite += nByte;
170736  return SQLITE_OK;
170737}
170738
170739
170740/*
170741** This macro is used to calculate hash key values for data structures. In
170742** order to use this macro, the entire data structure must be represented
170743** as a series of unsigned integers. In order to calculate a hash-key value
170744** for a data structure represented as three such integers, the macro may
170745** then be used as follows:
170746**
170747**    int hash_key_value;
170748**    hash_key_value = HASH_APPEND(0, <value 1>);
170749**    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
170750**    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
170751**
170752** In practice, the data structures this macro is used for are the primary
170753** key values of modified rows.
170754*/
170755#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
170756
170757/*
170758** Append the hash of the 64-bit integer passed as the second argument to the
170759** hash-key value passed as the first. Return the new hash-key value.
170760*/
170761static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
170762  h = HASH_APPEND(h, i & 0xFFFFFFFF);
170763  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
170764}
170765
170766/*
170767** Append the hash of the blob passed via the second and third arguments to
170768** the hash-key value passed as the first. Return the new hash-key value.
170769*/
170770static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
170771  int i;
170772  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
170773  return h;
170774}
170775
170776/*
170777** Append the hash of the data type passed as the second argument to the
170778** hash-key value passed as the first. Return the new hash-key value.
170779*/
170780static unsigned int sessionHashAppendType(unsigned int h, int eType){
170781  return HASH_APPEND(h, eType);
170782}
170783
170784/*
170785** This function may only be called from within a pre-update callback.
170786** It calculates a hash based on the primary key values of the old.* or
170787** new.* row currently available and, assuming no error occurs, writes it to
170788** *piHash before returning. If the primary key contains one or more NULL
170789** values, *pbNullPK is set to true before returning.
170790**
170791** If an error occurs, an SQLite error code is returned and the final values
170792** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
170793** and the output variables are set as described above.
170794*/
170795static int sessionPreupdateHash(
170796  sqlite3_session *pSession,      /* Session object that owns pTab */
170797  SessionTable *pTab,             /* Session table handle */
170798  int bNew,                       /* True to hash the new.* PK */
170799  int *piHash,                    /* OUT: Hash value */
170800  int *pbNullPK                   /* OUT: True if there are NULL values in PK */
170801){
170802  unsigned int h = 0;             /* Hash value to return */
170803  int i;                          /* Used to iterate through columns */
170804
170805  assert( *pbNullPK==0 );
170806  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
170807  for(i=0; i<pTab->nCol; i++){
170808    if( pTab->abPK[i] ){
170809      int rc;
170810      int eType;
170811      sqlite3_value *pVal;
170812
170813      if( bNew ){
170814        rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
170815      }else{
170816        rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
170817      }
170818      if( rc!=SQLITE_OK ) return rc;
170819
170820      eType = sqlite3_value_type(pVal);
170821      h = sessionHashAppendType(h, eType);
170822      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170823        i64 iVal;
170824        if( eType==SQLITE_INTEGER ){
170825          iVal = sqlite3_value_int64(pVal);
170826        }else{
170827          double rVal = sqlite3_value_double(pVal);
170828          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
170829          memcpy(&iVal, &rVal, 8);
170830        }
170831        h = sessionHashAppendI64(h, iVal);
170832      }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
170833        const u8 *z;
170834        int n;
170835        if( eType==SQLITE_TEXT ){
170836          z = (const u8 *)sqlite3_value_text(pVal);
170837        }else{
170838          z = (const u8 *)sqlite3_value_blob(pVal);
170839        }
170840        n = sqlite3_value_bytes(pVal);
170841        if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
170842        h = sessionHashAppendBlob(h, n, z);
170843      }else{
170844        assert( eType==SQLITE_NULL );
170845        *pbNullPK = 1;
170846      }
170847    }
170848  }
170849
170850  *piHash = (h % pTab->nChange);
170851  return SQLITE_OK;
170852}
170853
170854/*
170855** The buffer that the argument points to contains a serialized SQL value.
170856** Return the number of bytes of space occupied by the value (including
170857** the type byte).
170858*/
170859static int sessionSerialLen(u8 *a){
170860  int e = *a;
170861  int n;
170862  if( e==0 ) return 1;
170863  if( e==SQLITE_NULL ) return 1;
170864  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
170865  return sessionVarintGet(&a[1], &n) + 1 + n;
170866}
170867
170868/*
170869** Based on the primary key values stored in change aRecord, calculate a
170870** hash key. Assume the has table has nBucket buckets. The hash keys
170871** calculated by this function are compatible with those calculated by
170872** sessionPreupdateHash().
170873**
170874** The bPkOnly argument is non-zero if the record at aRecord[] is from
170875** a patchset DELETE. In this case the non-PK fields are omitted entirely.
170876*/
170877static unsigned int sessionChangeHash(
170878  SessionTable *pTab,             /* Table handle */
170879  int bPkOnly,                    /* Record consists of PK fields only */
170880  u8 *aRecord,                    /* Change record */
170881  int nBucket                     /* Assume this many buckets in hash table */
170882){
170883  unsigned int h = 0;             /* Value to return */
170884  int i;                          /* Used to iterate through columns */
170885  u8 *a = aRecord;                /* Used to iterate through change record */
170886
170887  for(i=0; i<pTab->nCol; i++){
170888    int eType = *a;
170889    int isPK = pTab->abPK[i];
170890    if( bPkOnly && isPK==0 ) continue;
170891
170892    /* It is not possible for eType to be SQLITE_NULL here. The session
170893    ** module does not record changes for rows with NULL values stored in
170894    ** primary key columns. */
170895    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
170896         || eType==SQLITE_TEXT || eType==SQLITE_BLOB
170897         || eType==SQLITE_NULL || eType==0
170898    );
170899    assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
170900
170901    if( isPK ){
170902      a++;
170903      h = sessionHashAppendType(h, eType);
170904      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170905        h = sessionHashAppendI64(h, sessionGetI64(a));
170906        a += 8;
170907      }else{
170908        int n;
170909        a += sessionVarintGet(a, &n);
170910        h = sessionHashAppendBlob(h, n, a);
170911        a += n;
170912      }
170913    }else{
170914      a += sessionSerialLen(a);
170915    }
170916  }
170917  return (h % nBucket);
170918}
170919
170920/*
170921** Arguments aLeft and aRight are pointers to change records for table pTab.
170922** This function returns true if the two records apply to the same row (i.e.
170923** have the same values stored in the primary key columns), or false
170924** otherwise.
170925*/
170926static int sessionChangeEqual(
170927  SessionTable *pTab,             /* Table used for PK definition */
170928  int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
170929  u8 *aLeft,                      /* Change record */
170930  int bRightPkOnly,               /* True if aRight[] contains PK fields only */
170931  u8 *aRight                      /* Change record */
170932){
170933  u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
170934  u8 *a2 = aRight;                /* Cursor to iterate through aRight */
170935  int iCol;                       /* Used to iterate through table columns */
170936
170937  for(iCol=0; iCol<pTab->nCol; iCol++){
170938    if( pTab->abPK[iCol] ){
170939      int n1 = sessionSerialLen(a1);
170940      int n2 = sessionSerialLen(a2);
170941
170942      if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
170943        return 0;
170944      }
170945      a1 += n1;
170946      a2 += n2;
170947    }else{
170948      if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
170949      if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
170950    }
170951  }
170952
170953  return 1;
170954}
170955
170956/*
170957** Arguments aLeft and aRight both point to buffers containing change
170958** records with nCol columns. This function "merges" the two records into
170959** a single records which is written to the buffer at *paOut. *paOut is
170960** then set to point to one byte after the last byte written before
170961** returning.
170962**
170963** The merging of records is done as follows: For each column, if the
170964** aRight record contains a value for the column, copy the value from
170965** their. Otherwise, if aLeft contains a value, copy it. If neither
170966** record contains a value for a given column, then neither does the
170967** output record.
170968*/
170969static void sessionMergeRecord(
170970  u8 **paOut,
170971  int nCol,
170972  u8 *aLeft,
170973  u8 *aRight
170974){
170975  u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
170976  u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
170977  u8 *aOut = *paOut;              /* Output cursor */
170978  int iCol;                       /* Used to iterate from 0 to nCol */
170979
170980  for(iCol=0; iCol<nCol; iCol++){
170981    int n1 = sessionSerialLen(a1);
170982    int n2 = sessionSerialLen(a2);
170983    if( *a2 ){
170984      memcpy(aOut, a2, n2);
170985      aOut += n2;
170986    }else{
170987      memcpy(aOut, a1, n1);
170988      aOut += n1;
170989    }
170990    a1 += n1;
170991    a2 += n2;
170992  }
170993
170994  *paOut = aOut;
170995}
170996
170997/*
170998** This is a helper function used by sessionMergeUpdate().
170999**
171000** When this function is called, both *paOne and *paTwo point to a value
171001** within a change record. Before it returns, both have been advanced so
171002** as to point to the next value in the record.
171003**
171004** If, when this function is called, *paTwo points to a valid value (i.e.
171005** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
171006** pointer is returned and *pnVal is set to the number of bytes in the
171007** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
171008** set to the number of bytes in the value at *paOne. If *paOne points
171009** to the "no value" placeholder, *pnVal is set to 1. In other words:
171010**
171011**   if( *paTwo is valid ) return *paTwo;
171012**   return *paOne;
171013**
171014*/
171015static u8 *sessionMergeValue(
171016  u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
171017  u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
171018  int *pnVal                      /* OUT: Bytes in returned value */
171019){
171020  u8 *a1 = *paOne;
171021  u8 *a2 = *paTwo;
171022  u8 *pRet = 0;
171023  int n1;
171024
171025  assert( a1 );
171026  if( a2 ){
171027    int n2 = sessionSerialLen(a2);
171028    if( *a2 ){
171029      *pnVal = n2;
171030      pRet = a2;
171031    }
171032    *paTwo = &a2[n2];
171033  }
171034
171035  n1 = sessionSerialLen(a1);
171036  if( pRet==0 ){
171037    *pnVal = n1;
171038    pRet = a1;
171039  }
171040  *paOne = &a1[n1];
171041
171042  return pRet;
171043}
171044
171045/*
171046** This function is used by changeset_concat() to merge two UPDATE changes
171047** on the same row.
171048*/
171049static int sessionMergeUpdate(
171050  u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
171051  SessionTable *pTab,             /* Table change pertains to */
171052  int bPatchset,                  /* True if records are patchset records */
171053  u8 *aOldRecord1,                /* old.* record for first change */
171054  u8 *aOldRecord2,                /* old.* record for second change */
171055  u8 *aNewRecord1,                /* new.* record for first change */
171056  u8 *aNewRecord2                 /* new.* record for second change */
171057){
171058  u8 *aOld1 = aOldRecord1;
171059  u8 *aOld2 = aOldRecord2;
171060  u8 *aNew1 = aNewRecord1;
171061  u8 *aNew2 = aNewRecord2;
171062
171063  u8 *aOut = *paOut;
171064  int i;
171065
171066  if( bPatchset==0 ){
171067    int bRequired = 0;
171068
171069    assert( aOldRecord1 && aNewRecord1 );
171070
171071    /* Write the old.* vector first. */
171072    for(i=0; i<pTab->nCol; i++){
171073      int nOld;
171074      u8 *aOld;
171075      int nNew;
171076      u8 *aNew;
171077
171078      aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
171079      aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
171080      if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
171081        if( pTab->abPK[i]==0 ) bRequired = 1;
171082        memcpy(aOut, aOld, nOld);
171083        aOut += nOld;
171084      }else{
171085        *(aOut++) = '\0';
171086      }
171087    }
171088
171089    if( !bRequired ) return 0;
171090  }
171091
171092  /* Write the new.* vector */
171093  aOld1 = aOldRecord1;
171094  aOld2 = aOldRecord2;
171095  aNew1 = aNewRecord1;
171096  aNew2 = aNewRecord2;
171097  for(i=0; i<pTab->nCol; i++){
171098    int nOld;
171099    u8 *aOld;
171100    int nNew;
171101    u8 *aNew;
171102
171103    aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
171104    aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
171105    if( bPatchset==0
171106     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
171107    ){
171108      *(aOut++) = '\0';
171109    }else{
171110      memcpy(aOut, aNew, nNew);
171111      aOut += nNew;
171112    }
171113  }
171114
171115  *paOut = aOut;
171116  return 1;
171117}
171118
171119/*
171120** This function is only called from within a pre-update-hook callback.
171121** It determines if the current pre-update-hook change affects the same row
171122** as the change stored in argument pChange. If so, it returns true. Otherwise
171123** if the pre-update-hook does not affect the same row as pChange, it returns
171124** false.
171125*/
171126static int sessionPreupdateEqual(
171127  sqlite3_session *pSession,      /* Session object that owns SessionTable */
171128  SessionTable *pTab,             /* Table associated with change */
171129  SessionChange *pChange,         /* Change to compare to */
171130  int op                          /* Current pre-update operation */
171131){
171132  int iCol;                       /* Used to iterate through columns */
171133  u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
171134
171135  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
171136  for(iCol=0; iCol<pTab->nCol; iCol++){
171137    if( !pTab->abPK[iCol] ){
171138      a += sessionSerialLen(a);
171139    }else{
171140      sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
171141      int rc;                     /* Error code from preupdate_new/old */
171142      int eType = *a++;           /* Type of value from change record */
171143
171144      /* The following calls to preupdate_new() and preupdate_old() can not
171145      ** fail. This is because they cache their return values, and by the
171146      ** time control flows to here they have already been called once from
171147      ** within sessionPreupdateHash(). The first two asserts below verify
171148      ** this (that the method has already been called). */
171149      if( op==SQLITE_INSERT ){
171150        /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
171151        rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
171152      }else{
171153        /* assert( db->pPreUpdate->pUnpacked ); */
171154        rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
171155      }
171156      assert( rc==SQLITE_OK );
171157      if( sqlite3_value_type(pVal)!=eType ) return 0;
171158
171159      /* A SessionChange object never has a NULL value in a PK column */
171160      assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
171161           || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
171162      );
171163
171164      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171165        i64 iVal = sessionGetI64(a);
171166        a += 8;
171167        if( eType==SQLITE_INTEGER ){
171168          if( sqlite3_value_int64(pVal)!=iVal ) return 0;
171169        }else{
171170          double rVal;
171171          assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
171172          memcpy(&rVal, &iVal, 8);
171173          if( sqlite3_value_double(pVal)!=rVal ) return 0;
171174        }
171175      }else{
171176        int n;
171177        const u8 *z;
171178        a += sessionVarintGet(a, &n);
171179        if( sqlite3_value_bytes(pVal)!=n ) return 0;
171180        if( eType==SQLITE_TEXT ){
171181          z = sqlite3_value_text(pVal);
171182        }else{
171183          z = sqlite3_value_blob(pVal);
171184        }
171185        if( memcmp(a, z, n) ) return 0;
171186        a += n;
171187        break;
171188      }
171189    }
171190  }
171191
171192  return 1;
171193}
171194
171195/*
171196** If required, grow the hash table used to store changes on table pTab
171197** (part of the session pSession). If a fatal OOM error occurs, set the
171198** session object to failed and return SQLITE_ERROR. Otherwise, return
171199** SQLITE_OK.
171200**
171201** It is possible that a non-fatal OOM error occurs in this function. In
171202** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
171203** Growing the hash table in this case is a performance optimization only,
171204** it is not required for correct operation.
171205*/
171206static int sessionGrowHash(int bPatchset, SessionTable *pTab){
171207  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
171208    int i;
171209    SessionChange **apNew;
171210    int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
171211
171212    apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
171213    if( apNew==0 ){
171214      if( pTab->nChange==0 ){
171215        return SQLITE_ERROR;
171216      }
171217      return SQLITE_OK;
171218    }
171219    memset(apNew, 0, sizeof(SessionChange *) * nNew);
171220
171221    for(i=0; i<pTab->nChange; i++){
171222      SessionChange *p;
171223      SessionChange *pNext;
171224      for(p=pTab->apChange[i]; p; p=pNext){
171225        int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
171226        int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
171227        pNext = p->pNext;
171228        p->pNext = apNew[iHash];
171229        apNew[iHash] = p;
171230      }
171231    }
171232
171233    sqlite3_free(pTab->apChange);
171234    pTab->nChange = nNew;
171235    pTab->apChange = apNew;
171236  }
171237
171238  return SQLITE_OK;
171239}
171240
171241/*
171242** This function queries the database for the names of the columns of table
171243** zThis, in schema zDb. It is expected that the table has nCol columns. If
171244** not, SQLITE_SCHEMA is returned and none of the output variables are
171245** populated.
171246**
171247** Otherwise, if they are not NULL, variable *pnCol is set to the number
171248** of columns in the database table and variable *pzTab is set to point to a
171249** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
171250** point to an array of pointers to column names. And *pabPK (again, if not
171251** NULL) is set to point to an array of booleans - true if the corresponding
171252** column is part of the primary key.
171253**
171254** For example, if the table is declared as:
171255**
171256**     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
171257**
171258** Then the four output variables are populated as follows:
171259**
171260**     *pnCol  = 4
171261**     *pzTab  = "tbl1"
171262**     *pazCol = {"w", "x", "y", "z"}
171263**     *pabPK  = {1, 0, 0, 1}
171264**
171265** All returned buffers are part of the same single allocation, which must
171266** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
171267** pointer *pazCol should be freed to release all memory. Otherwise, pointer
171268** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
171269*/
171270static int sessionTableInfo(
171271  sqlite3 *db,                    /* Database connection */
171272  const char *zDb,                /* Name of attached database (e.g. "main") */
171273  const char *zThis,              /* Table name */
171274  int *pnCol,                     /* OUT: number of columns */
171275  const char **pzTab,             /* OUT: Copy of zThis */
171276  const char ***pazCol,           /* OUT: Array of column names for table */
171277  u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
171278){
171279  char *zPragma;
171280  sqlite3_stmt *pStmt;
171281  int rc;
171282  int nByte;
171283  int nDbCol = 0;
171284  int nThis;
171285  int i;
171286  u8 *pAlloc = 0;
171287  char **azCol = 0;
171288  u8 *abPK = 0;
171289
171290  assert( pazCol && pabPK );
171291
171292  nThis = sqlite3Strlen30(zThis);
171293  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
171294  if( !zPragma ) return SQLITE_NOMEM;
171295
171296  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
171297  sqlite3_free(zPragma);
171298  if( rc!=SQLITE_OK ) return rc;
171299
171300  nByte = nThis + 1;
171301  while( SQLITE_ROW==sqlite3_step(pStmt) ){
171302    nByte += sqlite3_column_bytes(pStmt, 1);
171303    nDbCol++;
171304  }
171305  rc = sqlite3_reset(pStmt);
171306
171307  if( rc==SQLITE_OK ){
171308    nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
171309    pAlloc = sqlite3_malloc(nByte);
171310    if( pAlloc==0 ){
171311      rc = SQLITE_NOMEM;
171312    }
171313  }
171314  if( rc==SQLITE_OK ){
171315    azCol = (char **)pAlloc;
171316    pAlloc = (u8 *)&azCol[nDbCol];
171317    abPK = (u8 *)pAlloc;
171318    pAlloc = &abPK[nDbCol];
171319    if( pzTab ){
171320      memcpy(pAlloc, zThis, nThis+1);
171321      *pzTab = (char *)pAlloc;
171322      pAlloc += nThis+1;
171323    }
171324
171325    i = 0;
171326    while( SQLITE_ROW==sqlite3_step(pStmt) ){
171327      int nName = sqlite3_column_bytes(pStmt, 1);
171328      const unsigned char *zName = sqlite3_column_text(pStmt, 1);
171329      if( zName==0 ) break;
171330      memcpy(pAlloc, zName, nName+1);
171331      azCol[i] = (char *)pAlloc;
171332      pAlloc += nName+1;
171333      abPK[i] = sqlite3_column_int(pStmt, 5);
171334      i++;
171335    }
171336    rc = sqlite3_reset(pStmt);
171337
171338  }
171339
171340  /* If successful, populate the output variables. Otherwise, zero them and
171341  ** free any allocation made. An error code will be returned in this case.
171342  */
171343  if( rc==SQLITE_OK ){
171344    *pazCol = (const char **)azCol;
171345    *pabPK = abPK;
171346    *pnCol = nDbCol;
171347  }else{
171348    *pazCol = 0;
171349    *pabPK = 0;
171350    *pnCol = 0;
171351    if( pzTab ) *pzTab = 0;
171352    sqlite3_free(azCol);
171353  }
171354  sqlite3_finalize(pStmt);
171355  return rc;
171356}
171357
171358/*
171359** This function is only called from within a pre-update handler for a
171360** write to table pTab, part of session pSession. If this is the first
171361** write to this table, initalize the SessionTable.nCol, azCol[] and
171362** abPK[] arrays accordingly.
171363**
171364** If an error occurs, an error code is stored in sqlite3_session.rc and
171365** non-zero returned. Or, if no error occurs but the table has no primary
171366** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
171367** indicate that updates on this table should be ignored. SessionTable.abPK
171368** is set to NULL in this case.
171369*/
171370static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
171371  if( pTab->nCol==0 ){
171372    u8 *abPK;
171373    assert( pTab->azCol==0 || pTab->abPK==0 );
171374    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
171375        pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
171376    );
171377    if( pSession->rc==SQLITE_OK ){
171378      int i;
171379      for(i=0; i<pTab->nCol; i++){
171380        if( abPK[i] ){
171381          pTab->abPK = abPK;
171382          break;
171383        }
171384      }
171385    }
171386  }
171387  return (pSession->rc || pTab->abPK==0);
171388}
171389
171390/*
171391** This function is only called from with a pre-update-hook reporting a
171392** change on table pTab (attached to session pSession). The type of change
171393** (UPDATE, INSERT, DELETE) is specified by the first argument.
171394**
171395** Unless one is already present or an error occurs, an entry is added
171396** to the changed-rows hash table associated with table pTab.
171397*/
171398static void sessionPreupdateOneChange(
171399  int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
171400  sqlite3_session *pSession,      /* Session object pTab is attached to */
171401  SessionTable *pTab              /* Table that change applies to */
171402){
171403  int iHash;
171404  int bNull = 0;
171405  int rc = SQLITE_OK;
171406
171407  if( pSession->rc ) return;
171408
171409  /* Load table details if required */
171410  if( sessionInitTable(pSession, pTab) ) return;
171411
171412  /* Check the number of columns in this xPreUpdate call matches the
171413  ** number of columns in the table.  */
171414  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
171415    pSession->rc = SQLITE_SCHEMA;
171416    return;
171417  }
171418
171419  /* Grow the hash table if required */
171420  if( sessionGrowHash(0, pTab) ){
171421    pSession->rc = SQLITE_NOMEM;
171422    return;
171423  }
171424
171425  /* Calculate the hash-key for this change. If the primary key of the row
171426  ** includes a NULL value, exit early. Such changes are ignored by the
171427  ** session module. */
171428  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
171429  if( rc!=SQLITE_OK ) goto error_out;
171430
171431  if( bNull==0 ){
171432    /* Search the hash table for an existing record for this row. */
171433    SessionChange *pC;
171434    for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
171435      if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
171436    }
171437
171438    if( pC==0 ){
171439      /* Create a new change object containing all the old values (if
171440      ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
171441      ** values (if this is an INSERT). */
171442      SessionChange *pChange; /* New change object */
171443      int nByte;              /* Number of bytes to allocate */
171444      int i;                  /* Used to iterate through columns */
171445
171446      assert( rc==SQLITE_OK );
171447      pTab->nEntry++;
171448
171449      /* Figure out how large an allocation is required */
171450      nByte = sizeof(SessionChange);
171451      for(i=0; i<pTab->nCol; i++){
171452        sqlite3_value *p = 0;
171453        if( op!=SQLITE_INSERT ){
171454          TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
171455          assert( trc==SQLITE_OK );
171456        }else if( pTab->abPK[i] ){
171457          TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
171458          assert( trc==SQLITE_OK );
171459        }
171460
171461        /* This may fail if SQLite value p contains a utf-16 string that must
171462        ** be converted to utf-8 and an OOM error occurs while doing so. */
171463        rc = sessionSerializeValue(0, p, &nByte);
171464        if( rc!=SQLITE_OK ) goto error_out;
171465      }
171466
171467      /* Allocate the change object */
171468      pChange = (SessionChange *)sqlite3_malloc(nByte);
171469      if( !pChange ){
171470        rc = SQLITE_NOMEM;
171471        goto error_out;
171472      }else{
171473        memset(pChange, 0, sizeof(SessionChange));
171474        pChange->aRecord = (u8 *)&pChange[1];
171475      }
171476
171477      /* Populate the change object. None of the preupdate_old(),
171478      ** preupdate_new() or SerializeValue() calls below may fail as all
171479      ** required values and encodings have already been cached in memory.
171480      ** It is not possible for an OOM to occur in this block. */
171481      nByte = 0;
171482      for(i=0; i<pTab->nCol; i++){
171483        sqlite3_value *p = 0;
171484        if( op!=SQLITE_INSERT ){
171485          pSession->hook.xOld(pSession->hook.pCtx, i, &p);
171486        }else if( pTab->abPK[i] ){
171487          pSession->hook.xNew(pSession->hook.pCtx, i, &p);
171488        }
171489        sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
171490      }
171491
171492      /* Add the change to the hash-table */
171493      if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
171494        pChange->bIndirect = 1;
171495      }
171496      pChange->nRecord = nByte;
171497      pChange->op = op;
171498      pChange->pNext = pTab->apChange[iHash];
171499      pTab->apChange[iHash] = pChange;
171500
171501    }else if( pC->bIndirect ){
171502      /* If the existing change is considered "indirect", but this current
171503      ** change is "direct", mark the change object as direct. */
171504      if( pSession->hook.xDepth(pSession->hook.pCtx)==0
171505       && pSession->bIndirect==0
171506      ){
171507        pC->bIndirect = 0;
171508      }
171509    }
171510  }
171511
171512  /* If an error has occurred, mark the session object as failed. */
171513 error_out:
171514  if( rc!=SQLITE_OK ){
171515    pSession->rc = rc;
171516  }
171517}
171518
171519static int sessionFindTable(
171520  sqlite3_session *pSession,
171521  const char *zName,
171522  SessionTable **ppTab
171523){
171524  int rc = SQLITE_OK;
171525  int nName = sqlite3Strlen30(zName);
171526  SessionTable *pRet;
171527
171528  /* Search for an existing table */
171529  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
171530    if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
171531  }
171532
171533  if( pRet==0 && pSession->bAutoAttach ){
171534    /* If there is a table-filter configured, invoke it. If it returns 0,
171535    ** do not automatically add the new table. */
171536    if( pSession->xTableFilter==0
171537     || pSession->xTableFilter(pSession->pFilterCtx, zName)
171538    ){
171539      rc = sqlite3session_attach(pSession, zName);
171540      if( rc==SQLITE_OK ){
171541        for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
171542        assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
171543      }
171544    }
171545  }
171546
171547  assert( rc==SQLITE_OK || pRet==0 );
171548  *ppTab = pRet;
171549  return rc;
171550}
171551
171552/*
171553** The 'pre-update' hook registered by this module with SQLite databases.
171554*/
171555static void xPreUpdate(
171556  void *pCtx,                     /* Copy of third arg to preupdate_hook() */
171557  sqlite3 *db,                    /* Database handle */
171558  int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
171559  char const *zDb,                /* Database name */
171560  char const *zName,              /* Table name */
171561  sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
171562  sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
171563){
171564  sqlite3_session *pSession;
171565  int nDb = sqlite3Strlen30(zDb);
171566
171567  assert( sqlite3_mutex_held(db->mutex) );
171568
171569  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
171570    SessionTable *pTab;
171571
171572    /* If this session is attached to a different database ("main", "temp"
171573    ** etc.), or if it is not currently enabled, there is nothing to do. Skip
171574    ** to the next session object attached to this database. */
171575    if( pSession->bEnable==0 ) continue;
171576    if( pSession->rc ) continue;
171577    if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
171578
171579    pSession->rc = sessionFindTable(pSession, zName, &pTab);
171580    if( pTab ){
171581      assert( pSession->rc==SQLITE_OK );
171582      sessionPreupdateOneChange(op, pSession, pTab);
171583      if( op==SQLITE_UPDATE ){
171584        sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
171585      }
171586    }
171587  }
171588}
171589
171590/*
171591** The pre-update hook implementations.
171592*/
171593static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
171594  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
171595}
171596static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
171597  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
171598}
171599static int sessionPreupdateCount(void *pCtx){
171600  return sqlite3_preupdate_count((sqlite3*)pCtx);
171601}
171602static int sessionPreupdateDepth(void *pCtx){
171603  return sqlite3_preupdate_depth((sqlite3*)pCtx);
171604}
171605
171606/*
171607** Install the pre-update hooks on the session object passed as the only
171608** argument.
171609*/
171610static void sessionPreupdateHooks(
171611  sqlite3_session *pSession
171612){
171613  pSession->hook.pCtx = (void*)pSession->db;
171614  pSession->hook.xOld = sessionPreupdateOld;
171615  pSession->hook.xNew = sessionPreupdateNew;
171616  pSession->hook.xCount = sessionPreupdateCount;
171617  pSession->hook.xDepth = sessionPreupdateDepth;
171618}
171619
171620typedef struct SessionDiffCtx SessionDiffCtx;
171621struct SessionDiffCtx {
171622  sqlite3_stmt *pStmt;
171623  int nOldOff;
171624};
171625
171626/*
171627** The diff hook implementations.
171628*/
171629static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
171630  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171631  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
171632  return SQLITE_OK;
171633}
171634static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
171635  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171636  *ppVal = sqlite3_column_value(p->pStmt, iVal);
171637   return SQLITE_OK;
171638}
171639static int sessionDiffCount(void *pCtx){
171640  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171641  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
171642}
171643static int sessionDiffDepth(void *pCtx){
171644  return 0;
171645}
171646
171647/*
171648** Install the diff hooks on the session object passed as the only
171649** argument.
171650*/
171651static void sessionDiffHooks(
171652  sqlite3_session *pSession,
171653  SessionDiffCtx *pDiffCtx
171654){
171655  pSession->hook.pCtx = (void*)pDiffCtx;
171656  pSession->hook.xOld = sessionDiffOld;
171657  pSession->hook.xNew = sessionDiffNew;
171658  pSession->hook.xCount = sessionDiffCount;
171659  pSession->hook.xDepth = sessionDiffDepth;
171660}
171661
171662static char *sessionExprComparePK(
171663  int nCol,
171664  const char *zDb1, const char *zDb2,
171665  const char *zTab,
171666  const char **azCol, u8 *abPK
171667){
171668  int i;
171669  const char *zSep = "";
171670  char *zRet = 0;
171671
171672  for(i=0; i<nCol; i++){
171673    if( abPK[i] ){
171674      zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
171675          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
171676      );
171677      zSep = " AND ";
171678      if( zRet==0 ) break;
171679    }
171680  }
171681
171682  return zRet;
171683}
171684
171685static char *sessionExprCompareOther(
171686  int nCol,
171687  const char *zDb1, const char *zDb2,
171688  const char *zTab,
171689  const char **azCol, u8 *abPK
171690){
171691  int i;
171692  const char *zSep = "";
171693  char *zRet = 0;
171694  int bHave = 0;
171695
171696  for(i=0; i<nCol; i++){
171697    if( abPK[i]==0 ){
171698      bHave = 1;
171699      zRet = sqlite3_mprintf(
171700          "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
171701          zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
171702      );
171703      zSep = " OR ";
171704      if( zRet==0 ) break;
171705    }
171706  }
171707
171708  if( bHave==0 ){
171709    assert( zRet==0 );
171710    zRet = sqlite3_mprintf("0");
171711  }
171712
171713  return zRet;
171714}
171715
171716static char *sessionSelectFindNew(
171717  int nCol,
171718  const char *zDb1,      /* Pick rows in this db only */
171719  const char *zDb2,      /* But not in this one */
171720  const char *zTbl,      /* Table name */
171721  const char *zExpr
171722){
171723  char *zRet = sqlite3_mprintf(
171724      "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
171725      "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
171726      ")",
171727      zDb1, zTbl, zDb2, zTbl, zExpr
171728  );
171729  return zRet;
171730}
171731
171732static int sessionDiffFindNew(
171733  int op,
171734  sqlite3_session *pSession,
171735  SessionTable *pTab,
171736  const char *zDb1,
171737  const char *zDb2,
171738  char *zExpr
171739){
171740  int rc = SQLITE_OK;
171741  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
171742
171743  if( zStmt==0 ){
171744    rc = SQLITE_NOMEM;
171745  }else{
171746    sqlite3_stmt *pStmt;
171747    rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
171748    if( rc==SQLITE_OK ){
171749      SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
171750      pDiffCtx->pStmt = pStmt;
171751      pDiffCtx->nOldOff = 0;
171752      while( SQLITE_ROW==sqlite3_step(pStmt) ){
171753        sessionPreupdateOneChange(op, pSession, pTab);
171754      }
171755      rc = sqlite3_finalize(pStmt);
171756    }
171757    sqlite3_free(zStmt);
171758  }
171759
171760  return rc;
171761}
171762
171763static int sessionDiffFindModified(
171764  sqlite3_session *pSession,
171765  SessionTable *pTab,
171766  const char *zFrom,
171767  const char *zExpr
171768){
171769  int rc = SQLITE_OK;
171770
171771  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
171772      pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
171773  );
171774  if( zExpr2==0 ){
171775    rc = SQLITE_NOMEM;
171776  }else{
171777    char *zStmt = sqlite3_mprintf(
171778        "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
171779        pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
171780    );
171781    if( zStmt==0 ){
171782      rc = SQLITE_NOMEM;
171783    }else{
171784      sqlite3_stmt *pStmt;
171785      rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
171786
171787      if( rc==SQLITE_OK ){
171788        SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
171789        pDiffCtx->pStmt = pStmt;
171790        pDiffCtx->nOldOff = pTab->nCol;
171791        while( SQLITE_ROW==sqlite3_step(pStmt) ){
171792          sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
171793        }
171794        rc = sqlite3_finalize(pStmt);
171795      }
171796      sqlite3_free(zStmt);
171797    }
171798  }
171799
171800  return rc;
171801}
171802
171803SQLITE_API int SQLITE_STDCALL sqlite3session_diff(
171804  sqlite3_session *pSession,
171805  const char *zFrom,
171806  const char *zTbl,
171807  char **pzErrMsg
171808){
171809  const char *zDb = pSession->zDb;
171810  int rc = pSession->rc;
171811  SessionDiffCtx d;
171812
171813  memset(&d, 0, sizeof(d));
171814  sessionDiffHooks(pSession, &d);
171815
171816  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171817  if( pzErrMsg ) *pzErrMsg = 0;
171818  if( rc==SQLITE_OK ){
171819    char *zExpr = 0;
171820    sqlite3 *db = pSession->db;
171821    SessionTable *pTo;            /* Table zTbl */
171822
171823    /* Locate and if necessary initialize the target table object */
171824    rc = sessionFindTable(pSession, zTbl, &pTo);
171825    if( pTo==0 ) goto diff_out;
171826    if( sessionInitTable(pSession, pTo) ){
171827      rc = pSession->rc;
171828      goto diff_out;
171829    }
171830
171831    /* Check the table schemas match */
171832    if( rc==SQLITE_OK ){
171833      int bHasPk = 0;
171834      int bMismatch = 0;
171835      int nCol;                   /* Columns in zFrom.zTbl */
171836      u8 *abPK;
171837      const char **azCol = 0;
171838      rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
171839      if( rc==SQLITE_OK ){
171840        if( pTo->nCol!=nCol ){
171841          bMismatch = 1;
171842        }else{
171843          int i;
171844          for(i=0; i<nCol; i++){
171845            if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
171846            if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
171847            if( abPK[i] ) bHasPk = 1;
171848          }
171849        }
171850
171851      }
171852      sqlite3_free((char*)azCol);
171853      if( bMismatch ){
171854        *pzErrMsg = sqlite3_mprintf("table schemas do not match");
171855        rc = SQLITE_SCHEMA;
171856      }
171857      if( bHasPk==0 ){
171858        /* Ignore tables with no primary keys */
171859        goto diff_out;
171860      }
171861    }
171862
171863    if( rc==SQLITE_OK ){
171864      zExpr = sessionExprComparePK(pTo->nCol,
171865          zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
171866      );
171867    }
171868
171869    /* Find new rows */
171870    if( rc==SQLITE_OK ){
171871      rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
171872    }
171873
171874    /* Find old rows */
171875    if( rc==SQLITE_OK ){
171876      rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
171877    }
171878
171879    /* Find modified rows */
171880    if( rc==SQLITE_OK ){
171881      rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
171882    }
171883
171884    sqlite3_free(zExpr);
171885  }
171886
171887 diff_out:
171888  sessionPreupdateHooks(pSession);
171889  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171890  return rc;
171891}
171892
171893/*
171894** Create a session object. This session object will record changes to
171895** database zDb attached to connection db.
171896*/
171897SQLITE_API int SQLITE_STDCALL sqlite3session_create(
171898  sqlite3 *db,                    /* Database handle */
171899  const char *zDb,                /* Name of db (e.g. "main") */
171900  sqlite3_session **ppSession     /* OUT: New session object */
171901){
171902  sqlite3_session *pNew;          /* Newly allocated session object */
171903  sqlite3_session *pOld;          /* Session object already attached to db */
171904  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
171905
171906  /* Zero the output value in case an error occurs. */
171907  *ppSession = 0;
171908
171909  /* Allocate and populate the new session object. */
171910  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
171911  if( !pNew ) return SQLITE_NOMEM;
171912  memset(pNew, 0, sizeof(sqlite3_session));
171913  pNew->db = db;
171914  pNew->zDb = (char *)&pNew[1];
171915  pNew->bEnable = 1;
171916  memcpy(pNew->zDb, zDb, nDb+1);
171917  sessionPreupdateHooks(pNew);
171918
171919  /* Add the new session object to the linked list of session objects
171920  ** attached to database handle $db. Do this under the cover of the db
171921  ** handle mutex.  */
171922  sqlite3_mutex_enter(sqlite3_db_mutex(db));
171923  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
171924  pNew->pNext = pOld;
171925  sqlite3_mutex_leave(sqlite3_db_mutex(db));
171926
171927  *ppSession = pNew;
171928  return SQLITE_OK;
171929}
171930
171931/*
171932** Free the list of table objects passed as the first argument. The contents
171933** of the changed-rows hash tables are also deleted.
171934*/
171935static void sessionDeleteTable(SessionTable *pList){
171936  SessionTable *pNext;
171937  SessionTable *pTab;
171938
171939  for(pTab=pList; pTab; pTab=pNext){
171940    int i;
171941    pNext = pTab->pNext;
171942    for(i=0; i<pTab->nChange; i++){
171943      SessionChange *p;
171944      SessionChange *pNextChange;
171945      for(p=pTab->apChange[i]; p; p=pNextChange){
171946        pNextChange = p->pNext;
171947        sqlite3_free(p);
171948      }
171949    }
171950    sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
171951    sqlite3_free(pTab->apChange);
171952    sqlite3_free(pTab);
171953  }
171954}
171955
171956/*
171957** Delete a session object previously allocated using sqlite3session_create().
171958*/
171959SQLITE_API void SQLITE_STDCALL sqlite3session_delete(sqlite3_session *pSession){
171960  sqlite3 *db = pSession->db;
171961  sqlite3_session *pHead;
171962  sqlite3_session **pp;
171963
171964  /* Unlink the session from the linked list of sessions attached to the
171965  ** database handle. Hold the db mutex while doing so.  */
171966  sqlite3_mutex_enter(sqlite3_db_mutex(db));
171967  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
171968  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
171969    if( (*pp)==pSession ){
171970      *pp = (*pp)->pNext;
171971      if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
171972      break;
171973    }
171974  }
171975  sqlite3_mutex_leave(sqlite3_db_mutex(db));
171976
171977  /* Delete all attached table objects. And the contents of their
171978  ** associated hash-tables. */
171979  sessionDeleteTable(pSession->pTable);
171980
171981  /* Free the session object itself. */
171982  sqlite3_free(pSession);
171983}
171984
171985/*
171986** Set a table filter on a Session Object.
171987*/
171988SQLITE_API void SQLITE_STDCALL sqlite3session_table_filter(
171989  sqlite3_session *pSession,
171990  int(*xFilter)(void*, const char*),
171991  void *pCtx                      /* First argument passed to xFilter */
171992){
171993  pSession->bAutoAttach = 1;
171994  pSession->pFilterCtx = pCtx;
171995  pSession->xTableFilter = xFilter;
171996}
171997
171998/*
171999** Attach a table to a session. All subsequent changes made to the table
172000** while the session object is enabled will be recorded.
172001**
172002** Only tables that have a PRIMARY KEY defined may be attached. It does
172003** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
172004** or not.
172005*/
172006SQLITE_API int SQLITE_STDCALL sqlite3session_attach(
172007  sqlite3_session *pSession,      /* Session object */
172008  const char *zName               /* Table name */
172009){
172010  int rc = SQLITE_OK;
172011  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172012
172013  if( !zName ){
172014    pSession->bAutoAttach = 1;
172015  }else{
172016    SessionTable *pTab;           /* New table object (if required) */
172017    int nName;                    /* Number of bytes in string zName */
172018
172019    /* First search for an existing entry. If one is found, this call is
172020    ** a no-op. Return early. */
172021    nName = sqlite3Strlen30(zName);
172022    for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
172023      if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
172024    }
172025
172026    if( !pTab ){
172027      /* Allocate new SessionTable object. */
172028      pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
172029      if( !pTab ){
172030        rc = SQLITE_NOMEM;
172031      }else{
172032        /* Populate the new SessionTable object and link it into the list.
172033        ** The new object must be linked onto the end of the list, not
172034        ** simply added to the start of it in order to ensure that tables
172035        ** appear in the correct order when a changeset or patchset is
172036        ** eventually generated. */
172037        SessionTable **ppTab;
172038        memset(pTab, 0, sizeof(SessionTable));
172039        pTab->zName = (char *)&pTab[1];
172040        memcpy(pTab->zName, zName, nName+1);
172041        for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
172042        *ppTab = pTab;
172043      }
172044    }
172045  }
172046
172047  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172048  return rc;
172049}
172050
172051/*
172052** Ensure that there is room in the buffer to append nByte bytes of data.
172053** If not, use sqlite3_realloc() to grow the buffer so that there is.
172054**
172055** If successful, return zero. Otherwise, if an OOM condition is encountered,
172056** set *pRc to SQLITE_NOMEM and return non-zero.
172057*/
172058static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
172059  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
172060    u8 *aNew;
172061    int nNew = p->nAlloc ? p->nAlloc : 128;
172062    do {
172063      nNew = nNew*2;
172064    }while( nNew<(p->nBuf+nByte) );
172065
172066    aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
172067    if( 0==aNew ){
172068      *pRc = SQLITE_NOMEM;
172069    }else{
172070      p->aBuf = aNew;
172071      p->nAlloc = nNew;
172072    }
172073  }
172074  return (*pRc!=SQLITE_OK);
172075}
172076
172077/*
172078** Append the value passed as the second argument to the buffer passed
172079** as the first.
172080**
172081** This function is a no-op if *pRc is non-zero when it is called.
172082** Otherwise, if an error occurs, *pRc is set to an SQLite error code
172083** before returning.
172084*/
172085static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
172086  int rc = *pRc;
172087  if( rc==SQLITE_OK ){
172088    int nByte = 0;
172089    rc = sessionSerializeValue(0, pVal, &nByte);
172090    sessionBufferGrow(p, nByte, &rc);
172091    if( rc==SQLITE_OK ){
172092      rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
172093      p->nBuf += nByte;
172094    }else{
172095      *pRc = rc;
172096    }
172097  }
172098}
172099
172100/*
172101** This function is a no-op if *pRc is other than SQLITE_OK when it is
172102** called. Otherwise, append a single byte to the buffer.
172103**
172104** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172105** returning.
172106*/
172107static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
172108  if( 0==sessionBufferGrow(p, 1, pRc) ){
172109    p->aBuf[p->nBuf++] = v;
172110  }
172111}
172112
172113/*
172114** This function is a no-op if *pRc is other than SQLITE_OK when it is
172115** called. Otherwise, append a single varint to the buffer.
172116**
172117** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172118** returning.
172119*/
172120static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
172121  if( 0==sessionBufferGrow(p, 9, pRc) ){
172122    p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
172123  }
172124}
172125
172126/*
172127** This function is a no-op if *pRc is other than SQLITE_OK when it is
172128** called. Otherwise, append a blob of data to the buffer.
172129**
172130** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172131** returning.
172132*/
172133static void sessionAppendBlob(
172134  SessionBuffer *p,
172135  const u8 *aBlob,
172136  int nBlob,
172137  int *pRc
172138){
172139  if( 0==sessionBufferGrow(p, nBlob, pRc) ){
172140    memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
172141    p->nBuf += nBlob;
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 a string to the buffer. All bytes in the string
172148** up to (but not including) the nul-terminator are written to the buffer.
172149**
172150** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172151** returning.
172152*/
172153static void sessionAppendStr(
172154  SessionBuffer *p,
172155  const char *zStr,
172156  int *pRc
172157){
172158  int nStr = sqlite3Strlen30(zStr);
172159  if( 0==sessionBufferGrow(p, nStr, pRc) ){
172160    memcpy(&p->aBuf[p->nBuf], zStr, nStr);
172161    p->nBuf += nStr;
172162  }
172163}
172164
172165/*
172166** This function is a no-op if *pRc is other than SQLITE_OK when it is
172167** called. Otherwise, append the string representation of integer iVal
172168** to the buffer. No nul-terminator is written.
172169**
172170** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172171** returning.
172172*/
172173static void sessionAppendInteger(
172174  SessionBuffer *p,               /* Buffer to append to */
172175  int iVal,                       /* Value to write the string rep. of */
172176  int *pRc                        /* IN/OUT: Error code */
172177){
172178  char aBuf[24];
172179  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
172180  sessionAppendStr(p, aBuf, pRc);
172181}
172182
172183/*
172184** This function is a no-op if *pRc is other than SQLITE_OK when it is
172185** called. Otherwise, append the string zStr enclosed in quotes (") and
172186** with any embedded quote characters escaped to the buffer. No
172187** nul-terminator byte is written.
172188**
172189** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172190** returning.
172191*/
172192static void sessionAppendIdent(
172193  SessionBuffer *p,               /* Buffer to a append to */
172194  const char *zStr,               /* String to quote, escape and append */
172195  int *pRc                        /* IN/OUT: Error code */
172196){
172197  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
172198  if( 0==sessionBufferGrow(p, nStr, pRc) ){
172199    char *zOut = (char *)&p->aBuf[p->nBuf];
172200    const char *zIn = zStr;
172201    *zOut++ = '"';
172202    while( *zIn ){
172203      if( *zIn=='"' ) *zOut++ = '"';
172204      *zOut++ = *(zIn++);
172205    }
172206    *zOut++ = '"';
172207    p->nBuf = (int)((u8 *)zOut - p->aBuf);
172208  }
172209}
172210
172211/*
172212** This function is a no-op if *pRc is other than SQLITE_OK when it is
172213** called. Otherwse, it appends the serialized version of the value stored
172214** in column iCol of the row that SQL statement pStmt currently points
172215** to to the buffer.
172216*/
172217static void sessionAppendCol(
172218  SessionBuffer *p,               /* Buffer to append to */
172219  sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
172220  int iCol,                       /* Column to read value from */
172221  int *pRc                        /* IN/OUT: Error code */
172222){
172223  if( *pRc==SQLITE_OK ){
172224    int eType = sqlite3_column_type(pStmt, iCol);
172225    sessionAppendByte(p, (u8)eType, pRc);
172226    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172227      sqlite3_int64 i;
172228      u8 aBuf[8];
172229      if( eType==SQLITE_INTEGER ){
172230        i = sqlite3_column_int64(pStmt, iCol);
172231      }else{
172232        double r = sqlite3_column_double(pStmt, iCol);
172233        memcpy(&i, &r, 8);
172234      }
172235      sessionPutI64(aBuf, i);
172236      sessionAppendBlob(p, aBuf, 8, pRc);
172237    }
172238    if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
172239      u8 *z;
172240      int nByte;
172241      if( eType==SQLITE_BLOB ){
172242        z = (u8 *)sqlite3_column_blob(pStmt, iCol);
172243      }else{
172244        z = (u8 *)sqlite3_column_text(pStmt, iCol);
172245      }
172246      nByte = sqlite3_column_bytes(pStmt, iCol);
172247      if( z || (eType==SQLITE_BLOB && nByte==0) ){
172248        sessionAppendVarint(p, nByte, pRc);
172249        sessionAppendBlob(p, z, nByte, pRc);
172250      }else{
172251        *pRc = SQLITE_NOMEM;
172252      }
172253    }
172254  }
172255}
172256
172257/*
172258**
172259** This function appends an update change to the buffer (see the comments
172260** under "CHANGESET FORMAT" at the top of the file). An update change
172261** consists of:
172262**
172263**   1 byte:  SQLITE_UPDATE (0x17)
172264**   n bytes: old.* record (see RECORD FORMAT)
172265**   m bytes: new.* record (see RECORD FORMAT)
172266**
172267** The SessionChange object passed as the third argument contains the
172268** values that were stored in the row when the session began (the old.*
172269** values). The statement handle passed as the second argument points
172270** at the current version of the row (the new.* values).
172271**
172272** If all of the old.* values are equal to their corresponding new.* value
172273** (i.e. nothing has changed), then no data at all is appended to the buffer.
172274**
172275** Otherwise, the old.* record contains all primary key values and the
172276** original values of any fields that have been modified. The new.* record
172277** contains the new values of only those fields that have been modified.
172278*/
172279static int sessionAppendUpdate(
172280  SessionBuffer *pBuf,            /* Buffer to append to */
172281  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
172282  sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
172283  SessionChange *p,               /* Object containing old values */
172284  u8 *abPK                        /* Boolean array - true for PK columns */
172285){
172286  int rc = SQLITE_OK;
172287  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
172288  int bNoop = 1;                /* Set to zero if any values are modified */
172289  int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
172290  int i;                        /* Used to iterate through columns */
172291  u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
172292
172293  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
172294  sessionAppendByte(pBuf, p->bIndirect, &rc);
172295  for(i=0; i<sqlite3_column_count(pStmt); i++){
172296    int bChanged = 0;
172297    int nAdvance;
172298    int eType = *pCsr;
172299    switch( eType ){
172300      case SQLITE_NULL:
172301        nAdvance = 1;
172302        if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
172303          bChanged = 1;
172304        }
172305        break;
172306
172307      case SQLITE_FLOAT:
172308      case SQLITE_INTEGER: {
172309        nAdvance = 9;
172310        if( eType==sqlite3_column_type(pStmt, i) ){
172311          sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
172312          if( eType==SQLITE_INTEGER ){
172313            if( iVal==sqlite3_column_int64(pStmt, i) ) break;
172314          }else{
172315            double dVal;
172316            memcpy(&dVal, &iVal, 8);
172317            if( dVal==sqlite3_column_double(pStmt, i) ) break;
172318          }
172319        }
172320        bChanged = 1;
172321        break;
172322      }
172323
172324      default: {
172325        int nByte;
172326        int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
172327        assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
172328        nAdvance = nHdr + nByte;
172329        if( eType==sqlite3_column_type(pStmt, i)
172330         && nByte==sqlite3_column_bytes(pStmt, i)
172331         && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
172332        ){
172333          break;
172334        }
172335        bChanged = 1;
172336      }
172337    }
172338
172339    /* If at least one field has been modified, this is not a no-op. */
172340    if( bChanged ) bNoop = 0;
172341
172342    /* Add a field to the old.* record. This is omitted if this modules is
172343    ** currently generating a patchset. */
172344    if( bPatchset==0 ){
172345      if( bChanged || abPK[i] ){
172346        sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
172347      }else{
172348        sessionAppendByte(pBuf, 0, &rc);
172349      }
172350    }
172351
172352    /* Add a field to the new.* record. Or the only record if currently
172353    ** generating a patchset.  */
172354    if( bChanged || (bPatchset && abPK[i]) ){
172355      sessionAppendCol(&buf2, pStmt, i, &rc);
172356    }else{
172357      sessionAppendByte(&buf2, 0, &rc);
172358    }
172359
172360    pCsr += nAdvance;
172361  }
172362
172363  if( bNoop ){
172364    pBuf->nBuf = nRewind;
172365  }else{
172366    sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
172367  }
172368  sqlite3_free(buf2.aBuf);
172369
172370  return rc;
172371}
172372
172373/*
172374** Append a DELETE change to the buffer passed as the first argument. Use
172375** the changeset format if argument bPatchset is zero, or the patchset
172376** format otherwise.
172377*/
172378static int sessionAppendDelete(
172379  SessionBuffer *pBuf,            /* Buffer to append to */
172380  int bPatchset,                  /* True for "patchset", 0 for "changeset" */
172381  SessionChange *p,               /* Object containing old values */
172382  int nCol,                       /* Number of columns in table */
172383  u8 *abPK                        /* Boolean array - true for PK columns */
172384){
172385  int rc = SQLITE_OK;
172386
172387  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
172388  sessionAppendByte(pBuf, p->bIndirect, &rc);
172389
172390  if( bPatchset==0 ){
172391    sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
172392  }else{
172393    int i;
172394    u8 *a = p->aRecord;
172395    for(i=0; i<nCol; i++){
172396      u8 *pStart = a;
172397      int eType = *a++;
172398
172399      switch( eType ){
172400        case 0:
172401        case SQLITE_NULL:
172402          assert( abPK[i]==0 );
172403          break;
172404
172405        case SQLITE_FLOAT:
172406        case SQLITE_INTEGER:
172407          a += 8;
172408          break;
172409
172410        default: {
172411          int n;
172412          a += sessionVarintGet(a, &n);
172413          a += n;
172414          break;
172415        }
172416      }
172417      if( abPK[i] ){
172418        sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
172419      }
172420    }
172421    assert( (a - p->aRecord)==p->nRecord );
172422  }
172423
172424  return rc;
172425}
172426
172427/*
172428** Formulate and prepare a SELECT statement to retrieve a row from table
172429** zTab in database zDb based on its primary key. i.e.
172430**
172431**   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
172432*/
172433static int sessionSelectStmt(
172434  sqlite3 *db,                    /* Database handle */
172435  const char *zDb,                /* Database name */
172436  const char *zTab,               /* Table name */
172437  int nCol,                       /* Number of columns in table */
172438  const char **azCol,             /* Names of table columns */
172439  u8 *abPK,                       /* PRIMARY KEY  array */
172440  sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
172441){
172442  int rc = SQLITE_OK;
172443  int i;
172444  const char *zSep = "";
172445  SessionBuffer buf = {0, 0, 0};
172446
172447  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
172448  sessionAppendIdent(&buf, zDb, &rc);
172449  sessionAppendStr(&buf, ".", &rc);
172450  sessionAppendIdent(&buf, zTab, &rc);
172451  sessionAppendStr(&buf, " WHERE ", &rc);
172452  for(i=0; i<nCol; i++){
172453    if( abPK[i] ){
172454      sessionAppendStr(&buf, zSep, &rc);
172455      sessionAppendIdent(&buf, azCol[i], &rc);
172456      sessionAppendStr(&buf, " = ?", &rc);
172457      sessionAppendInteger(&buf, i+1, &rc);
172458      zSep = " AND ";
172459    }
172460  }
172461  if( rc==SQLITE_OK ){
172462    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
172463  }
172464  sqlite3_free(buf.aBuf);
172465  return rc;
172466}
172467
172468/*
172469** Bind the PRIMARY KEY values from the change passed in argument pChange
172470** to the SELECT statement passed as the first argument. The SELECT statement
172471** is as prepared by function sessionSelectStmt().
172472**
172473** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
172474** error code (e.g. SQLITE_NOMEM) otherwise.
172475*/
172476static int sessionSelectBind(
172477  sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
172478  int nCol,                       /* Number of columns in table */
172479  u8 *abPK,                       /* PRIMARY KEY array */
172480  SessionChange *pChange          /* Change structure */
172481){
172482  int i;
172483  int rc = SQLITE_OK;
172484  u8 *a = pChange->aRecord;
172485
172486  for(i=0; i<nCol && rc==SQLITE_OK; i++){
172487    int eType = *a++;
172488
172489    switch( eType ){
172490      case 0:
172491      case SQLITE_NULL:
172492        assert( abPK[i]==0 );
172493        break;
172494
172495      case SQLITE_INTEGER: {
172496        if( abPK[i] ){
172497          i64 iVal = sessionGetI64(a);
172498          rc = sqlite3_bind_int64(pSelect, i+1, iVal);
172499        }
172500        a += 8;
172501        break;
172502      }
172503
172504      case SQLITE_FLOAT: {
172505        if( abPK[i] ){
172506          double rVal;
172507          i64 iVal = sessionGetI64(a);
172508          memcpy(&rVal, &iVal, 8);
172509          rc = sqlite3_bind_double(pSelect, i+1, rVal);
172510        }
172511        a += 8;
172512        break;
172513      }
172514
172515      case SQLITE_TEXT: {
172516        int n;
172517        a += sessionVarintGet(a, &n);
172518        if( abPK[i] ){
172519          rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
172520        }
172521        a += n;
172522        break;
172523      }
172524
172525      default: {
172526        int n;
172527        assert( eType==SQLITE_BLOB );
172528        a += sessionVarintGet(a, &n);
172529        if( abPK[i] ){
172530          rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
172531        }
172532        a += n;
172533        break;
172534      }
172535    }
172536  }
172537
172538  return rc;
172539}
172540
172541/*
172542** This function is a no-op if *pRc is set to other than SQLITE_OK when it
172543** is called. Otherwise, append a serialized table header (part of the binary
172544** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
172545** SQLite error code before returning.
172546*/
172547static void sessionAppendTableHdr(
172548  SessionBuffer *pBuf,            /* Append header to this buffer */
172549  int bPatchset,                  /* Use the patchset format if true */
172550  SessionTable *pTab,             /* Table object to append header for */
172551  int *pRc                        /* IN/OUT: Error code */
172552){
172553  /* Write a table header */
172554  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
172555  sessionAppendVarint(pBuf, pTab->nCol, pRc);
172556  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
172557  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
172558}
172559
172560/*
172561** Generate either a changeset (if argument bPatchset is zero) or a patchset
172562** (if it is non-zero) based on the current contents of the session object
172563** passed as the first argument.
172564**
172565** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
172566** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
172567** occurs, an SQLite error code is returned and both output variables set
172568** to 0.
172569*/
172570static int sessionGenerateChangeset(
172571  sqlite3_session *pSession,      /* Session object */
172572  int bPatchset,                  /* True for patchset, false for changeset */
172573  int (*xOutput)(void *pOut, const void *pData, int nData),
172574  void *pOut,                     /* First argument for xOutput */
172575  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
172576  void **ppChangeset              /* OUT: Buffer containing changeset */
172577){
172578  sqlite3 *db = pSession->db;     /* Source database handle */
172579  SessionTable *pTab;             /* Used to iterate through attached tables */
172580  SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
172581  int rc;                         /* Return code */
172582
172583  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
172584
172585  /* Zero the output variables in case an error occurs. If this session
172586  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
172587  ** this call will be a no-op.  */
172588  if( xOutput==0 ){
172589    *pnChangeset = 0;
172590    *ppChangeset = 0;
172591  }
172592
172593  if( pSession->rc ) return pSession->rc;
172594  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
172595  if( rc!=SQLITE_OK ) return rc;
172596
172597  sqlite3_mutex_enter(sqlite3_db_mutex(db));
172598
172599  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
172600    if( pTab->nEntry ){
172601      const char *zName = pTab->zName;
172602      int nCol;                   /* Number of columns in table */
172603      u8 *abPK;                   /* Primary key array */
172604      const char **azCol = 0;     /* Table columns */
172605      int i;                      /* Used to iterate through hash buckets */
172606      sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
172607      int nRewind = buf.nBuf;     /* Initial size of write buffer */
172608      int nNoop;                  /* Size of buffer after writing tbl header */
172609
172610      /* Check the table schema is still Ok. */
172611      rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
172612      if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
172613        rc = SQLITE_SCHEMA;
172614      }
172615
172616      /* Write a table header */
172617      sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
172618
172619      /* Build and compile a statement to execute: */
172620      if( rc==SQLITE_OK ){
172621        rc = sessionSelectStmt(
172622            db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
172623      }
172624
172625      nNoop = buf.nBuf;
172626      for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
172627        SessionChange *p;         /* Used to iterate through changes */
172628
172629        for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
172630          rc = sessionSelectBind(pSel, nCol, abPK, p);
172631          if( rc!=SQLITE_OK ) continue;
172632          if( sqlite3_step(pSel)==SQLITE_ROW ){
172633            if( p->op==SQLITE_INSERT ){
172634              int iCol;
172635              sessionAppendByte(&buf, SQLITE_INSERT, &rc);
172636              sessionAppendByte(&buf, p->bIndirect, &rc);
172637              for(iCol=0; iCol<nCol; iCol++){
172638                sessionAppendCol(&buf, pSel, iCol, &rc);
172639              }
172640            }else{
172641              rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
172642            }
172643          }else if( p->op!=SQLITE_INSERT ){
172644            rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
172645          }
172646          if( rc==SQLITE_OK ){
172647            rc = sqlite3_reset(pSel);
172648          }
172649
172650          /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
172651          ** its contents to the xOutput() callback. */
172652          if( xOutput
172653           && rc==SQLITE_OK
172654           && buf.nBuf>nNoop
172655           && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
172656          ){
172657            rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
172658            nNoop = -1;
172659            buf.nBuf = 0;
172660          }
172661
172662        }
172663      }
172664
172665      sqlite3_finalize(pSel);
172666      if( buf.nBuf==nNoop ){
172667        buf.nBuf = nRewind;
172668      }
172669      sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
172670    }
172671  }
172672
172673  if( rc==SQLITE_OK ){
172674    if( xOutput==0 ){
172675      *pnChangeset = buf.nBuf;
172676      *ppChangeset = buf.aBuf;
172677      buf.aBuf = 0;
172678    }else if( buf.nBuf>0 ){
172679      rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
172680    }
172681  }
172682
172683  sqlite3_free(buf.aBuf);
172684  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
172685  sqlite3_mutex_leave(sqlite3_db_mutex(db));
172686  return rc;
172687}
172688
172689/*
172690** Obtain a changeset object containing all changes recorded by the
172691** session object passed as the first argument.
172692**
172693** It is the responsibility of the caller to eventually free the buffer
172694** using sqlite3_free().
172695*/
172696SQLITE_API int SQLITE_STDCALL sqlite3session_changeset(
172697  sqlite3_session *pSession,      /* Session object */
172698  int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
172699  void **ppChangeset              /* OUT: Buffer containing changeset */
172700){
172701  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
172702}
172703
172704/*
172705** Streaming version of sqlite3session_changeset().
172706*/
172707SQLITE_API int SQLITE_STDCALL sqlite3session_changeset_strm(
172708  sqlite3_session *pSession,
172709  int (*xOutput)(void *pOut, const void *pData, int nData),
172710  void *pOut
172711){
172712  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
172713}
172714
172715/*
172716** Streaming version of sqlite3session_patchset().
172717*/
172718SQLITE_API int SQLITE_STDCALL sqlite3session_patchset_strm(
172719  sqlite3_session *pSession,
172720  int (*xOutput)(void *pOut, const void *pData, int nData),
172721  void *pOut
172722){
172723  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
172724}
172725
172726/*
172727** Obtain a patchset object containing all changes recorded by the
172728** session object passed as the first argument.
172729**
172730** It is the responsibility of the caller to eventually free the buffer
172731** using sqlite3_free().
172732*/
172733SQLITE_API int SQLITE_STDCALL sqlite3session_patchset(
172734  sqlite3_session *pSession,      /* Session object */
172735  int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
172736  void **ppPatchset               /* OUT: Buffer containing changeset */
172737){
172738  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
172739}
172740
172741/*
172742** Enable or disable the session object passed as the first argument.
172743*/
172744SQLITE_API int SQLITE_STDCALL sqlite3session_enable(sqlite3_session *pSession, int bEnable){
172745  int ret;
172746  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172747  if( bEnable>=0 ){
172748    pSession->bEnable = bEnable;
172749  }
172750  ret = pSession->bEnable;
172751  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172752  return ret;
172753}
172754
172755/*
172756** Enable or disable the session object passed as the first argument.
172757*/
172758SQLITE_API int SQLITE_STDCALL sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
172759  int ret;
172760  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172761  if( bIndirect>=0 ){
172762    pSession->bIndirect = bIndirect;
172763  }
172764  ret = pSession->bIndirect;
172765  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172766  return ret;
172767}
172768
172769/*
172770** Return true if there have been no changes to monitored tables recorded
172771** by the session object passed as the only argument.
172772*/
172773SQLITE_API int SQLITE_STDCALL sqlite3session_isempty(sqlite3_session *pSession){
172774  int ret = 0;
172775  SessionTable *pTab;
172776
172777  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172778  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
172779    ret = (pTab->nEntry>0);
172780  }
172781  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172782
172783  return (ret==0);
172784}
172785
172786/*
172787** Do the work for either sqlite3changeset_start() or start_strm().
172788*/
172789static int sessionChangesetStart(
172790  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172791  int (*xInput)(void *pIn, void *pData, int *pnData),
172792  void *pIn,
172793  int nChangeset,                 /* Size of buffer pChangeset in bytes */
172794  void *pChangeset                /* Pointer to buffer containing changeset */
172795){
172796  sqlite3_changeset_iter *pRet;   /* Iterator to return */
172797  int nByte;                      /* Number of bytes to allocate for iterator */
172798
172799  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
172800
172801  /* Zero the output variable in case an error occurs. */
172802  *pp = 0;
172803
172804  /* Allocate and initialize the iterator structure. */
172805  nByte = sizeof(sqlite3_changeset_iter);
172806  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
172807  if( !pRet ) return SQLITE_NOMEM;
172808  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
172809  pRet->in.aData = (u8 *)pChangeset;
172810  pRet->in.nData = nChangeset;
172811  pRet->in.xInput = xInput;
172812  pRet->in.pIn = pIn;
172813  pRet->in.bEof = (xInput ? 0 : 1);
172814
172815  /* Populate the output variable and return success. */
172816  *pp = pRet;
172817  return SQLITE_OK;
172818}
172819
172820/*
172821** Create an iterator used to iterate through the contents of a changeset.
172822*/
172823SQLITE_API int SQLITE_STDCALL sqlite3changeset_start(
172824  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172825  int nChangeset,                 /* Size of buffer pChangeset in bytes */
172826  void *pChangeset                /* Pointer to buffer containing changeset */
172827){
172828  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
172829}
172830
172831/*
172832** Streaming version of sqlite3changeset_start().
172833*/
172834SQLITE_API int SQLITE_STDCALL sqlite3changeset_start_strm(
172835  sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172836  int (*xInput)(void *pIn, void *pData, int *pnData),
172837  void *pIn
172838){
172839  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
172840}
172841
172842/*
172843** If the SessionInput object passed as the only argument is a streaming
172844** object and the buffer is full, discard some data to free up space.
172845*/
172846static void sessionDiscardData(SessionInput *pIn){
172847  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
172848    int nMove = pIn->buf.nBuf - pIn->iNext;
172849    assert( nMove>=0 );
172850    if( nMove>0 ){
172851      memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
172852    }
172853    pIn->buf.nBuf -= pIn->iNext;
172854    pIn->iNext = 0;
172855    pIn->nData = pIn->buf.nBuf;
172856  }
172857}
172858
172859/*
172860** Ensure that there are at least nByte bytes available in the buffer. Or,
172861** if there are not nByte bytes remaining in the input, that all available
172862** data is in the buffer.
172863**
172864** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
172865*/
172866static int sessionInputBuffer(SessionInput *pIn, int nByte){
172867  int rc = SQLITE_OK;
172868  if( pIn->xInput ){
172869    while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
172870      int nNew = SESSIONS_STRM_CHUNK_SIZE;
172871
172872      if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
172873      if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
172874        rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
172875        if( nNew==0 ){
172876          pIn->bEof = 1;
172877        }else{
172878          pIn->buf.nBuf += nNew;
172879        }
172880      }
172881
172882      pIn->aData = pIn->buf.aBuf;
172883      pIn->nData = pIn->buf.nBuf;
172884    }
172885  }
172886  return rc;
172887}
172888
172889/*
172890** When this function is called, *ppRec points to the start of a record
172891** that contains nCol values. This function advances the pointer *ppRec
172892** until it points to the byte immediately following that record.
172893*/
172894static void sessionSkipRecord(
172895  u8 **ppRec,                     /* IN/OUT: Record pointer */
172896  int nCol                        /* Number of values in record */
172897){
172898  u8 *aRec = *ppRec;
172899  int i;
172900  for(i=0; i<nCol; i++){
172901    int eType = *aRec++;
172902    if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172903      int nByte;
172904      aRec += sessionVarintGet((u8*)aRec, &nByte);
172905      aRec += nByte;
172906    }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172907      aRec += 8;
172908    }
172909  }
172910
172911  *ppRec = aRec;
172912}
172913
172914/*
172915** This function sets the value of the sqlite3_value object passed as the
172916** first argument to a copy of the string or blob held in the aData[]
172917** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
172918** error occurs.
172919*/
172920static int sessionValueSetStr(
172921  sqlite3_value *pVal,            /* Set the value of this object */
172922  u8 *aData,                      /* Buffer containing string or blob data */
172923  int nData,                      /* Size of buffer aData[] in bytes */
172924  u8 enc                          /* String encoding (0 for blobs) */
172925){
172926  /* In theory this code could just pass SQLITE_TRANSIENT as the final
172927  ** argument to sqlite3ValueSetStr() and have the copy created
172928  ** automatically. But doing so makes it difficult to detect any OOM
172929  ** error. Hence the code to create the copy externally. */
172930  u8 *aCopy = sqlite3_malloc(nData+1);
172931  if( aCopy==0 ) return SQLITE_NOMEM;
172932  memcpy(aCopy, aData, nData);
172933  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
172934  return SQLITE_OK;
172935}
172936
172937/*
172938** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
172939** for details.
172940**
172941** When this function is called, *paChange points to the start of the record
172942** to deserialize. Assuming no error occurs, *paChange is set to point to
172943** one byte after the end of the same record before this function returns.
172944** If the argument abPK is NULL, then the record contains nCol values. Or,
172945** if abPK is other than NULL, then the record contains only the PK fields
172946** (in other words, it is a patchset DELETE record).
172947**
172948** If successful, each element of the apOut[] array (allocated by the caller)
172949** is set to point to an sqlite3_value object containing the value read
172950** from the corresponding position in the record. If that value is not
172951** included in the record (i.e. because the record is part of an UPDATE change
172952** and the field was not modified), the corresponding element of apOut[] is
172953** set to NULL.
172954**
172955** It is the responsibility of the caller to free all sqlite_value structures
172956** using sqlite3_free().
172957**
172958** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
172959** The apOut[] array may have been partially populated in this case.
172960*/
172961static int sessionReadRecord(
172962  SessionInput *pIn,              /* Input data */
172963  int nCol,                       /* Number of values in record */
172964  u8 *abPK,                       /* Array of primary key flags, or NULL */
172965  sqlite3_value **apOut           /* Write values to this array */
172966){
172967  int i;                          /* Used to iterate through columns */
172968  int rc = SQLITE_OK;
172969
172970  for(i=0; i<nCol && rc==SQLITE_OK; i++){
172971    int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
172972    if( abPK && abPK[i]==0 ) continue;
172973    rc = sessionInputBuffer(pIn, 9);
172974    if( rc==SQLITE_OK ){
172975      eType = pIn->aData[pIn->iNext++];
172976    }
172977
172978    assert( apOut[i]==0 );
172979    if( eType ){
172980      apOut[i] = sqlite3ValueNew(0);
172981      if( !apOut[i] ) rc = SQLITE_NOMEM;
172982    }
172983
172984    if( rc==SQLITE_OK ){
172985      u8 *aVal = &pIn->aData[pIn->iNext];
172986      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172987        int nByte;
172988        pIn->iNext += sessionVarintGet(aVal, &nByte);
172989        rc = sessionInputBuffer(pIn, nByte);
172990        if( rc==SQLITE_OK ){
172991          u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
172992          rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
172993        }
172994        pIn->iNext += nByte;
172995      }
172996      if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172997        sqlite3_int64 v = sessionGetI64(aVal);
172998        if( eType==SQLITE_INTEGER ){
172999          sqlite3VdbeMemSetInt64(apOut[i], v);
173000        }else{
173001          double d;
173002          memcpy(&d, &v, 8);
173003          sqlite3VdbeMemSetDouble(apOut[i], d);
173004        }
173005        pIn->iNext += 8;
173006      }
173007    }
173008  }
173009
173010  return rc;
173011}
173012
173013/*
173014** The input pointer currently points to the second byte of a table-header.
173015** Specifically, to the following:
173016**
173017**   + number of columns in table (varint)
173018**   + array of PK flags (1 byte per column),
173019**   + table name (nul terminated).
173020**
173021** This function ensures that all of the above is present in the input
173022** buffer (i.e. that it can be accessed without any calls to xInput()).
173023** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
173024** The input pointer is not moved.
173025*/
173026static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
173027  int rc = SQLITE_OK;
173028  int nCol = 0;
173029  int nRead = 0;
173030
173031  rc = sessionInputBuffer(pIn, 9);
173032  if( rc==SQLITE_OK ){
173033    nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
173034    rc = sessionInputBuffer(pIn, nRead+nCol+100);
173035    nRead += nCol;
173036  }
173037
173038  while( rc==SQLITE_OK ){
173039    while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
173040      nRead++;
173041    }
173042    if( (pIn->iNext + nRead)<pIn->nData ) break;
173043    rc = sessionInputBuffer(pIn, nRead + 100);
173044  }
173045  *pnByte = nRead+1;
173046  return rc;
173047}
173048
173049/*
173050** The input pointer currently points to the first byte of the first field
173051** of a record consisting of nCol columns. This function ensures the entire
173052** record is buffered. It does not move the input pointer.
173053**
173054** If successful, SQLITE_OK is returned and *pnByte is set to the size of
173055** the record in bytes. Otherwise, an SQLite error code is returned. The
173056** final value of *pnByte is undefined in this case.
173057*/
173058static int sessionChangesetBufferRecord(
173059  SessionInput *pIn,              /* Input data */
173060  int nCol,                       /* Number of columns in record */
173061  int *pnByte                     /* OUT: Size of record in bytes */
173062){
173063  int rc = SQLITE_OK;
173064  int nByte = 0;
173065  int i;
173066  for(i=0; rc==SQLITE_OK && i<nCol; i++){
173067    int eType;
173068    rc = sessionInputBuffer(pIn, nByte + 10);
173069    if( rc==SQLITE_OK ){
173070      eType = pIn->aData[pIn->iNext + nByte++];
173071      if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
173072        int n;
173073        nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
173074        nByte += n;
173075        rc = sessionInputBuffer(pIn, nByte);
173076      }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
173077        nByte += 8;
173078      }
173079    }
173080  }
173081  *pnByte = nByte;
173082  return rc;
173083}
173084
173085/*
173086** The input pointer currently points to the second byte of a table-header.
173087** Specifically, to the following:
173088**
173089**   + number of columns in table (varint)
173090**   + array of PK flags (1 byte per column),
173091**   + table name (nul terminated).
173092**
173093** This function decodes the table-header and populates the p->nCol,
173094** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
173095** also allocated or resized according to the new value of p->nCol. The
173096** input pointer is left pointing to the byte following the table header.
173097**
173098** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
173099** is returned and the final values of the various fields enumerated above
173100** are undefined.
173101*/
173102static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
173103  int rc;
173104  int nCopy;
173105  assert( p->rc==SQLITE_OK );
173106
173107  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
173108  if( rc==SQLITE_OK ){
173109    int nByte;
173110    int nVarint;
173111    nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
173112    nCopy -= nVarint;
173113    p->in.iNext += nVarint;
173114    nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
173115    p->tblhdr.nBuf = 0;
173116    sessionBufferGrow(&p->tblhdr, nByte, &rc);
173117  }
173118
173119  if( rc==SQLITE_OK ){
173120    int iPK = sizeof(sqlite3_value*)*p->nCol*2;
173121    memset(p->tblhdr.aBuf, 0, iPK);
173122    memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
173123    p->in.iNext += nCopy;
173124  }
173125
173126  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
173127  p->abPK = (u8*)&p->apValue[p->nCol*2];
173128  p->zTab = (char*)&p->abPK[p->nCol];
173129  return (p->rc = rc);
173130}
173131
173132/*
173133** Advance the changeset iterator to the next change.
173134**
173135** If both paRec and pnRec are NULL, then this function works like the public
173136** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
173137** sqlite3changeset_new() and old() APIs may be used to query for values.
173138**
173139** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
173140** record is written to *paRec before returning and the number of bytes in
173141** the record to *pnRec.
173142**
173143** Either way, this function returns SQLITE_ROW if the iterator is
173144** successfully advanced to the next change in the changeset, an SQLite
173145** error code if an error occurs, or SQLITE_DONE if there are no further
173146** changes in the changeset.
173147*/
173148static int sessionChangesetNext(
173149  sqlite3_changeset_iter *p,      /* Changeset iterator */
173150  u8 **paRec,                     /* If non-NULL, store record pointer here */
173151  int *pnRec                      /* If non-NULL, store size of record here */
173152){
173153  int i;
173154  u8 op;
173155
173156  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
173157
173158  /* If the iterator is in the error-state, return immediately. */
173159  if( p->rc!=SQLITE_OK ) return p->rc;
173160
173161  /* Free the current contents of p->apValue[], if any. */
173162  if( p->apValue ){
173163    for(i=0; i<p->nCol*2; i++){
173164      sqlite3ValueFree(p->apValue[i]);
173165    }
173166    memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
173167  }
173168
173169  /* Make sure the buffer contains at least 10 bytes of input data, or all
173170  ** remaining data if there are less than 10 bytes available. This is
173171  ** sufficient either for the 'T' or 'P' byte and the varint that follows
173172  ** it, or for the two single byte values otherwise. */
173173  p->rc = sessionInputBuffer(&p->in, 2);
173174  if( p->rc!=SQLITE_OK ) return p->rc;
173175
173176  /* If the iterator is already at the end of the changeset, return DONE. */
173177  if( p->in.iNext>=p->in.nData ){
173178    return SQLITE_DONE;
173179  }
173180
173181  sessionDiscardData(&p->in);
173182  p->in.iCurrent = p->in.iNext;
173183
173184  op = p->in.aData[p->in.iNext++];
173185  if( op=='T' || op=='P' ){
173186    p->bPatchset = (op=='P');
173187    if( sessionChangesetReadTblhdr(p) ) return p->rc;
173188    if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
173189    p->in.iCurrent = p->in.iNext;
173190    op = p->in.aData[p->in.iNext++];
173191  }
173192
173193  p->op = op;
173194  p->bIndirect = p->in.aData[p->in.iNext++];
173195  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
173196    return (p->rc = SQLITE_CORRUPT_BKPT);
173197  }
173198
173199  if( paRec ){
173200    int nVal;                     /* Number of values to buffer */
173201    if( p->bPatchset==0 && op==SQLITE_UPDATE ){
173202      nVal = p->nCol * 2;
173203    }else if( p->bPatchset && op==SQLITE_DELETE ){
173204      nVal = 0;
173205      for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
173206    }else{
173207      nVal = p->nCol;
173208    }
173209    p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
173210    if( p->rc!=SQLITE_OK ) return p->rc;
173211    *paRec = &p->in.aData[p->in.iNext];
173212    p->in.iNext += *pnRec;
173213  }else{
173214
173215    /* If this is an UPDATE or DELETE, read the old.* record. */
173216    if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
173217      u8 *abPK = p->bPatchset ? p->abPK : 0;
173218      p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
173219      if( p->rc!=SQLITE_OK ) return p->rc;
173220    }
173221
173222    /* If this is an INSERT or UPDATE, read the new.* record. */
173223    if( p->op!=SQLITE_DELETE ){
173224      p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
173225      if( p->rc!=SQLITE_OK ) return p->rc;
173226    }
173227
173228    if( p->bPatchset && p->op==SQLITE_UPDATE ){
173229      /* If this is an UPDATE that is part of a patchset, then all PK and
173230      ** modified fields are present in the new.* record. The old.* record
173231      ** is currently completely empty. This block shifts the PK fields from
173232      ** new.* to old.*, to accommodate the code that reads these arrays.  */
173233      for(i=0; i<p->nCol; i++){
173234        assert( p->apValue[i]==0 );
173235        assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
173236        if( p->abPK[i] ){
173237          p->apValue[i] = p->apValue[i+p->nCol];
173238          p->apValue[i+p->nCol] = 0;
173239        }
173240      }
173241    }
173242  }
173243
173244  return SQLITE_ROW;
173245}
173246
173247/*
173248** Advance an iterator created by sqlite3changeset_start() to the next
173249** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
173250** or SQLITE_CORRUPT.
173251**
173252** This function may not be called on iterators passed to a conflict handler
173253** callback by changeset_apply().
173254*/
173255SQLITE_API int SQLITE_STDCALL sqlite3changeset_next(sqlite3_changeset_iter *p){
173256  return sessionChangesetNext(p, 0, 0);
173257}
173258
173259/*
173260** The following function extracts information on the current change
173261** from a changeset iterator. It may only be called after changeset_next()
173262** has returned SQLITE_ROW.
173263*/
173264SQLITE_API int SQLITE_STDCALL sqlite3changeset_op(
173265  sqlite3_changeset_iter *pIter,  /* Iterator handle */
173266  const char **pzTab,             /* OUT: Pointer to table name */
173267  int *pnCol,                     /* OUT: Number of columns in table */
173268  int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
173269  int *pbIndirect                 /* OUT: True if change is indirect */
173270){
173271  *pOp = pIter->op;
173272  *pnCol = pIter->nCol;
173273  *pzTab = pIter->zTab;
173274  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
173275  return SQLITE_OK;
173276}
173277
173278/*
173279** Return information regarding the PRIMARY KEY and number of columns in
173280** the database table affected by the change that pIter currently points
173281** to. This function may only be called after changeset_next() returns
173282** SQLITE_ROW.
173283*/
173284SQLITE_API int SQLITE_STDCALL sqlite3changeset_pk(
173285  sqlite3_changeset_iter *pIter,  /* Iterator object */
173286  unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
173287  int *pnCol                      /* OUT: Number of entries in output array */
173288){
173289  *pabPK = pIter->abPK;
173290  if( pnCol ) *pnCol = pIter->nCol;
173291  return SQLITE_OK;
173292}
173293
173294/*
173295** This function may only be called while the iterator is pointing to an
173296** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
173297** Otherwise, SQLITE_MISUSE is returned.
173298**
173299** It sets *ppValue to point to an sqlite3_value structure containing the
173300** iVal'th value in the old.* record. Or, if that particular value is not
173301** included in the record (because the change is an UPDATE and the field
173302** was not modified and is not a PK column), set *ppValue to NULL.
173303**
173304** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
173305** not modified. Otherwise, SQLITE_OK.
173306*/
173307SQLITE_API int SQLITE_STDCALL sqlite3changeset_old(
173308  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173309  int iVal,                       /* Index of old.* value to retrieve */
173310  sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
173311){
173312  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
173313    return SQLITE_MISUSE;
173314  }
173315  if( iVal<0 || iVal>=pIter->nCol ){
173316    return SQLITE_RANGE;
173317  }
173318  *ppValue = pIter->apValue[iVal];
173319  return SQLITE_OK;
173320}
173321
173322/*
173323** This function may only be called while the iterator is pointing to an
173324** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
173325** Otherwise, SQLITE_MISUSE is returned.
173326**
173327** It sets *ppValue to point to an sqlite3_value structure containing the
173328** iVal'th value in the new.* record. Or, if that particular value is not
173329** included in the record (because the change is an UPDATE and the field
173330** was not modified), set *ppValue to NULL.
173331**
173332** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
173333** not modified. Otherwise, SQLITE_OK.
173334*/
173335SQLITE_API int SQLITE_STDCALL sqlite3changeset_new(
173336  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173337  int iVal,                       /* Index of new.* value to retrieve */
173338  sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
173339){
173340  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
173341    return SQLITE_MISUSE;
173342  }
173343  if( iVal<0 || iVal>=pIter->nCol ){
173344    return SQLITE_RANGE;
173345  }
173346  *ppValue = pIter->apValue[pIter->nCol+iVal];
173347  return SQLITE_OK;
173348}
173349
173350/*
173351** The following two macros are used internally. They are similar to the
173352** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
173353** they omit all error checking and return a pointer to the requested value.
173354*/
173355#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
173356#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
173357
173358/*
173359** This function may only be called with a changeset iterator that has been
173360** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
173361** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
173362**
173363** If successful, *ppValue is set to point to an sqlite3_value structure
173364** containing the iVal'th value of the conflicting record.
173365**
173366** If value iVal is out-of-range or some other error occurs, an SQLite error
173367** code is returned. Otherwise, SQLITE_OK.
173368*/
173369SQLITE_API int SQLITE_STDCALL sqlite3changeset_conflict(
173370  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173371  int iVal,                       /* Index of conflict record value to fetch */
173372  sqlite3_value **ppValue         /* OUT: Value from conflicting row */
173373){
173374  if( !pIter->pConflict ){
173375    return SQLITE_MISUSE;
173376  }
173377  if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
173378    return SQLITE_RANGE;
173379  }
173380  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
173381  return SQLITE_OK;
173382}
173383
173384/*
173385** This function may only be called with an iterator passed to an
173386** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
173387** it sets the output variable to the total number of known foreign key
173388** violations in the destination database and returns SQLITE_OK.
173389**
173390** In all other cases this function returns SQLITE_MISUSE.
173391*/
173392SQLITE_API int SQLITE_STDCALL sqlite3changeset_fk_conflicts(
173393  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173394  int *pnOut                      /* OUT: Number of FK violations */
173395){
173396  if( pIter->pConflict || pIter->apValue ){
173397    return SQLITE_MISUSE;
173398  }
173399  *pnOut = pIter->nCol;
173400  return SQLITE_OK;
173401}
173402
173403
173404/*
173405** Finalize an iterator allocated with sqlite3changeset_start().
173406**
173407** This function may not be called on iterators passed to a conflict handler
173408** callback by changeset_apply().
173409*/
173410SQLITE_API int SQLITE_STDCALL sqlite3changeset_finalize(sqlite3_changeset_iter *p){
173411  int rc = SQLITE_OK;
173412  if( p ){
173413    int i;                        /* Used to iterate through p->apValue[] */
173414    rc = p->rc;
173415    if( p->apValue ){
173416      for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
173417    }
173418    sqlite3_free(p->tblhdr.aBuf);
173419    sqlite3_free(p->in.buf.aBuf);
173420    sqlite3_free(p);
173421  }
173422  return rc;
173423}
173424
173425static int sessionChangesetInvert(
173426  SessionInput *pInput,           /* Input changeset */
173427  int (*xOutput)(void *pOut, const void *pData, int nData),
173428  void *pOut,
173429  int *pnInverted,                /* OUT: Number of bytes in output changeset */
173430  void **ppInverted               /* OUT: Inverse of pChangeset */
173431){
173432  int rc = SQLITE_OK;             /* Return value */
173433  SessionBuffer sOut;             /* Output buffer */
173434  int nCol = 0;                   /* Number of cols in current table */
173435  u8 *abPK = 0;                   /* PK array for current table */
173436  sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
173437  SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
173438
173439  /* Initialize the output buffer */
173440  memset(&sOut, 0, sizeof(SessionBuffer));
173441
173442  /* Zero the output variables in case an error occurs. */
173443  if( ppInverted ){
173444    *ppInverted = 0;
173445    *pnInverted = 0;
173446  }
173447
173448  while( 1 ){
173449    u8 eType;
173450
173451    /* Test for EOF. */
173452    if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
173453    if( pInput->iNext>=pInput->nData ) break;
173454    eType = pInput->aData[pInput->iNext];
173455
173456    switch( eType ){
173457      case 'T': {
173458        /* A 'table' record consists of:
173459        **
173460        **   * A constant 'T' character,
173461        **   * Number of columns in said table (a varint),
173462        **   * An array of nCol bytes (sPK),
173463        **   * A nul-terminated table name.
173464        */
173465        int nByte;
173466        int nVar;
173467        pInput->iNext++;
173468        if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
173469          goto finished_invert;
173470        }
173471        nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
173472        sPK.nBuf = 0;
173473        sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
173474        sessionAppendByte(&sOut, eType, &rc);
173475        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
173476        if( rc ) goto finished_invert;
173477
173478        pInput->iNext += nByte;
173479        sqlite3_free(apVal);
173480        apVal = 0;
173481        abPK = sPK.aBuf;
173482        break;
173483      }
173484
173485      case SQLITE_INSERT:
173486      case SQLITE_DELETE: {
173487        int nByte;
173488        int bIndirect = pInput->aData[pInput->iNext+1];
173489        int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
173490        pInput->iNext += 2;
173491        assert( rc==SQLITE_OK );
173492        rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
173493        sessionAppendByte(&sOut, eType2, &rc);
173494        sessionAppendByte(&sOut, bIndirect, &rc);
173495        sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
173496        pInput->iNext += nByte;
173497        if( rc ) goto finished_invert;
173498        break;
173499      }
173500
173501      case SQLITE_UPDATE: {
173502        int iCol;
173503
173504        if( 0==apVal ){
173505          apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
173506          if( 0==apVal ){
173507            rc = SQLITE_NOMEM;
173508            goto finished_invert;
173509          }
173510          memset(apVal, 0, sizeof(apVal[0])*nCol*2);
173511        }
173512
173513        /* Write the header for the new UPDATE change. Same as the original. */
173514        sessionAppendByte(&sOut, eType, &rc);
173515        sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
173516
173517        /* Read the old.* and new.* records for the update change. */
173518        pInput->iNext += 2;
173519        rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
173520        if( rc==SQLITE_OK ){
173521          rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
173522        }
173523
173524        /* Write the new old.* record. Consists of the PK columns from the
173525        ** original old.* record, and the other values from the original
173526        ** new.* record. */
173527        for(iCol=0; iCol<nCol; iCol++){
173528          sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
173529          sessionAppendValue(&sOut, pVal, &rc);
173530        }
173531
173532        /* Write the new new.* record. Consists of a copy of all values
173533        ** from the original old.* record, except for the PK columns, which
173534        ** are set to "undefined". */
173535        for(iCol=0; iCol<nCol; iCol++){
173536          sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
173537          sessionAppendValue(&sOut, pVal, &rc);
173538        }
173539
173540        for(iCol=0; iCol<nCol*2; iCol++){
173541          sqlite3ValueFree(apVal[iCol]);
173542        }
173543        memset(apVal, 0, sizeof(apVal[0])*nCol*2);
173544        if( rc!=SQLITE_OK ){
173545          goto finished_invert;
173546        }
173547
173548        break;
173549      }
173550
173551      default:
173552        rc = SQLITE_CORRUPT_BKPT;
173553        goto finished_invert;
173554    }
173555
173556    assert( rc==SQLITE_OK );
173557    if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
173558      rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
173559      sOut.nBuf = 0;
173560      if( rc!=SQLITE_OK ) goto finished_invert;
173561    }
173562  }
173563
173564  assert( rc==SQLITE_OK );
173565  if( pnInverted ){
173566    *pnInverted = sOut.nBuf;
173567    *ppInverted = sOut.aBuf;
173568    sOut.aBuf = 0;
173569  }else if( sOut.nBuf>0 ){
173570    rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
173571  }
173572
173573 finished_invert:
173574  sqlite3_free(sOut.aBuf);
173575  sqlite3_free(apVal);
173576  sqlite3_free(sPK.aBuf);
173577  return rc;
173578}
173579
173580
173581/*
173582** Invert a changeset object.
173583*/
173584SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert(
173585  int nChangeset,                 /* Number of bytes in input */
173586  const void *pChangeset,         /* Input changeset */
173587  int *pnInverted,                /* OUT: Number of bytes in output changeset */
173588  void **ppInverted               /* OUT: Inverse of pChangeset */
173589){
173590  SessionInput sInput;
173591
173592  /* Set up the input stream */
173593  memset(&sInput, 0, sizeof(SessionInput));
173594  sInput.nData = nChangeset;
173595  sInput.aData = (u8*)pChangeset;
173596
173597  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
173598}
173599
173600/*
173601** Streaming version of sqlite3changeset_invert().
173602*/
173603SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert_strm(
173604  int (*xInput)(void *pIn, void *pData, int *pnData),
173605  void *pIn,
173606  int (*xOutput)(void *pOut, const void *pData, int nData),
173607  void *pOut
173608){
173609  SessionInput sInput;
173610  int rc;
173611
173612  /* Set up the input stream */
173613  memset(&sInput, 0, sizeof(SessionInput));
173614  sInput.xInput = xInput;
173615  sInput.pIn = pIn;
173616
173617  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
173618  sqlite3_free(sInput.buf.aBuf);
173619  return rc;
173620}
173621
173622typedef struct SessionApplyCtx SessionApplyCtx;
173623struct SessionApplyCtx {
173624  sqlite3 *db;
173625  sqlite3_stmt *pDelete;          /* DELETE statement */
173626  sqlite3_stmt *pUpdate;          /* UPDATE statement */
173627  sqlite3_stmt *pInsert;          /* INSERT statement */
173628  sqlite3_stmt *pSelect;          /* SELECT statement */
173629  int nCol;                       /* Size of azCol[] and abPK[] arrays */
173630  const char **azCol;             /* Array of column names */
173631  u8 *abPK;                       /* Boolean array - true if column is in PK */
173632
173633  int bDeferConstraints;          /* True to defer constraints */
173634  SessionBuffer constraints;      /* Deferred constraints are stored here */
173635};
173636
173637/*
173638** Formulate a statement to DELETE a row from database db. Assuming a table
173639** structure like this:
173640**
173641**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173642**
173643** The DELETE statement looks like this:
173644**
173645**     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
173646**
173647** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
173648** matching b and d values, or 1 otherwise. The second case comes up if the
173649** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
173650**
173651** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
173652** pointing to the prepared version of the SQL statement.
173653*/
173654static int sessionDeleteRow(
173655  sqlite3 *db,                    /* Database handle */
173656  const char *zTab,               /* Table name */
173657  SessionApplyCtx *p              /* Session changeset-apply context */
173658){
173659  int i;
173660  const char *zSep = "";
173661  int rc = SQLITE_OK;
173662  SessionBuffer buf = {0, 0, 0};
173663  int nPk = 0;
173664
173665  sessionAppendStr(&buf, "DELETE FROM ", &rc);
173666  sessionAppendIdent(&buf, zTab, &rc);
173667  sessionAppendStr(&buf, " WHERE ", &rc);
173668
173669  for(i=0; i<p->nCol; i++){
173670    if( p->abPK[i] ){
173671      nPk++;
173672      sessionAppendStr(&buf, zSep, &rc);
173673      sessionAppendIdent(&buf, p->azCol[i], &rc);
173674      sessionAppendStr(&buf, " = ?", &rc);
173675      sessionAppendInteger(&buf, i+1, &rc);
173676      zSep = " AND ";
173677    }
173678  }
173679
173680  if( nPk<p->nCol ){
173681    sessionAppendStr(&buf, " AND (?", &rc);
173682    sessionAppendInteger(&buf, p->nCol+1, &rc);
173683    sessionAppendStr(&buf, " OR ", &rc);
173684
173685    zSep = "";
173686    for(i=0; i<p->nCol; i++){
173687      if( !p->abPK[i] ){
173688        sessionAppendStr(&buf, zSep, &rc);
173689        sessionAppendIdent(&buf, p->azCol[i], &rc);
173690        sessionAppendStr(&buf, " IS ?", &rc);
173691        sessionAppendInteger(&buf, i+1, &rc);
173692        zSep = "AND ";
173693      }
173694    }
173695    sessionAppendStr(&buf, ")", &rc);
173696  }
173697
173698  if( rc==SQLITE_OK ){
173699    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
173700  }
173701  sqlite3_free(buf.aBuf);
173702
173703  return rc;
173704}
173705
173706/*
173707** Formulate and prepare a statement to UPDATE a row from database db.
173708** Assuming a table structure like this:
173709**
173710**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173711**
173712** The UPDATE statement looks like this:
173713**
173714**     UPDATE x SET
173715**     a = CASE WHEN ?2  THEN ?3  ELSE a END,
173716**     b = CASE WHEN ?5  THEN ?6  ELSE b END,
173717**     c = CASE WHEN ?8  THEN ?9  ELSE c END,
173718**     d = CASE WHEN ?11 THEN ?12 ELSE d END
173719**     WHERE a = ?1 AND c = ?7 AND (?13 OR
173720**       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
173721**     )
173722**
173723** For each column in the table, there are three variables to bind:
173724**
173725**     ?(i*3+1)    The old.* value of the column, if any.
173726**     ?(i*3+2)    A boolean flag indicating that the value is being modified.
173727**     ?(i*3+3)    The new.* value of the column, if any.
173728**
173729** Also, a boolean flag that, if set to true, causes the statement to update
173730** a row even if the non-PK values do not match. This is required if the
173731** conflict-handler is invoked with CHANGESET_DATA and returns
173732** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
173733**
173734** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
173735** pointing to the prepared version of the SQL statement.
173736*/
173737static int sessionUpdateRow(
173738  sqlite3 *db,                    /* Database handle */
173739  const char *zTab,               /* Table name */
173740  SessionApplyCtx *p              /* Session changeset-apply context */
173741){
173742  int rc = SQLITE_OK;
173743  int i;
173744  const char *zSep = "";
173745  SessionBuffer buf = {0, 0, 0};
173746
173747  /* Append "UPDATE tbl SET " */
173748  sessionAppendStr(&buf, "UPDATE ", &rc);
173749  sessionAppendIdent(&buf, zTab, &rc);
173750  sessionAppendStr(&buf, " SET ", &rc);
173751
173752  /* Append the assignments */
173753  for(i=0; i<p->nCol; i++){
173754    sessionAppendStr(&buf, zSep, &rc);
173755    sessionAppendIdent(&buf, p->azCol[i], &rc);
173756    sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
173757    sessionAppendInteger(&buf, i*3+2, &rc);
173758    sessionAppendStr(&buf, " THEN ?", &rc);
173759    sessionAppendInteger(&buf, i*3+3, &rc);
173760    sessionAppendStr(&buf, " ELSE ", &rc);
173761    sessionAppendIdent(&buf, p->azCol[i], &rc);
173762    sessionAppendStr(&buf, " END", &rc);
173763    zSep = ", ";
173764  }
173765
173766  /* Append the PK part of the WHERE clause */
173767  sessionAppendStr(&buf, " WHERE ", &rc);
173768  for(i=0; i<p->nCol; i++){
173769    if( p->abPK[i] ){
173770      sessionAppendIdent(&buf, p->azCol[i], &rc);
173771      sessionAppendStr(&buf, " = ?", &rc);
173772      sessionAppendInteger(&buf, i*3+1, &rc);
173773      sessionAppendStr(&buf, " AND ", &rc);
173774    }
173775  }
173776
173777  /* Append the non-PK part of the WHERE clause */
173778  sessionAppendStr(&buf, " (?", &rc);
173779  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
173780  sessionAppendStr(&buf, " OR 1", &rc);
173781  for(i=0; i<p->nCol; i++){
173782    if( !p->abPK[i] ){
173783      sessionAppendStr(&buf, " AND (?", &rc);
173784      sessionAppendInteger(&buf, i*3+2, &rc);
173785      sessionAppendStr(&buf, "=0 OR ", &rc);
173786      sessionAppendIdent(&buf, p->azCol[i], &rc);
173787      sessionAppendStr(&buf, " IS ?", &rc);
173788      sessionAppendInteger(&buf, i*3+1, &rc);
173789      sessionAppendStr(&buf, ")", &rc);
173790    }
173791  }
173792  sessionAppendStr(&buf, ")", &rc);
173793
173794  if( rc==SQLITE_OK ){
173795    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
173796  }
173797  sqlite3_free(buf.aBuf);
173798
173799  return rc;
173800}
173801
173802/*
173803** Formulate and prepare an SQL statement to query table zTab by primary
173804** key. Assuming the following table structure:
173805**
173806**     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173807**
173808** The SELECT statement looks like this:
173809**
173810**     SELECT * FROM x WHERE a = ?1 AND c = ?3
173811**
173812** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
173813** pointing to the prepared version of the SQL statement.
173814*/
173815static int sessionSelectRow(
173816  sqlite3 *db,                    /* Database handle */
173817  const char *zTab,               /* Table name */
173818  SessionApplyCtx *p              /* Session changeset-apply context */
173819){
173820  return sessionSelectStmt(
173821      db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
173822}
173823
173824/*
173825** Formulate and prepare an INSERT statement to add a record to table zTab.
173826** For example:
173827**
173828**     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
173829**
173830** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
173831** pointing to the prepared version of the SQL statement.
173832*/
173833static int sessionInsertRow(
173834  sqlite3 *db,                    /* Database handle */
173835  const char *zTab,               /* Table name */
173836  SessionApplyCtx *p              /* Session changeset-apply context */
173837){
173838  int rc = SQLITE_OK;
173839  int i;
173840  SessionBuffer buf = {0, 0, 0};
173841
173842  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
173843  sessionAppendIdent(&buf, zTab, &rc);
173844  sessionAppendStr(&buf, " VALUES(?", &rc);
173845  for(i=1; i<p->nCol; i++){
173846    sessionAppendStr(&buf, ", ?", &rc);
173847  }
173848  sessionAppendStr(&buf, ")", &rc);
173849
173850  if( rc==SQLITE_OK ){
173851    rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
173852  }
173853  sqlite3_free(buf.aBuf);
173854  return rc;
173855}
173856
173857/*
173858** A wrapper around sqlite3_bind_value() that detects an extra problem.
173859** See comments in the body of this function for details.
173860*/
173861static int sessionBindValue(
173862  sqlite3_stmt *pStmt,            /* Statement to bind value to */
173863  int i,                          /* Parameter number to bind to */
173864  sqlite3_value *pVal             /* Value to bind */
173865){
173866  int eType = sqlite3_value_type(pVal);
173867  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
173868  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
173869  ** the (pVal->z) variable remains as it was or the type of the value is
173870  ** set to SQLITE_NULL.  */
173871  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
173872    /* This condition occurs when an earlier OOM in a call to
173873    ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
173874    ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
173875    return SQLITE_NOMEM;
173876  }
173877  return sqlite3_bind_value(pStmt, i, pVal);
173878}
173879
173880/*
173881** Iterator pIter must point to an SQLITE_INSERT entry. This function
173882** transfers new.* values from the current iterator entry to statement
173883** pStmt. The table being inserted into has nCol columns.
173884**
173885** New.* value $i from the iterator is bound to variable ($i+1) of
173886** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
173887** are transfered to the statement. Otherwise, if abPK is not NULL, it points
173888** to an array nCol elements in size. In this case only those values for
173889** which abPK[$i] is true are read from the iterator and bound to the
173890** statement.
173891**
173892** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
173893*/
173894static int sessionBindRow(
173895  sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
173896  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
173897  int nCol,                       /* Number of columns */
173898  u8 *abPK,                       /* If not NULL, bind only if true */
173899  sqlite3_stmt *pStmt             /* Bind values to this statement */
173900){
173901  int i;
173902  int rc = SQLITE_OK;
173903
173904  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
173905  ** argument iterator points to a suitable entry. Make sure that xValue
173906  ** is one of these to guarantee that it is safe to ignore the return
173907  ** in the code below. */
173908  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
173909
173910  for(i=0; rc==SQLITE_OK && i<nCol; i++){
173911    if( !abPK || abPK[i] ){
173912      sqlite3_value *pVal;
173913      (void)xValue(pIter, i, &pVal);
173914      rc = sessionBindValue(pStmt, i+1, pVal);
173915    }
173916  }
173917  return rc;
173918}
173919
173920/*
173921** SQL statement pSelect is as generated by the sessionSelectRow() function.
173922** This function binds the primary key values from the change that changeset
173923** iterator pIter points to to the SELECT and attempts to seek to the table
173924** entry. If a row is found, the SELECT statement left pointing at the row
173925** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
173926** has occured, the statement is reset and SQLITE_OK is returned. If an
173927** error occurs, the statement is reset and an SQLite error code is returned.
173928**
173929** If this function returns SQLITE_ROW, the caller must eventually reset()
173930** statement pSelect. If any other value is returned, the statement does
173931** not require a reset().
173932**
173933** If the iterator currently points to an INSERT record, bind values from the
173934** new.* record to the SELECT statement. Or, if it points to a DELETE or
173935** UPDATE, bind values from the old.* record.
173936*/
173937static int sessionSeekToRow(
173938  sqlite3 *db,                    /* Database handle */
173939  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173940  u8 *abPK,                       /* Primary key flags array */
173941  sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
173942){
173943  int rc;                         /* Return code */
173944  int nCol;                       /* Number of columns in table */
173945  int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
173946  const char *zDummy;             /* Unused */
173947
173948  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173949  rc = sessionBindRow(pIter,
173950      op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
173951      nCol, abPK, pSelect
173952  );
173953
173954  if( rc==SQLITE_OK ){
173955    rc = sqlite3_step(pSelect);
173956    if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
173957  }
173958
173959  return rc;
173960}
173961
173962/*
173963** Invoke the conflict handler for the change that the changeset iterator
173964** currently points to.
173965**
173966** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
173967** If argument pbReplace is NULL, then the type of conflict handler invoked
173968** depends solely on eType, as follows:
173969**
173970**    eType value                 Value passed to xConflict
173971**    -------------------------------------------------
173972**    CHANGESET_DATA              CHANGESET_NOTFOUND
173973**    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
173974**
173975** Or, if pbReplace is not NULL, then an attempt is made to find an existing
173976** record with the same primary key as the record about to be deleted, updated
173977** or inserted. If such a record can be found, it is available to the conflict
173978** handler as the "conflicting" record. In this case the type of conflict
173979** handler invoked is as follows:
173980**
173981**    eType value         PK Record found?   Value passed to xConflict
173982**    ----------------------------------------------------------------
173983**    CHANGESET_DATA      Yes                CHANGESET_DATA
173984**    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
173985**    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
173986**    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
173987**
173988** If pbReplace is not NULL, and a record with a matching PK is found, and
173989** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
173990** is set to non-zero before returning SQLITE_OK.
173991**
173992** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
173993** returned. Or, if the conflict handler returns an invalid value,
173994** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
173995** this function returns SQLITE_OK.
173996*/
173997static int sessionConflictHandler(
173998  int eType,                      /* Either CHANGESET_DATA or CONFLICT */
173999  SessionApplyCtx *p,             /* changeset_apply() context */
174000  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
174001  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
174002  void *pCtx,                     /* First argument for conflict handler */
174003  int *pbReplace                  /* OUT: Set to true if PK row is found */
174004){
174005  int res = 0;                    /* Value returned by conflict handler */
174006  int rc;
174007  int nCol;
174008  int op;
174009  const char *zDummy;
174010
174011  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
174012
174013  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
174014  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
174015  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
174016
174017  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
174018  if( pbReplace ){
174019    rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
174020  }else{
174021    rc = SQLITE_OK;
174022  }
174023
174024  if( rc==SQLITE_ROW ){
174025    /* There exists another row with the new.* primary key. */
174026    pIter->pConflict = p->pSelect;
174027    res = xConflict(pCtx, eType, pIter);
174028    pIter->pConflict = 0;
174029    rc = sqlite3_reset(p->pSelect);
174030  }else if( rc==SQLITE_OK ){
174031    if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
174032      /* Instead of invoking the conflict handler, append the change blob
174033      ** to the SessionApplyCtx.constraints buffer. */
174034      u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
174035      int nBlob = pIter->in.iNext - pIter->in.iCurrent;
174036      sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
174037      res = SQLITE_CHANGESET_OMIT;
174038    }else{
174039      /* No other row with the new.* primary key. */
174040      res = xConflict(pCtx, eType+1, pIter);
174041      if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
174042    }
174043  }
174044
174045  if( rc==SQLITE_OK ){
174046    switch( res ){
174047      case SQLITE_CHANGESET_REPLACE:
174048        assert( pbReplace );
174049        *pbReplace = 1;
174050        break;
174051
174052      case SQLITE_CHANGESET_OMIT:
174053        break;
174054
174055      case SQLITE_CHANGESET_ABORT:
174056        rc = SQLITE_ABORT;
174057        break;
174058
174059      default:
174060        rc = SQLITE_MISUSE;
174061        break;
174062    }
174063  }
174064
174065  return rc;
174066}
174067
174068/*
174069** Attempt to apply the change that the iterator passed as the first argument
174070** currently points to to the database. If a conflict is encountered, invoke
174071** the conflict handler callback.
174072**
174073** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
174074** one is encountered, update or delete the row with the matching primary key
174075** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
174076** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
174077** to true before returning. In this case the caller will invoke this function
174078** again, this time with pbRetry set to NULL.
174079**
174080** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
174081** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
174082** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
174083** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
174084** before retrying. In this case the caller attempts to remove the conflicting
174085** row before invoking this function again, this time with pbReplace set
174086** to NULL.
174087**
174088** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
174089** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
174090** returned.
174091*/
174092static int sessionApplyOneOp(
174093  sqlite3_changeset_iter *pIter,  /* Changeset iterator */
174094  SessionApplyCtx *p,             /* changeset_apply() context */
174095  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
174096  void *pCtx,                     /* First argument for the conflict handler */
174097  int *pbReplace,                 /* OUT: True to remove PK row and retry */
174098  int *pbRetry                    /* OUT: True to retry. */
174099){
174100  const char *zDummy;
174101  int op;
174102  int nCol;
174103  int rc = SQLITE_OK;
174104
174105  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
174106  assert( p->azCol && p->abPK );
174107  assert( !pbReplace || *pbReplace==0 );
174108
174109  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
174110
174111  if( op==SQLITE_DELETE ){
174112
174113    /* Bind values to the DELETE statement. If conflict handling is required,
174114    ** bind values for all columns and set bound variable (nCol+1) to true.
174115    ** Or, if conflict handling is not required, bind just the PK column
174116    ** values and, if it exists, set (nCol+1) to false. Conflict handling
174117    ** is not required if:
174118    **
174119    **   * this is a patchset, or
174120    **   * (pbRetry==0), or
174121    **   * all columns of the table are PK columns (in this case there is
174122    **     no (nCol+1) variable to bind to).
174123    */
174124    u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
174125    rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
174126    if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
174127      rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
174128    }
174129    if( rc!=SQLITE_OK ) return rc;
174130
174131    sqlite3_step(p->pDelete);
174132    rc = sqlite3_reset(p->pDelete);
174133    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
174134      rc = sessionConflictHandler(
174135          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
174136      );
174137    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
174138      rc = sessionConflictHandler(
174139          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
174140      );
174141    }
174142
174143  }else if( op==SQLITE_UPDATE ){
174144    int i;
174145
174146    /* Bind values to the UPDATE statement. */
174147    for(i=0; rc==SQLITE_OK && i<nCol; i++){
174148      sqlite3_value *pOld = sessionChangesetOld(pIter, i);
174149      sqlite3_value *pNew = sessionChangesetNew(pIter, i);
174150
174151      sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
174152      if( pOld ){
174153        rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
174154      }
174155      if( rc==SQLITE_OK && pNew ){
174156        rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
174157      }
174158    }
174159    if( rc==SQLITE_OK ){
174160      sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
174161    }
174162    if( rc!=SQLITE_OK ) return rc;
174163
174164    /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
174165    ** the result will be SQLITE_OK with 0 rows modified. */
174166    sqlite3_step(p->pUpdate);
174167    rc = sqlite3_reset(p->pUpdate);
174168
174169    if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
174170      /* A NOTFOUND or DATA error. Search the table to see if it contains
174171      ** a row with a matching primary key. If so, this is a DATA conflict.
174172      ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
174173
174174      rc = sessionConflictHandler(
174175          SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
174176      );
174177
174178    }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
174179      /* This is always a CONSTRAINT conflict. */
174180      rc = sessionConflictHandler(
174181          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
174182      );
174183    }
174184
174185  }else{
174186    assert( op==SQLITE_INSERT );
174187    rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
174188    if( rc!=SQLITE_OK ) return rc;
174189
174190    sqlite3_step(p->pInsert);
174191    rc = sqlite3_reset(p->pInsert);
174192    if( (rc&0xff)==SQLITE_CONSTRAINT ){
174193      rc = sessionConflictHandler(
174194          SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
174195      );
174196    }
174197  }
174198
174199  return rc;
174200}
174201
174202/*
174203** Attempt to apply the change that the iterator passed as the first argument
174204** currently points to to the database. If a conflict is encountered, invoke
174205** the conflict handler callback.
174206**
174207** The difference between this function and sessionApplyOne() is that this
174208** function handles the case where the conflict-handler is invoked and
174209** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
174210** retried in some manner.
174211*/
174212static int sessionApplyOneWithRetry(
174213  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174214  sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
174215  SessionApplyCtx *pApply,        /* Apply context */
174216  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
174217  void *pCtx                      /* First argument passed to xConflict */
174218){
174219  int bReplace = 0;
174220  int bRetry = 0;
174221  int rc;
174222
174223  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
174224  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
174225
174226  /* If the bRetry flag is set, the change has not been applied due to an
174227  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
174228  ** a row with the correct PK is present in the db, but one or more other
174229  ** fields do not contain the expected values) and the conflict handler
174230  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
174231  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
174232  ** the SQLITE_CHANGESET_DATA problem.  */
174233  if( bRetry ){
174234    assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
174235    rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
174236  }
174237
174238  /* If the bReplace flag is set, the change is an INSERT that has not
174239  ** been performed because the database already contains a row with the
174240  ** specified primary key and the conflict handler returned
174241  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
174242  ** before reattempting the INSERT.  */
174243  else if( bReplace ){
174244    assert( pIter->op==SQLITE_INSERT );
174245    rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
174246    if( rc==SQLITE_OK ){
174247      rc = sessionBindRow(pIter,
174248          sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
174249      sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
174250    }
174251    if( rc==SQLITE_OK ){
174252      sqlite3_step(pApply->pDelete);
174253      rc = sqlite3_reset(pApply->pDelete);
174254    }
174255    if( rc==SQLITE_OK ){
174256      rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
174257    }
174258    if( rc==SQLITE_OK ){
174259      rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
174260    }
174261  }
174262
174263  return rc;
174264}
174265
174266/*
174267** Retry the changes accumulated in the pApply->constraints buffer.
174268*/
174269static int sessionRetryConstraints(
174270  sqlite3 *db,
174271  int bPatchset,
174272  const char *zTab,
174273  SessionApplyCtx *pApply,
174274  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
174275  void *pCtx                      /* First argument passed to xConflict */
174276){
174277  int rc = SQLITE_OK;
174278
174279  while( pApply->constraints.nBuf ){
174280    sqlite3_changeset_iter *pIter2 = 0;
174281    SessionBuffer cons = pApply->constraints;
174282    memset(&pApply->constraints, 0, sizeof(SessionBuffer));
174283
174284    rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
174285    if( rc==SQLITE_OK ){
174286      int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
174287      int rc2;
174288      pIter2->bPatchset = bPatchset;
174289      pIter2->zTab = (char*)zTab;
174290      pIter2->nCol = pApply->nCol;
174291      pIter2->abPK = pApply->abPK;
174292      sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
174293      pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
174294      if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
174295
174296      while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
174297        rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
174298      }
174299
174300      rc2 = sqlite3changeset_finalize(pIter2);
174301      if( rc==SQLITE_OK ) rc = rc2;
174302    }
174303    assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
174304
174305    sqlite3_free(cons.aBuf);
174306    if( rc!=SQLITE_OK ) break;
174307    if( pApply->constraints.nBuf>=cons.nBuf ){
174308      /* No progress was made on the last round. */
174309      pApply->bDeferConstraints = 0;
174310    }
174311  }
174312
174313  return rc;
174314}
174315
174316/*
174317** Argument pIter is a changeset iterator that has been initialized, but
174318** not yet passed to sqlite3changeset_next(). This function applies the
174319** changeset to the main database attached to handle "db". The supplied
174320** conflict handler callback is invoked to resolve any conflicts encountered
174321** while applying the change.
174322*/
174323static int sessionChangesetApply(
174324  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174325  sqlite3_changeset_iter *pIter,  /* Changeset to apply */
174326  int(*xFilter)(
174327    void *pCtx,                   /* Copy of sixth arg to _apply() */
174328    const char *zTab              /* Table name */
174329  ),
174330  int(*xConflict)(
174331    void *pCtx,                   /* Copy of fifth arg to _apply() */
174332    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174333    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174334  ),
174335  void *pCtx                      /* First argument passed to xConflict */
174336){
174337  int schemaMismatch = 0;
174338  int rc;                         /* Return code */
174339  const char *zTab = 0;           /* Name of current table */
174340  int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
174341  SessionApplyCtx sApply;         /* changeset_apply() context object */
174342  int bPatchset;
174343
174344  assert( xConflict!=0 );
174345
174346  pIter->in.bNoDiscard = 1;
174347  memset(&sApply, 0, sizeof(sApply));
174348  sqlite3_mutex_enter(sqlite3_db_mutex(db));
174349  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
174350  if( rc==SQLITE_OK ){
174351    rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
174352  }
174353  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
174354    int nCol;
174355    int op;
174356    const char *zNew;
174357
174358    sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
174359
174360    if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
174361      u8 *abPK;
174362
174363      rc = sessionRetryConstraints(
174364          db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
174365      );
174366      if( rc!=SQLITE_OK ) break;
174367
174368      sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
174369      sqlite3_finalize(sApply.pDelete);
174370      sqlite3_finalize(sApply.pUpdate);
174371      sqlite3_finalize(sApply.pInsert);
174372      sqlite3_finalize(sApply.pSelect);
174373      memset(&sApply, 0, sizeof(sApply));
174374      sApply.db = db;
174375      sApply.bDeferConstraints = 1;
174376
174377      /* If an xFilter() callback was specified, invoke it now. If the
174378      ** xFilter callback returns zero, skip this table. If it returns
174379      ** non-zero, proceed. */
174380      schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
174381      if( schemaMismatch ){
174382        zTab = sqlite3_mprintf("%s", zNew);
174383        if( zTab==0 ){
174384          rc = SQLITE_NOMEM;
174385          break;
174386        }
174387        nTab = (int)strlen(zTab);
174388        sApply.azCol = (const char **)zTab;
174389      }else{
174390        sqlite3changeset_pk(pIter, &abPK, 0);
174391        rc = sessionTableInfo(
174392            db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
174393        );
174394        if( rc!=SQLITE_OK ) break;
174395
174396        if( sApply.nCol==0 ){
174397          schemaMismatch = 1;
174398          sqlite3_log(SQLITE_SCHEMA,
174399              "sqlite3changeset_apply(): no such table: %s", zTab
174400          );
174401        }
174402        else if( sApply.nCol!=nCol ){
174403          schemaMismatch = 1;
174404          sqlite3_log(SQLITE_SCHEMA,
174405              "sqlite3changeset_apply(): table %s has %d columns, expected %d",
174406              zTab, sApply.nCol, nCol
174407          );
174408        }
174409        else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
174410          schemaMismatch = 1;
174411          sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
174412              "primary key mismatch for table %s", zTab
174413          );
174414        }
174415        else if(
174416            (rc = sessionSelectRow(db, zTab, &sApply))
174417         || (rc = sessionUpdateRow(db, zTab, &sApply))
174418         || (rc = sessionDeleteRow(db, zTab, &sApply))
174419         || (rc = sessionInsertRow(db, zTab, &sApply))
174420        ){
174421          break;
174422        }
174423        nTab = sqlite3Strlen30(zTab);
174424      }
174425    }
174426
174427    /* If there is a schema mismatch on the current table, proceed to the
174428    ** next change. A log message has already been issued. */
174429    if( schemaMismatch ) continue;
174430
174431    rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
174432  }
174433
174434  bPatchset = pIter->bPatchset;
174435  if( rc==SQLITE_OK ){
174436    rc = sqlite3changeset_finalize(pIter);
174437  }else{
174438    sqlite3changeset_finalize(pIter);
174439  }
174440
174441  if( rc==SQLITE_OK ){
174442    rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
174443  }
174444
174445  if( rc==SQLITE_OK ){
174446    int nFk, notUsed;
174447    sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
174448    if( nFk!=0 ){
174449      int res = SQLITE_CHANGESET_ABORT;
174450      sqlite3_changeset_iter sIter;
174451      memset(&sIter, 0, sizeof(sIter));
174452      sIter.nCol = nFk;
174453      res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
174454      if( res!=SQLITE_CHANGESET_OMIT ){
174455        rc = SQLITE_CONSTRAINT;
174456      }
174457    }
174458  }
174459  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
174460
174461  if( rc==SQLITE_OK ){
174462    rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
174463  }else{
174464    sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
174465    sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
174466  }
174467
174468  sqlite3_finalize(sApply.pInsert);
174469  sqlite3_finalize(sApply.pDelete);
174470  sqlite3_finalize(sApply.pUpdate);
174471  sqlite3_finalize(sApply.pSelect);
174472  sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
174473  sqlite3_free((char*)sApply.constraints.aBuf);
174474  sqlite3_mutex_leave(sqlite3_db_mutex(db));
174475  return rc;
174476}
174477
174478/*
174479** Apply the changeset passed via pChangeset/nChangeset to the main database
174480** attached to handle "db". Invoke the supplied conflict handler callback
174481** to resolve any conflicts encountered while applying the change.
174482*/
174483SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply(
174484  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174485  int nChangeset,                 /* Size of changeset in bytes */
174486  void *pChangeset,               /* Changeset blob */
174487  int(*xFilter)(
174488    void *pCtx,                   /* Copy of sixth arg to _apply() */
174489    const char *zTab              /* Table name */
174490  ),
174491  int(*xConflict)(
174492    void *pCtx,                   /* Copy of fifth arg to _apply() */
174493    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174494    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174495  ),
174496  void *pCtx                      /* First argument passed to xConflict */
174497){
174498  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
174499  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
174500  if( rc==SQLITE_OK ){
174501    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
174502  }
174503  return rc;
174504}
174505
174506/*
174507** Apply the changeset passed via xInput/pIn to the main database
174508** attached to handle "db". Invoke the supplied conflict handler callback
174509** to resolve any conflicts encountered while applying the change.
174510*/
174511SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply_strm(
174512  sqlite3 *db,                    /* Apply change to "main" db of this handle */
174513  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
174514  void *pIn,                                          /* First arg for xInput */
174515  int(*xFilter)(
174516    void *pCtx,                   /* Copy of sixth arg to _apply() */
174517    const char *zTab              /* Table name */
174518  ),
174519  int(*xConflict)(
174520    void *pCtx,                   /* Copy of sixth arg to _apply() */
174521    int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174522    sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174523  ),
174524  void *pCtx                      /* First argument passed to xConflict */
174525){
174526  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
174527  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
174528  if( rc==SQLITE_OK ){
174529    rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
174530  }
174531  return rc;
174532}
174533
174534/*
174535** sqlite3_changegroup handle.
174536*/
174537struct sqlite3_changegroup {
174538  int rc;                         /* Error code */
174539  int bPatch;                     /* True to accumulate patchsets */
174540  SessionTable *pList;            /* List of tables in current patch */
174541};
174542
174543/*
174544** This function is called to merge two changes to the same row together as
174545** part of an sqlite3changeset_concat() operation. A new change object is
174546** allocated and a pointer to it stored in *ppNew.
174547*/
174548static int sessionChangeMerge(
174549  SessionTable *pTab,             /* Table structure */
174550  int bPatchset,                  /* True for patchsets */
174551  SessionChange *pExist,          /* Existing change */
174552  int op2,                        /* Second change operation */
174553  int bIndirect,                  /* True if second change is indirect */
174554  u8 *aRec,                       /* Second change record */
174555  int nRec,                       /* Number of bytes in aRec */
174556  SessionChange **ppNew           /* OUT: Merged change */
174557){
174558  SessionChange *pNew = 0;
174559
174560  if( !pExist ){
174561    pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
174562    if( !pNew ){
174563      return SQLITE_NOMEM;
174564    }
174565    memset(pNew, 0, sizeof(SessionChange));
174566    pNew->op = op2;
174567    pNew->bIndirect = bIndirect;
174568    pNew->nRecord = nRec;
174569    pNew->aRecord = (u8*)&pNew[1];
174570    memcpy(pNew->aRecord, aRec, nRec);
174571  }else{
174572    int op1 = pExist->op;
174573
174574    /*
174575    **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
174576    **   op1=INSERT, op2=UPDATE      ->      INSERT.
174577    **   op1=INSERT, op2=DELETE      ->      (none)
174578    **
174579    **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
174580    **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
174581    **   op1=UPDATE, op2=DELETE      ->      DELETE.
174582    **
174583    **   op1=DELETE, op2=INSERT      ->      UPDATE.
174584    **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
174585    **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
174586    */
174587    if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
174588     || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
174589     || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
174590     || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
174591    ){
174592      pNew = pExist;
174593    }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
174594      sqlite3_free(pExist);
174595      assert( pNew==0 );
174596    }else{
174597      u8 *aExist = pExist->aRecord;
174598      int nByte;
174599      u8 *aCsr;
174600
174601      /* Allocate a new SessionChange object. Ensure that the aRecord[]
174602      ** buffer of the new object is large enough to hold any record that
174603      ** may be generated by combining the input records.  */
174604      nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
174605      pNew = (SessionChange *)sqlite3_malloc(nByte);
174606      if( !pNew ){
174607        sqlite3_free(pExist);
174608        return SQLITE_NOMEM;
174609      }
174610      memset(pNew, 0, sizeof(SessionChange));
174611      pNew->bIndirect = (bIndirect && pExist->bIndirect);
174612      aCsr = pNew->aRecord = (u8 *)&pNew[1];
174613
174614      if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
174615        u8 *a1 = aRec;
174616        assert( op2==SQLITE_UPDATE );
174617        pNew->op = SQLITE_INSERT;
174618        if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
174619        sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
174620      }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
174621        assert( op2==SQLITE_INSERT );
174622        pNew->op = SQLITE_UPDATE;
174623        if( bPatchset ){
174624          memcpy(aCsr, aRec, nRec);
174625          aCsr += nRec;
174626        }else{
174627          if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
174628            sqlite3_free(pNew);
174629            pNew = 0;
174630          }
174631        }
174632      }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
174633        u8 *a1 = aExist;
174634        u8 *a2 = aRec;
174635        assert( op1==SQLITE_UPDATE );
174636        if( bPatchset==0 ){
174637          sessionSkipRecord(&a1, pTab->nCol);
174638          sessionSkipRecord(&a2, pTab->nCol);
174639        }
174640        pNew->op = SQLITE_UPDATE;
174641        if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
174642          sqlite3_free(pNew);
174643          pNew = 0;
174644        }
174645      }else{                                /* UPDATE + DELETE */
174646        assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
174647        pNew->op = SQLITE_DELETE;
174648        if( bPatchset ){
174649          memcpy(aCsr, aRec, nRec);
174650          aCsr += nRec;
174651        }else{
174652          sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
174653        }
174654      }
174655
174656      if( pNew ){
174657        pNew->nRecord = (int)(aCsr - pNew->aRecord);
174658      }
174659      sqlite3_free(pExist);
174660    }
174661  }
174662
174663  *ppNew = pNew;
174664  return SQLITE_OK;
174665}
174666
174667/*
174668** Add all changes in the changeset traversed by the iterator passed as
174669** the first argument to the changegroup hash tables.
174670*/
174671static int sessionChangesetToHash(
174672  sqlite3_changeset_iter *pIter,   /* Iterator to read from */
174673  sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
174674){
174675  u8 *aRec;
174676  int nRec;
174677  int rc = SQLITE_OK;
174678  SessionTable *pTab = 0;
174679
174680
174681  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
174682    const char *zNew;
174683    int nCol;
174684    int op;
174685    int iHash;
174686    int bIndirect;
174687    SessionChange *pChange;
174688    SessionChange *pExist = 0;
174689    SessionChange **pp;
174690
174691    if( pGrp->pList==0 ){
174692      pGrp->bPatch = pIter->bPatchset;
174693    }else if( pIter->bPatchset!=pGrp->bPatch ){
174694      rc = SQLITE_ERROR;
174695      break;
174696    }
174697
174698    sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
174699    if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
174700      /* Search the list for a matching table */
174701      int nNew = (int)strlen(zNew);
174702      u8 *abPK;
174703
174704      sqlite3changeset_pk(pIter, &abPK, 0);
174705      for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
174706        if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
174707      }
174708      if( !pTab ){
174709        SessionTable **ppTab;
174710
174711        pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
174712        if( !pTab ){
174713          rc = SQLITE_NOMEM;
174714          break;
174715        }
174716        memset(pTab, 0, sizeof(SessionTable));
174717        pTab->nCol = nCol;
174718        pTab->abPK = (u8*)&pTab[1];
174719        memcpy(pTab->abPK, abPK, nCol);
174720        pTab->zName = (char*)&pTab->abPK[nCol];
174721        memcpy(pTab->zName, zNew, nNew+1);
174722
174723        /* The new object must be linked on to the end of the list, not
174724        ** simply added to the start of it. This is to ensure that the
174725        ** tables within the output of sqlite3changegroup_output() are in
174726        ** the right order.  */
174727        for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
174728        *ppTab = pTab;
174729      }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
174730        rc = SQLITE_SCHEMA;
174731        break;
174732      }
174733    }
174734
174735    if( sessionGrowHash(pIter->bPatchset, pTab) ){
174736      rc = SQLITE_NOMEM;
174737      break;
174738    }
174739    iHash = sessionChangeHash(
174740        pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
174741    );
174742
174743    /* Search for existing entry. If found, remove it from the hash table.
174744    ** Code below may link it back in.
174745    */
174746    for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
174747      int bPkOnly1 = 0;
174748      int bPkOnly2 = 0;
174749      if( pIter->bPatchset ){
174750        bPkOnly1 = (*pp)->op==SQLITE_DELETE;
174751        bPkOnly2 = op==SQLITE_DELETE;
174752      }
174753      if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
174754        pExist = *pp;
174755        *pp = (*pp)->pNext;
174756        pTab->nEntry--;
174757        break;
174758      }
174759    }
174760
174761    rc = sessionChangeMerge(pTab,
174762        pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
174763    );
174764    if( rc ) break;
174765    if( pChange ){
174766      pChange->pNext = pTab->apChange[iHash];
174767      pTab->apChange[iHash] = pChange;
174768      pTab->nEntry++;
174769    }
174770  }
174771
174772  if( rc==SQLITE_OK ) rc = pIter->rc;
174773  return rc;
174774}
174775
174776/*
174777** Serialize a changeset (or patchset) based on all changesets (or patchsets)
174778** added to the changegroup object passed as the first argument.
174779**
174780** If xOutput is not NULL, then the changeset/patchset is returned to the
174781** user via one or more calls to xOutput, as with the other streaming
174782** interfaces.
174783**
174784** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
174785** buffer containing the output changeset before this function returns. In
174786** this case (*pnOut) is set to the size of the output buffer in bytes. It
174787** is the responsibility of the caller to free the output buffer using
174788** sqlite3_free() when it is no longer required.
174789**
174790** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
174791** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
174792** are both set to 0 before returning.
174793*/
174794static int sessionChangegroupOutput(
174795  sqlite3_changegroup *pGrp,
174796  int (*xOutput)(void *pOut, const void *pData, int nData),
174797  void *pOut,
174798  int *pnOut,
174799  void **ppOut
174800){
174801  int rc = SQLITE_OK;
174802  SessionBuffer buf = {0, 0, 0};
174803  SessionTable *pTab;
174804  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
174805
174806  /* Create the serialized output changeset based on the contents of the
174807  ** hash tables attached to the SessionTable objects in list p->pList.
174808  */
174809  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
174810    int i;
174811    if( pTab->nEntry==0 ) continue;
174812
174813    sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
174814    for(i=0; i<pTab->nChange; i++){
174815      SessionChange *p;
174816      for(p=pTab->apChange[i]; p; p=p->pNext){
174817        sessionAppendByte(&buf, p->op, &rc);
174818        sessionAppendByte(&buf, p->bIndirect, &rc);
174819        sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
174820      }
174821    }
174822
174823    if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
174824      rc = xOutput(pOut, buf.aBuf, buf.nBuf);
174825      buf.nBuf = 0;
174826    }
174827  }
174828
174829  if( rc==SQLITE_OK ){
174830    if( xOutput ){
174831      if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
174832    }else{
174833      *ppOut = buf.aBuf;
174834      *pnOut = buf.nBuf;
174835      buf.aBuf = 0;
174836    }
174837  }
174838  sqlite3_free(buf.aBuf);
174839
174840  return rc;
174841}
174842
174843/*
174844** Allocate a new, empty, sqlite3_changegroup.
174845*/
174846SQLITE_API int SQLITE_STDCALL sqlite3changegroup_new(sqlite3_changegroup **pp){
174847  int rc = SQLITE_OK;             /* Return code */
174848  sqlite3_changegroup *p;         /* New object */
174849  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
174850  if( p==0 ){
174851    rc = SQLITE_NOMEM;
174852  }else{
174853    memset(p, 0, sizeof(sqlite3_changegroup));
174854  }
174855  *pp = p;
174856  return rc;
174857}
174858
174859/*
174860** Add the changeset currently stored in buffer pData, size nData bytes,
174861** to changeset-group p.
174862*/
174863SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
174864  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
174865  int rc;                         /* Return code */
174866
174867  rc = sqlite3changeset_start(&pIter, nData, pData);
174868  if( rc==SQLITE_OK ){
174869    rc = sessionChangesetToHash(pIter, pGrp);
174870  }
174871  sqlite3changeset_finalize(pIter);
174872  return rc;
174873}
174874
174875/*
174876** Obtain a buffer containing a changeset representing the concatenation
174877** of all changesets added to the group so far.
174878*/
174879SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output(
174880    sqlite3_changegroup *pGrp,
174881    int *pnData,
174882    void **ppData
174883){
174884  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
174885}
174886
174887/*
174888** Streaming versions of changegroup_add().
174889*/
174890SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add_strm(
174891  sqlite3_changegroup *pGrp,
174892  int (*xInput)(void *pIn, void *pData, int *pnData),
174893  void *pIn
174894){
174895  sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
174896  int rc;                         /* Return code */
174897
174898  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
174899  if( rc==SQLITE_OK ){
174900    rc = sessionChangesetToHash(pIter, pGrp);
174901  }
174902  sqlite3changeset_finalize(pIter);
174903  return rc;
174904}
174905
174906/*
174907** Streaming versions of changegroup_output().
174908*/
174909SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output_strm(
174910  sqlite3_changegroup *pGrp,
174911  int (*xOutput)(void *pOut, const void *pData, int nData),
174912  void *pOut
174913){
174914  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
174915}
174916
174917/*
174918** Delete a changegroup object.
174919*/
174920SQLITE_API void SQLITE_STDCALL sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
174921  if( pGrp ){
174922    sessionDeleteTable(pGrp->pList);
174923    sqlite3_free(pGrp);
174924  }
174925}
174926
174927/*
174928** Combine two changesets together.
174929*/
174930SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat(
174931  int nLeft,                      /* Number of bytes in lhs input */
174932  void *pLeft,                    /* Lhs input changeset */
174933  int nRight                      /* Number of bytes in rhs input */,
174934  void *pRight,                   /* Rhs input changeset */
174935  int *pnOut,                     /* OUT: Number of bytes in output changeset */
174936  void **ppOut                    /* OUT: changeset (left <concat> right) */
174937){
174938  sqlite3_changegroup *pGrp;
174939  int rc;
174940
174941  rc = sqlite3changegroup_new(&pGrp);
174942  if( rc==SQLITE_OK ){
174943    rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
174944  }
174945  if( rc==SQLITE_OK ){
174946    rc = sqlite3changegroup_add(pGrp, nRight, pRight);
174947  }
174948  if( rc==SQLITE_OK ){
174949    rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
174950  }
174951  sqlite3changegroup_delete(pGrp);
174952
174953  return rc;
174954}
174955
174956/*
174957** Streaming version of sqlite3changeset_concat().
174958*/
174959SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat_strm(
174960  int (*xInputA)(void *pIn, void *pData, int *pnData),
174961  void *pInA,
174962  int (*xInputB)(void *pIn, void *pData, int *pnData),
174963  void *pInB,
174964  int (*xOutput)(void *pOut, const void *pData, int nData),
174965  void *pOut
174966){
174967  sqlite3_changegroup *pGrp;
174968  int rc;
174969
174970  rc = sqlite3changegroup_new(&pGrp);
174971  if( rc==SQLITE_OK ){
174972    rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
174973  }
174974  if( rc==SQLITE_OK ){
174975    rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
174976  }
174977  if( rc==SQLITE_OK ){
174978    rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
174979  }
174980  sqlite3changegroup_delete(pGrp);
174981
174982  return rc;
174983}
174984
174985#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
174986
174987/************** End of sqlite3session.c **************************************/
174988/************** Begin file json1.c *******************************************/
174989/*
174990** 2015-08-12
174991**
174992** The author disclaims copyright to this source code.  In place of
174993** a legal notice, here is a blessing:
174994**
174995**    May you do good and not evil.
174996**    May you find forgiveness for yourself and forgive others.
174997**    May you share freely, never taking more than you give.
174998**
174999******************************************************************************
175000**
175001** This SQLite extension implements JSON functions.  The interface is
175002** modeled after MySQL JSON functions:
175003**
175004**     https://dev.mysql.com/doc/refman/5.7/en/json.html
175005**
175006** For the time being, all JSON is stored as pure text.  (We might add
175007** a JSONB type in the future which stores a binary encoding of JSON in
175008** a BLOB, but there is no support for JSONB in the current implementation.
175009** This implementation parses JSON text at 250 MB/s, so it is hard to see
175010** how JSONB might improve on that.)
175011*/
175012#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
175013#if !defined(_SQLITEINT_H_)
175014/* #include "sqlite3ext.h" */
175015#endif
175016SQLITE_EXTENSION_INIT1
175017/* #include <assert.h> */
175018/* #include <string.h> */
175019/* #include <stdlib.h> */
175020/* #include <stdarg.h> */
175021
175022/* Mark a function parameter as unused, to suppress nuisance compiler
175023** warnings. */
175024#ifndef UNUSED_PARAM
175025# define UNUSED_PARAM(X)  (void)(X)
175026#endif
175027
175028#ifndef LARGEST_INT64
175029# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
175030# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
175031#endif
175032
175033/*
175034** Versions of isspace(), isalnum() and isdigit() to which it is safe
175035** to pass signed char values.
175036*/
175037#ifdef sqlite3Isdigit
175038   /* Use the SQLite core versions if this routine is part of the
175039   ** SQLite amalgamation */
175040#  define safe_isdigit(x) sqlite3Isdigit(x)
175041#  define safe_isalnum(x) sqlite3Isalnum(x)
175042#else
175043   /* Use the standard library for separate compilation */
175044#include <ctype.h>  /* amalgamator: keep */
175045#  define safe_isdigit(x) isdigit((unsigned char)(x))
175046#  define safe_isalnum(x) isalnum((unsigned char)(x))
175047#endif
175048
175049/*
175050** Growing our own isspace() routine this way is twice as fast as
175051** the library isspace() function, resulting in a 7% overall performance
175052** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
175053*/
175054static const char jsonIsSpace[] = {
175055  0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
175056  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175057  1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175058  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175059  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175060  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175061  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175062  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175063  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175064  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175065  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175066  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175067  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175068  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175069  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175070  0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175071};
175072#define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
175073
175074#ifndef SQLITE_AMALGAMATION
175075  /* Unsigned integer types.  These are already defined in the sqliteInt.h,
175076  ** but the definitions need to be repeated for separate compilation. */
175077  typedef sqlite3_uint64 u64;
175078  typedef unsigned int u32;
175079  typedef unsigned char u8;
175080#endif
175081
175082/* Objects */
175083typedef struct JsonString JsonString;
175084typedef struct JsonNode JsonNode;
175085typedef struct JsonParse JsonParse;
175086
175087/* An instance of this object represents a JSON string
175088** under construction.  Really, this is a generic string accumulator
175089** that can be and is used to create strings other than JSON.
175090*/
175091struct JsonString {
175092  sqlite3_context *pCtx;   /* Function context - put error messages here */
175093  char *zBuf;              /* Append JSON content here */
175094  u64 nAlloc;              /* Bytes of storage available in zBuf[] */
175095  u64 nUsed;               /* Bytes of zBuf[] currently used */
175096  u8 bStatic;              /* True if zBuf is static space */
175097  u8 bErr;                 /* True if an error has been encountered */
175098  char zSpace[100];        /* Initial static space */
175099};
175100
175101/* JSON type values
175102*/
175103#define JSON_NULL     0
175104#define JSON_TRUE     1
175105#define JSON_FALSE    2
175106#define JSON_INT      3
175107#define JSON_REAL     4
175108#define JSON_STRING   5
175109#define JSON_ARRAY    6
175110#define JSON_OBJECT   7
175111
175112/* The "subtype" set for JSON values */
175113#define JSON_SUBTYPE  74    /* Ascii for "J" */
175114
175115/*
175116** Names of the various JSON types:
175117*/
175118static const char * const jsonType[] = {
175119  "null", "true", "false", "integer", "real", "text", "array", "object"
175120};
175121
175122/* Bit values for the JsonNode.jnFlag field
175123*/
175124#define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
175125#define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
175126#define JNODE_REMOVE  0x04         /* Do not output */
175127#define JNODE_REPLACE 0x08         /* Replace with JsonNode.iVal */
175128#define JNODE_APPEND  0x10         /* More ARRAY/OBJECT entries at u.iAppend */
175129#define JNODE_LABEL   0x20         /* Is a label of an object */
175130
175131
175132/* A single node of parsed JSON
175133*/
175134struct JsonNode {
175135  u8 eType;              /* One of the JSON_ type values */
175136  u8 jnFlags;            /* JNODE flags */
175137  u8 iVal;               /* Replacement value when JNODE_REPLACE */
175138  u32 n;                 /* Bytes of content, or number of sub-nodes */
175139  union {
175140    const char *zJContent; /* Content for INT, REAL, and STRING */
175141    u32 iAppend;           /* More terms for ARRAY and OBJECT */
175142    u32 iKey;              /* Key for ARRAY objects in json_tree() */
175143  } u;
175144};
175145
175146/* A completely parsed JSON string
175147*/
175148struct JsonParse {
175149  u32 nNode;         /* Number of slots of aNode[] used */
175150  u32 nAlloc;        /* Number of slots of aNode[] allocated */
175151  JsonNode *aNode;   /* Array of nodes containing the parse */
175152  const char *zJson; /* Original JSON string */
175153  u32 *aUp;          /* Index of parent of each node */
175154  u8 oom;            /* Set to true if out of memory */
175155  u8 nErr;           /* Number of errors seen */
175156};
175157
175158/**************************************************************************
175159** Utility routines for dealing with JsonString objects
175160**************************************************************************/
175161
175162/* Set the JsonString object to an empty string
175163*/
175164static void jsonZero(JsonString *p){
175165  p->zBuf = p->zSpace;
175166  p->nAlloc = sizeof(p->zSpace);
175167  p->nUsed = 0;
175168  p->bStatic = 1;
175169}
175170
175171/* Initialize the JsonString object
175172*/
175173static void jsonInit(JsonString *p, sqlite3_context *pCtx){
175174  p->pCtx = pCtx;
175175  p->bErr = 0;
175176  jsonZero(p);
175177}
175178
175179
175180/* Free all allocated memory and reset the JsonString object back to its
175181** initial state.
175182*/
175183static void jsonReset(JsonString *p){
175184  if( !p->bStatic ) sqlite3_free(p->zBuf);
175185  jsonZero(p);
175186}
175187
175188
175189/* Report an out-of-memory (OOM) condition
175190*/
175191static void jsonOom(JsonString *p){
175192  p->bErr = 1;
175193  sqlite3_result_error_nomem(p->pCtx);
175194  jsonReset(p);
175195}
175196
175197/* Enlarge pJson->zBuf so that it can hold at least N more bytes.
175198** Return zero on success.  Return non-zero on an OOM error
175199*/
175200static int jsonGrow(JsonString *p, u32 N){
175201  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
175202  char *zNew;
175203  if( p->bStatic ){
175204    if( p->bErr ) return 1;
175205    zNew = sqlite3_malloc64(nTotal);
175206    if( zNew==0 ){
175207      jsonOom(p);
175208      return SQLITE_NOMEM;
175209    }
175210    memcpy(zNew, p->zBuf, (size_t)p->nUsed);
175211    p->zBuf = zNew;
175212    p->bStatic = 0;
175213  }else{
175214    zNew = sqlite3_realloc64(p->zBuf, nTotal);
175215    if( zNew==0 ){
175216      jsonOom(p);
175217      return SQLITE_NOMEM;
175218    }
175219    p->zBuf = zNew;
175220  }
175221  p->nAlloc = nTotal;
175222  return SQLITE_OK;
175223}
175224
175225/* Append N bytes from zIn onto the end of the JsonString string.
175226*/
175227static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
175228  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
175229  memcpy(p->zBuf+p->nUsed, zIn, N);
175230  p->nUsed += N;
175231}
175232
175233/* Append formatted text (not to exceed N bytes) to the JsonString.
175234*/
175235static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
175236  va_list ap;
175237  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
175238  va_start(ap, zFormat);
175239  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
175240  va_end(ap);
175241  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
175242}
175243
175244/* Append a single character
175245*/
175246static void jsonAppendChar(JsonString *p, char c){
175247  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
175248  p->zBuf[p->nUsed++] = c;
175249}
175250
175251/* Append a comma separator to the output buffer, if the previous
175252** character is not '[' or '{'.
175253*/
175254static void jsonAppendSeparator(JsonString *p){
175255  char c;
175256  if( p->nUsed==0 ) return;
175257  c = p->zBuf[p->nUsed-1];
175258  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
175259}
175260
175261/* Append the N-byte string in zIn to the end of the JsonString string
175262** under construction.  Enclose the string in "..." and escape
175263** any double-quotes or backslash characters contained within the
175264** string.
175265*/
175266static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
175267  u32 i;
175268  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
175269  p->zBuf[p->nUsed++] = '"';
175270  for(i=0; i<N; i++){
175271    unsigned char c = ((unsigned const char*)zIn)[i];
175272    if( c=='"' || c=='\\' ){
175273      json_simple_escape:
175274      if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
175275      p->zBuf[p->nUsed++] = '\\';
175276    }else if( c<=0x1f ){
175277      static const char aSpecial[] = {
175278         0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
175279         0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
175280      };
175281      assert( sizeof(aSpecial)==32 );
175282      assert( aSpecial['\b']=='b' );
175283      assert( aSpecial['\f']=='f' );
175284      assert( aSpecial['\n']=='n' );
175285      assert( aSpecial['\r']=='r' );
175286      assert( aSpecial['\t']=='t' );
175287      if( aSpecial[c] ){
175288        c = aSpecial[c];
175289        goto json_simple_escape;
175290      }
175291      if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
175292      p->zBuf[p->nUsed++] = '\\';
175293      p->zBuf[p->nUsed++] = 'u';
175294      p->zBuf[p->nUsed++] = '0';
175295      p->zBuf[p->nUsed++] = '0';
175296      p->zBuf[p->nUsed++] = '0' + (c>>4);
175297      c = "0123456789abcdef"[c&0xf];
175298    }
175299    p->zBuf[p->nUsed++] = c;
175300  }
175301  p->zBuf[p->nUsed++] = '"';
175302  assert( p->nUsed<p->nAlloc );
175303}
175304
175305/*
175306** Append a function parameter value to the JSON string under
175307** construction.
175308*/
175309static void jsonAppendValue(
175310  JsonString *p,                 /* Append to this JSON string */
175311  sqlite3_value *pValue          /* Value to append */
175312){
175313  switch( sqlite3_value_type(pValue) ){
175314    case SQLITE_NULL: {
175315      jsonAppendRaw(p, "null", 4);
175316      break;
175317    }
175318    case SQLITE_INTEGER:
175319    case SQLITE_FLOAT: {
175320      const char *z = (const char*)sqlite3_value_text(pValue);
175321      u32 n = (u32)sqlite3_value_bytes(pValue);
175322      jsonAppendRaw(p, z, n);
175323      break;
175324    }
175325    case SQLITE_TEXT: {
175326      const char *z = (const char*)sqlite3_value_text(pValue);
175327      u32 n = (u32)sqlite3_value_bytes(pValue);
175328      if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
175329        jsonAppendRaw(p, z, n);
175330      }else{
175331        jsonAppendString(p, z, n);
175332      }
175333      break;
175334    }
175335    default: {
175336      if( p->bErr==0 ){
175337        sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
175338        p->bErr = 2;
175339        jsonReset(p);
175340      }
175341      break;
175342    }
175343  }
175344}
175345
175346
175347/* Make the JSON in p the result of the SQL function.
175348*/
175349static void jsonResult(JsonString *p){
175350  if( p->bErr==0 ){
175351    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
175352                          p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
175353                          SQLITE_UTF8);
175354    jsonZero(p);
175355  }
175356  assert( p->bStatic );
175357}
175358
175359/**************************************************************************
175360** Utility routines for dealing with JsonNode and JsonParse objects
175361**************************************************************************/
175362
175363/*
175364** Return the number of consecutive JsonNode slots need to represent
175365** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
175366** OBJECT types, the number might be larger.
175367**
175368** Appended elements are not counted.  The value returned is the number
175369** by which the JsonNode counter should increment in order to go to the
175370** next peer value.
175371*/
175372static u32 jsonNodeSize(JsonNode *pNode){
175373  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
175374}
175375
175376/*
175377** Reclaim all memory allocated by a JsonParse object.  But do not
175378** delete the JsonParse object itself.
175379*/
175380static void jsonParseReset(JsonParse *pParse){
175381  sqlite3_free(pParse->aNode);
175382  pParse->aNode = 0;
175383  pParse->nNode = 0;
175384  pParse->nAlloc = 0;
175385  sqlite3_free(pParse->aUp);
175386  pParse->aUp = 0;
175387}
175388
175389/*
175390** Convert the JsonNode pNode into a pure JSON string and
175391** append to pOut.  Subsubstructure is also included.  Return
175392** the number of JsonNode objects that are encoded.
175393*/
175394static void jsonRenderNode(
175395  JsonNode *pNode,               /* The node to render */
175396  JsonString *pOut,              /* Write JSON here */
175397  sqlite3_value **aReplace       /* Replacement values */
175398){
175399  switch( pNode->eType ){
175400    default: {
175401      assert( pNode->eType==JSON_NULL );
175402      jsonAppendRaw(pOut, "null", 4);
175403      break;
175404    }
175405    case JSON_TRUE: {
175406      jsonAppendRaw(pOut, "true", 4);
175407      break;
175408    }
175409    case JSON_FALSE: {
175410      jsonAppendRaw(pOut, "false", 5);
175411      break;
175412    }
175413    case JSON_STRING: {
175414      if( pNode->jnFlags & JNODE_RAW ){
175415        jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
175416        break;
175417      }
175418      /* Fall through into the next case */
175419    }
175420    case JSON_REAL:
175421    case JSON_INT: {
175422      jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
175423      break;
175424    }
175425    case JSON_ARRAY: {
175426      u32 j = 1;
175427      jsonAppendChar(pOut, '[');
175428      for(;;){
175429        while( j<=pNode->n ){
175430          if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
175431            if( pNode[j].jnFlags & JNODE_REPLACE ){
175432              jsonAppendSeparator(pOut);
175433              jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
175434            }
175435          }else{
175436            jsonAppendSeparator(pOut);
175437            jsonRenderNode(&pNode[j], pOut, aReplace);
175438          }
175439          j += jsonNodeSize(&pNode[j]);
175440        }
175441        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
175442        pNode = &pNode[pNode->u.iAppend];
175443        j = 1;
175444      }
175445      jsonAppendChar(pOut, ']');
175446      break;
175447    }
175448    case JSON_OBJECT: {
175449      u32 j = 1;
175450      jsonAppendChar(pOut, '{');
175451      for(;;){
175452        while( j<=pNode->n ){
175453          if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
175454            jsonAppendSeparator(pOut);
175455            jsonRenderNode(&pNode[j], pOut, aReplace);
175456            jsonAppendChar(pOut, ':');
175457            if( pNode[j+1].jnFlags & JNODE_REPLACE ){
175458              jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
175459            }else{
175460              jsonRenderNode(&pNode[j+1], pOut, aReplace);
175461            }
175462          }
175463          j += 1 + jsonNodeSize(&pNode[j+1]);
175464        }
175465        if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
175466        pNode = &pNode[pNode->u.iAppend];
175467        j = 1;
175468      }
175469      jsonAppendChar(pOut, '}');
175470      break;
175471    }
175472  }
175473}
175474
175475/*
175476** Return a JsonNode and all its descendents as a JSON string.
175477*/
175478static void jsonReturnJson(
175479  JsonNode *pNode,            /* Node to return */
175480  sqlite3_context *pCtx,      /* Return value for this function */
175481  sqlite3_value **aReplace    /* Array of replacement values */
175482){
175483  JsonString s;
175484  jsonInit(&s, pCtx);
175485  jsonRenderNode(pNode, &s, aReplace);
175486  jsonResult(&s);
175487  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
175488}
175489
175490/*
175491** Make the JsonNode the return value of the function.
175492*/
175493static void jsonReturn(
175494  JsonNode *pNode,            /* Node to return */
175495  sqlite3_context *pCtx,      /* Return value for this function */
175496  sqlite3_value **aReplace    /* Array of replacement values */
175497){
175498  switch( pNode->eType ){
175499    default: {
175500      assert( pNode->eType==JSON_NULL );
175501      sqlite3_result_null(pCtx);
175502      break;
175503    }
175504    case JSON_TRUE: {
175505      sqlite3_result_int(pCtx, 1);
175506      break;
175507    }
175508    case JSON_FALSE: {
175509      sqlite3_result_int(pCtx, 0);
175510      break;
175511    }
175512    case JSON_INT: {
175513      sqlite3_int64 i = 0;
175514      const char *z = pNode->u.zJContent;
175515      if( z[0]=='-' ){ z++; }
175516      while( z[0]>='0' && z[0]<='9' ){
175517        unsigned v = *(z++) - '0';
175518        if( i>=LARGEST_INT64/10 ){
175519          if( i>LARGEST_INT64/10 ) goto int_as_real;
175520          if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
175521          if( v==9 ) goto int_as_real;
175522          if( v==8 ){
175523            if( pNode->u.zJContent[0]=='-' ){
175524              sqlite3_result_int64(pCtx, SMALLEST_INT64);
175525              goto int_done;
175526            }else{
175527              goto int_as_real;
175528            }
175529          }
175530        }
175531        i = i*10 + v;
175532      }
175533      if( pNode->u.zJContent[0]=='-' ){ i = -i; }
175534      sqlite3_result_int64(pCtx, i);
175535      int_done:
175536      break;
175537      int_as_real: /* fall through to real */;
175538    }
175539    case JSON_REAL: {
175540      double r;
175541#ifdef SQLITE_AMALGAMATION
175542      const char *z = pNode->u.zJContent;
175543      sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
175544#else
175545      r = strtod(pNode->u.zJContent, 0);
175546#endif
175547      sqlite3_result_double(pCtx, r);
175548      break;
175549    }
175550    case JSON_STRING: {
175551#if 0 /* Never happens because JNODE_RAW is only set by json_set(),
175552      ** json_insert() and json_replace() and those routines do not
175553      ** call jsonReturn() */
175554      if( pNode->jnFlags & JNODE_RAW ){
175555        sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
175556                            SQLITE_TRANSIENT);
175557      }else
175558#endif
175559      assert( (pNode->jnFlags & JNODE_RAW)==0 );
175560      if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
175561        /* JSON formatted without any backslash-escapes */
175562        sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
175563                            SQLITE_TRANSIENT);
175564      }else{
175565        /* Translate JSON formatted string into raw text */
175566        u32 i;
175567        u32 n = pNode->n;
175568        const char *z = pNode->u.zJContent;
175569        char *zOut;
175570        u32 j;
175571        zOut = sqlite3_malloc( n+1 );
175572        if( zOut==0 ){
175573          sqlite3_result_error_nomem(pCtx);
175574          break;
175575        }
175576        for(i=1, j=0; i<n-1; i++){
175577          char c = z[i];
175578          if( c!='\\' ){
175579            zOut[j++] = c;
175580          }else{
175581            c = z[++i];
175582            if( c=='u' ){
175583              u32 v = 0, k;
175584              for(k=0; k<4 && i<n-2; i++, k++){
175585                c = z[i+1];
175586                if( c>='0' && c<='9' ) v = v*16 + c - '0';
175587                else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
175588                else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
175589                else break;
175590              }
175591              if( v==0 ) break;
175592              if( v<=0x7f ){
175593                zOut[j++] = (char)v;
175594              }else if( v<=0x7ff ){
175595                zOut[j++] = (char)(0xc0 | (v>>6));
175596                zOut[j++] = 0x80 | (v&0x3f);
175597              }else{
175598                zOut[j++] = (char)(0xe0 | (v>>12));
175599                zOut[j++] = 0x80 | ((v>>6)&0x3f);
175600                zOut[j++] = 0x80 | (v&0x3f);
175601              }
175602            }else{
175603              if( c=='b' ){
175604                c = '\b';
175605              }else if( c=='f' ){
175606                c = '\f';
175607              }else if( c=='n' ){
175608                c = '\n';
175609              }else if( c=='r' ){
175610                c = '\r';
175611              }else if( c=='t' ){
175612                c = '\t';
175613              }
175614              zOut[j++] = c;
175615            }
175616          }
175617        }
175618        zOut[j] = 0;
175619        sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
175620      }
175621      break;
175622    }
175623    case JSON_ARRAY:
175624    case JSON_OBJECT: {
175625      jsonReturnJson(pNode, pCtx, aReplace);
175626      break;
175627    }
175628  }
175629}
175630
175631/* Forward reference */
175632static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
175633
175634/*
175635** A macro to hint to the compiler that a function should not be
175636** inlined.
175637*/
175638#if defined(__GNUC__)
175639#  define JSON_NOINLINE  __attribute__((noinline))
175640#elif defined(_MSC_VER) && _MSC_VER>=1310
175641#  define JSON_NOINLINE  __declspec(noinline)
175642#else
175643#  define JSON_NOINLINE
175644#endif
175645
175646
175647static JSON_NOINLINE int jsonParseAddNodeExpand(
175648  JsonParse *pParse,        /* Append the node to this object */
175649  u32 eType,                /* Node type */
175650  u32 n,                    /* Content size or sub-node count */
175651  const char *zContent      /* Content */
175652){
175653  u32 nNew;
175654  JsonNode *pNew;
175655  assert( pParse->nNode>=pParse->nAlloc );
175656  if( pParse->oom ) return -1;
175657  nNew = pParse->nAlloc*2 + 10;
175658  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
175659  if( pNew==0 ){
175660    pParse->oom = 1;
175661    return -1;
175662  }
175663  pParse->nAlloc = nNew;
175664  pParse->aNode = pNew;
175665  assert( pParse->nNode<pParse->nAlloc );
175666  return jsonParseAddNode(pParse, eType, n, zContent);
175667}
175668
175669/*
175670** Create a new JsonNode instance based on the arguments and append that
175671** instance to the JsonParse.  Return the index in pParse->aNode[] of the
175672** new node, or -1 if a memory allocation fails.
175673*/
175674static int jsonParseAddNode(
175675  JsonParse *pParse,        /* Append the node to this object */
175676  u32 eType,                /* Node type */
175677  u32 n,                    /* Content size or sub-node count */
175678  const char *zContent      /* Content */
175679){
175680  JsonNode *p;
175681  if( pParse->nNode>=pParse->nAlloc ){
175682    return jsonParseAddNodeExpand(pParse, eType, n, zContent);
175683  }
175684  p = &pParse->aNode[pParse->nNode];
175685  p->eType = (u8)eType;
175686  p->jnFlags = 0;
175687  p->iVal = 0;
175688  p->n = n;
175689  p->u.zJContent = zContent;
175690  return pParse->nNode++;
175691}
175692
175693/*
175694** Parse a single JSON value which begins at pParse->zJson[i].  Return the
175695** index of the first character past the end of the value parsed.
175696**
175697** Return negative for a syntax error.  Special cases:  return -2 if the
175698** first non-whitespace character is '}' and return -3 if the first
175699** non-whitespace character is ']'.
175700*/
175701static int jsonParseValue(JsonParse *pParse, u32 i){
175702  char c;
175703  u32 j;
175704  int iThis;
175705  int x;
175706  JsonNode *pNode;
175707  while( safe_isspace(pParse->zJson[i]) ){ i++; }
175708  if( (c = pParse->zJson[i])=='{' ){
175709    /* Parse object */
175710    iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
175711    if( iThis<0 ) return -1;
175712    for(j=i+1;;j++){
175713      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175714      x = jsonParseValue(pParse, j);
175715      if( x<0 ){
175716        if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
175717        return -1;
175718      }
175719      if( pParse->oom ) return -1;
175720      pNode = &pParse->aNode[pParse->nNode-1];
175721      if( pNode->eType!=JSON_STRING ) return -1;
175722      pNode->jnFlags |= JNODE_LABEL;
175723      j = x;
175724      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175725      if( pParse->zJson[j]!=':' ) return -1;
175726      j++;
175727      x = jsonParseValue(pParse, j);
175728      if( x<0 ) return -1;
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 array */
175740    iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
175741    if( iThis<0 ) return -1;
175742    for(j=i+1;;j++){
175743      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175744      x = jsonParseValue(pParse, j);
175745      if( x<0 ){
175746        if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
175747        return -1;
175748      }
175749      j = x;
175750      while( safe_isspace(pParse->zJson[j]) ){ j++; }
175751      c = pParse->zJson[j];
175752      if( c==',' ) continue;
175753      if( c!=']' ) return -1;
175754      break;
175755    }
175756    pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
175757    return j+1;
175758  }else if( c=='"' ){
175759    /* Parse string */
175760    u8 jnFlags = 0;
175761    j = i+1;
175762    for(;;){
175763      c = pParse->zJson[j];
175764      if( c==0 ) return -1;
175765      if( c=='\\' ){
175766        c = pParse->zJson[++j];
175767        if( c==0 ) return -1;
175768        jnFlags = JNODE_ESCAPE;
175769      }else if( c=='"' ){
175770        break;
175771      }
175772      j++;
175773    }
175774    jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
175775    if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
175776    return j+1;
175777  }else if( c=='n'
175778         && strncmp(pParse->zJson+i,"null",4)==0
175779         && !safe_isalnum(pParse->zJson[i+4]) ){
175780    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
175781    return i+4;
175782  }else if( c=='t'
175783         && strncmp(pParse->zJson+i,"true",4)==0
175784         && !safe_isalnum(pParse->zJson[i+4]) ){
175785    jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
175786    return i+4;
175787  }else if( c=='f'
175788         && strncmp(pParse->zJson+i,"false",5)==0
175789         && !safe_isalnum(pParse->zJson[i+5]) ){
175790    jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
175791    return i+5;
175792  }else if( c=='-' || (c>='0' && c<='9') ){
175793    /* Parse number */
175794    u8 seenDP = 0;
175795    u8 seenE = 0;
175796    j = i+1;
175797    for(;; j++){
175798      c = pParse->zJson[j];
175799      if( c>='0' && c<='9' ) continue;
175800      if( c=='.' ){
175801        if( pParse->zJson[j-1]=='-' ) return -1;
175802        if( seenDP ) return -1;
175803        seenDP = 1;
175804        continue;
175805      }
175806      if( c=='e' || c=='E' ){
175807        if( pParse->zJson[j-1]<'0' ) return -1;
175808        if( seenE ) return -1;
175809        seenDP = seenE = 1;
175810        c = pParse->zJson[j+1];
175811        if( c=='+' || c=='-' ){
175812          j++;
175813          c = pParse->zJson[j+1];
175814        }
175815        if( c<'0' || c>'9' ) return -1;
175816        continue;
175817      }
175818      break;
175819    }
175820    if( pParse->zJson[j-1]<'0' ) return -1;
175821    jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
175822                        j - i, &pParse->zJson[i]);
175823    return j;
175824  }else if( c=='}' ){
175825    return -2;  /* End of {...} */
175826  }else if( c==']' ){
175827    return -3;  /* End of [...] */
175828  }else if( c==0 ){
175829    return 0;   /* End of file */
175830  }else{
175831    return -1;  /* Syntax error */
175832  }
175833}
175834
175835/*
175836** Parse a complete JSON string.  Return 0 on success or non-zero if there
175837** are any errors.  If an error occurs, free all memory associated with
175838** pParse.
175839**
175840** pParse is uninitialized when this routine is called.
175841*/
175842static int jsonParse(
175843  JsonParse *pParse,           /* Initialize and fill this JsonParse object */
175844  sqlite3_context *pCtx,       /* Report errors here */
175845  const char *zJson            /* Input JSON text to be parsed */
175846){
175847  int i;
175848  memset(pParse, 0, sizeof(*pParse));
175849  if( zJson==0 ) return 1;
175850  pParse->zJson = zJson;
175851  i = jsonParseValue(pParse, 0);
175852  if( pParse->oom ) i = -1;
175853  if( i>0 ){
175854    while( safe_isspace(zJson[i]) ) i++;
175855    if( zJson[i] ) i = -1;
175856  }
175857  if( i<=0 ){
175858    if( pCtx!=0 ){
175859      if( pParse->oom ){
175860        sqlite3_result_error_nomem(pCtx);
175861      }else{
175862        sqlite3_result_error(pCtx, "malformed JSON", -1);
175863      }
175864    }
175865    jsonParseReset(pParse);
175866    return 1;
175867  }
175868  return 0;
175869}
175870
175871/* Mark node i of pParse as being a child of iParent.  Call recursively
175872** to fill in all the descendants of node i.
175873*/
175874static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
175875  JsonNode *pNode = &pParse->aNode[i];
175876  u32 j;
175877  pParse->aUp[i] = iParent;
175878  switch( pNode->eType ){
175879    case JSON_ARRAY: {
175880      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
175881        jsonParseFillInParentage(pParse, i+j, i);
175882      }
175883      break;
175884    }
175885    case JSON_OBJECT: {
175886      for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
175887        pParse->aUp[i+j] = i;
175888        jsonParseFillInParentage(pParse, i+j+1, i);
175889      }
175890      break;
175891    }
175892    default: {
175893      break;
175894    }
175895  }
175896}
175897
175898/*
175899** Compute the parentage of all nodes in a completed parse.
175900*/
175901static int jsonParseFindParents(JsonParse *pParse){
175902  u32 *aUp;
175903  assert( pParse->aUp==0 );
175904  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
175905  if( aUp==0 ){
175906    pParse->oom = 1;
175907    return SQLITE_NOMEM;
175908  }
175909  jsonParseFillInParentage(pParse, 0, 0);
175910  return SQLITE_OK;
175911}
175912
175913/*
175914** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
175915** a match.
175916*/
175917static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
175918  if( pNode->jnFlags & JNODE_RAW ){
175919    if( pNode->n!=nKey ) return 0;
175920    return strncmp(pNode->u.zJContent, zKey, nKey)==0;
175921  }else{
175922    if( pNode->n!=nKey+2 ) return 0;
175923    return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
175924  }
175925}
175926
175927/* forward declaration */
175928static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
175929
175930/*
175931** Search along zPath to find the node specified.  Return a pointer
175932** to that node, or NULL if zPath is malformed or if there is no such
175933** node.
175934**
175935** If pApnd!=0, then try to append new nodes to complete zPath if it is
175936** possible to do so and if no existing node corresponds to zPath.  If
175937** new nodes are appended *pApnd is set to 1.
175938*/
175939static JsonNode *jsonLookupStep(
175940  JsonParse *pParse,      /* The JSON to search */
175941  u32 iRoot,              /* Begin the search at this node */
175942  const char *zPath,      /* The path to search */
175943  int *pApnd,             /* Append nodes to complete path if not NULL */
175944  const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
175945){
175946  u32 i, j, nKey;
175947  const char *zKey;
175948  JsonNode *pRoot = &pParse->aNode[iRoot];
175949  if( zPath[0]==0 ) return pRoot;
175950  if( zPath[0]=='.' ){
175951    if( pRoot->eType!=JSON_OBJECT ) return 0;
175952    zPath++;
175953    if( zPath[0]=='"' ){
175954      zKey = zPath + 1;
175955      for(i=1; zPath[i] && zPath[i]!='"'; i++){}
175956      nKey = i-1;
175957      if( zPath[i] ){
175958        i++;
175959      }else{
175960        *pzErr = zPath;
175961        return 0;
175962      }
175963    }else{
175964      zKey = zPath;
175965      for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
175966      nKey = i;
175967    }
175968    if( nKey==0 ){
175969      *pzErr = zPath;
175970      return 0;
175971    }
175972    j = 1;
175973    for(;;){
175974      while( j<=pRoot->n ){
175975        if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
175976          return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
175977        }
175978        j++;
175979        j += jsonNodeSize(&pRoot[j]);
175980      }
175981      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
175982      iRoot += pRoot->u.iAppend;
175983      pRoot = &pParse->aNode[iRoot];
175984      j = 1;
175985    }
175986    if( pApnd ){
175987      u32 iStart, iLabel;
175988      JsonNode *pNode;
175989      iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
175990      iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
175991      zPath += i;
175992      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
175993      if( pParse->oom ) return 0;
175994      if( pNode ){
175995        pRoot = &pParse->aNode[iRoot];
175996        pRoot->u.iAppend = iStart - iRoot;
175997        pRoot->jnFlags |= JNODE_APPEND;
175998        pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
175999      }
176000      return pNode;
176001    }
176002  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
176003    if( pRoot->eType!=JSON_ARRAY ) return 0;
176004    i = 0;
176005    j = 1;
176006    while( safe_isdigit(zPath[j]) ){
176007      i = i*10 + zPath[j] - '0';
176008      j++;
176009    }
176010    if( zPath[j]!=']' ){
176011      *pzErr = zPath;
176012      return 0;
176013    }
176014    zPath += j + 1;
176015    j = 1;
176016    for(;;){
176017      while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
176018        if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
176019        j += jsonNodeSize(&pRoot[j]);
176020      }
176021      if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
176022      iRoot += pRoot->u.iAppend;
176023      pRoot = &pParse->aNode[iRoot];
176024      j = 1;
176025    }
176026    if( j<=pRoot->n ){
176027      return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
176028    }
176029    if( i==0 && pApnd ){
176030      u32 iStart;
176031      JsonNode *pNode;
176032      iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
176033      pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
176034      if( pParse->oom ) return 0;
176035      if( pNode ){
176036        pRoot = &pParse->aNode[iRoot];
176037        pRoot->u.iAppend = iStart - iRoot;
176038        pRoot->jnFlags |= JNODE_APPEND;
176039      }
176040      return pNode;
176041    }
176042  }else{
176043    *pzErr = zPath;
176044  }
176045  return 0;
176046}
176047
176048/*
176049** Append content to pParse that will complete zPath.  Return a pointer
176050** to the inserted node, or return NULL if the append fails.
176051*/
176052static JsonNode *jsonLookupAppend(
176053  JsonParse *pParse,     /* Append content to the JSON parse */
176054  const char *zPath,     /* Description of content to append */
176055  int *pApnd,            /* Set this flag to 1 */
176056  const char **pzErr     /* Make this point to any syntax error */
176057){
176058  *pApnd = 1;
176059  if( zPath[0]==0 ){
176060    jsonParseAddNode(pParse, JSON_NULL, 0, 0);
176061    return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
176062  }
176063  if( zPath[0]=='.' ){
176064    jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
176065  }else if( strncmp(zPath,"[0]",3)==0 ){
176066    jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
176067  }else{
176068    return 0;
176069  }
176070  if( pParse->oom ) return 0;
176071  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
176072}
176073
176074/*
176075** Return the text of a syntax error message on a JSON path.  Space is
176076** obtained from sqlite3_malloc().
176077*/
176078static char *jsonPathSyntaxError(const char *zErr){
176079  return sqlite3_mprintf("JSON path error near '%q'", zErr);
176080}
176081
176082/*
176083** Do a node lookup using zPath.  Return a pointer to the node on success.
176084** Return NULL if not found or if there is an error.
176085**
176086** On an error, write an error message into pCtx and increment the
176087** pParse->nErr counter.
176088**
176089** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
176090** nodes are appended.
176091*/
176092static JsonNode *jsonLookup(
176093  JsonParse *pParse,      /* The JSON to search */
176094  const char *zPath,      /* The path to search */
176095  int *pApnd,             /* Append nodes to complete path if not NULL */
176096  sqlite3_context *pCtx   /* Report errors here, if not NULL */
176097){
176098  const char *zErr = 0;
176099  JsonNode *pNode = 0;
176100  char *zMsg;
176101
176102  if( zPath==0 ) return 0;
176103  if( zPath[0]!='$' ){
176104    zErr = zPath;
176105    goto lookup_err;
176106  }
176107  zPath++;
176108  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
176109  if( zErr==0 ) return pNode;
176110
176111lookup_err:
176112  pParse->nErr++;
176113  assert( zErr!=0 && pCtx!=0 );
176114  zMsg = jsonPathSyntaxError(zErr);
176115  if( zMsg ){
176116    sqlite3_result_error(pCtx, zMsg, -1);
176117    sqlite3_free(zMsg);
176118  }else{
176119    sqlite3_result_error_nomem(pCtx);
176120  }
176121  return 0;
176122}
176123
176124
176125/*
176126** Report the wrong number of arguments for json_insert(), json_replace()
176127** or json_set().
176128*/
176129static void jsonWrongNumArgs(
176130  sqlite3_context *pCtx,
176131  const char *zFuncName
176132){
176133  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
176134                               zFuncName);
176135  sqlite3_result_error(pCtx, zMsg, -1);
176136  sqlite3_free(zMsg);
176137}
176138
176139
176140/****************************************************************************
176141** SQL functions used for testing and debugging
176142****************************************************************************/
176143
176144#ifdef SQLITE_DEBUG
176145/*
176146** The json_parse(JSON) function returns a string which describes
176147** a parse of the JSON provided.  Or it returns NULL if JSON is not
176148** well-formed.
176149*/
176150static void jsonParseFunc(
176151  sqlite3_context *ctx,
176152  int argc,
176153  sqlite3_value **argv
176154){
176155  JsonString s;       /* Output string - not real JSON */
176156  JsonParse x;        /* The parse */
176157  u32 i;
176158
176159  assert( argc==1 );
176160  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176161  jsonParseFindParents(&x);
176162  jsonInit(&s, ctx);
176163  for(i=0; i<x.nNode; i++){
176164    const char *zType;
176165    if( x.aNode[i].jnFlags & JNODE_LABEL ){
176166      assert( x.aNode[i].eType==JSON_STRING );
176167      zType = "label";
176168    }else{
176169      zType = jsonType[x.aNode[i].eType];
176170    }
176171    jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
176172               i, zType, x.aNode[i].n, x.aUp[i]);
176173    if( x.aNode[i].u.zJContent!=0 ){
176174      jsonAppendRaw(&s, " ", 1);
176175      jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
176176    }
176177    jsonAppendRaw(&s, "\n", 1);
176178  }
176179  jsonParseReset(&x);
176180  jsonResult(&s);
176181}
176182
176183/*
176184** The json_test1(JSON) function return true (1) if the input is JSON
176185** text generated by another json function.  It returns (0) if the input
176186** is not known to be JSON.
176187*/
176188static void jsonTest1Func(
176189  sqlite3_context *ctx,
176190  int argc,
176191  sqlite3_value **argv
176192){
176193  UNUSED_PARAM(argc);
176194  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
176195}
176196#endif /* SQLITE_DEBUG */
176197
176198/****************************************************************************
176199** Scalar SQL function implementations
176200****************************************************************************/
176201
176202/*
176203** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
176204** corresponding to the SQL value input.  Mostly this means putting
176205** double-quotes around strings and returning the unquoted string "null"
176206** when given a NULL input.
176207*/
176208static void jsonQuoteFunc(
176209  sqlite3_context *ctx,
176210  int argc,
176211  sqlite3_value **argv
176212){
176213  JsonString jx;
176214  UNUSED_PARAM(argc);
176215
176216  jsonInit(&jx, ctx);
176217  jsonAppendValue(&jx, argv[0]);
176218  jsonResult(&jx);
176219  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176220}
176221
176222/*
176223** Implementation of the json_array(VALUE,...) function.  Return a JSON
176224** array that contains all values given in arguments.  Or if any argument
176225** is a BLOB, throw an error.
176226*/
176227static void jsonArrayFunc(
176228  sqlite3_context *ctx,
176229  int argc,
176230  sqlite3_value **argv
176231){
176232  int i;
176233  JsonString jx;
176234
176235  jsonInit(&jx, ctx);
176236  jsonAppendChar(&jx, '[');
176237  for(i=0; i<argc; i++){
176238    jsonAppendSeparator(&jx);
176239    jsonAppendValue(&jx, argv[i]);
176240  }
176241  jsonAppendChar(&jx, ']');
176242  jsonResult(&jx);
176243  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176244}
176245
176246
176247/*
176248** json_array_length(JSON)
176249** json_array_length(JSON, PATH)
176250**
176251** Return the number of elements in the top-level JSON array.
176252** Return 0 if the input is not a well-formed JSON array.
176253*/
176254static void jsonArrayLengthFunc(
176255  sqlite3_context *ctx,
176256  int argc,
176257  sqlite3_value **argv
176258){
176259  JsonParse x;          /* The parse */
176260  sqlite3_int64 n = 0;
176261  u32 i;
176262  JsonNode *pNode;
176263
176264  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176265  assert( x.nNode );
176266  if( argc==2 ){
176267    const char *zPath = (const char*)sqlite3_value_text(argv[1]);
176268    pNode = jsonLookup(&x, zPath, 0, ctx);
176269  }else{
176270    pNode = x.aNode;
176271  }
176272  if( pNode==0 ){
176273    x.nErr = 1;
176274  }else if( pNode->eType==JSON_ARRAY ){
176275    assert( (pNode->jnFlags & JNODE_APPEND)==0 );
176276    for(i=1; i<=pNode->n; n++){
176277      i += jsonNodeSize(&pNode[i]);
176278    }
176279  }
176280  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
176281  jsonParseReset(&x);
176282}
176283
176284/*
176285** json_extract(JSON, PATH, ...)
176286**
176287** Return the element described by PATH.  Return NULL if there is no
176288** PATH element.  If there are multiple PATHs, then return a JSON array
176289** with the result from each path.  Throw an error if the JSON or any PATH
176290** is malformed.
176291*/
176292static void jsonExtractFunc(
176293  sqlite3_context *ctx,
176294  int argc,
176295  sqlite3_value **argv
176296){
176297  JsonParse x;          /* The parse */
176298  JsonNode *pNode;
176299  const char *zPath;
176300  JsonString jx;
176301  int i;
176302
176303  if( argc<2 ) return;
176304  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176305  jsonInit(&jx, ctx);
176306  jsonAppendChar(&jx, '[');
176307  for(i=1; i<argc; i++){
176308    zPath = (const char*)sqlite3_value_text(argv[i]);
176309    pNode = jsonLookup(&x, zPath, 0, ctx);
176310    if( x.nErr ) break;
176311    if( argc>2 ){
176312      jsonAppendSeparator(&jx);
176313      if( pNode ){
176314        jsonRenderNode(pNode, &jx, 0);
176315      }else{
176316        jsonAppendRaw(&jx, "null", 4);
176317      }
176318    }else if( pNode ){
176319      jsonReturn(pNode, ctx, 0);
176320    }
176321  }
176322  if( argc>2 && i==argc ){
176323    jsonAppendChar(&jx, ']');
176324    jsonResult(&jx);
176325    sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176326  }
176327  jsonReset(&jx);
176328  jsonParseReset(&x);
176329}
176330
176331/*
176332** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
176333** object that contains all name/value given in arguments.  Or if any name
176334** is not a string or if any value is a BLOB, throw an error.
176335*/
176336static void jsonObjectFunc(
176337  sqlite3_context *ctx,
176338  int argc,
176339  sqlite3_value **argv
176340){
176341  int i;
176342  JsonString jx;
176343  const char *z;
176344  u32 n;
176345
176346  if( argc&1 ){
176347    sqlite3_result_error(ctx, "json_object() requires an even number "
176348                                  "of arguments", -1);
176349    return;
176350  }
176351  jsonInit(&jx, ctx);
176352  jsonAppendChar(&jx, '{');
176353  for(i=0; i<argc; i+=2){
176354    if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
176355      sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
176356      jsonReset(&jx);
176357      return;
176358    }
176359    jsonAppendSeparator(&jx);
176360    z = (const char*)sqlite3_value_text(argv[i]);
176361    n = (u32)sqlite3_value_bytes(argv[i]);
176362    jsonAppendString(&jx, z, n);
176363    jsonAppendChar(&jx, ':');
176364    jsonAppendValue(&jx, argv[i+1]);
176365  }
176366  jsonAppendChar(&jx, '}');
176367  jsonResult(&jx);
176368  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176369}
176370
176371
176372/*
176373** json_remove(JSON, PATH, ...)
176374**
176375** Remove the named elements from JSON and return the result.  malformed
176376** JSON or PATH arguments result in an error.
176377*/
176378static void jsonRemoveFunc(
176379  sqlite3_context *ctx,
176380  int argc,
176381  sqlite3_value **argv
176382){
176383  JsonParse x;          /* The parse */
176384  JsonNode *pNode;
176385  const char *zPath;
176386  u32 i;
176387
176388  if( argc<1 ) return;
176389  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176390  assert( x.nNode );
176391  for(i=1; i<(u32)argc; i++){
176392    zPath = (const char*)sqlite3_value_text(argv[i]);
176393    if( zPath==0 ) goto remove_done;
176394    pNode = jsonLookup(&x, zPath, 0, ctx);
176395    if( x.nErr ) goto remove_done;
176396    if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
176397  }
176398  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
176399    jsonReturnJson(x.aNode, ctx, 0);
176400  }
176401remove_done:
176402  jsonParseReset(&x);
176403}
176404
176405/*
176406** json_replace(JSON, PATH, VALUE, ...)
176407**
176408** Replace the value at PATH with VALUE.  If PATH does not already exist,
176409** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
176410*/
176411static void jsonReplaceFunc(
176412  sqlite3_context *ctx,
176413  int argc,
176414  sqlite3_value **argv
176415){
176416  JsonParse x;          /* The parse */
176417  JsonNode *pNode;
176418  const char *zPath;
176419  u32 i;
176420
176421  if( argc<1 ) return;
176422  if( (argc&1)==0 ) {
176423    jsonWrongNumArgs(ctx, "replace");
176424    return;
176425  }
176426  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176427  assert( x.nNode );
176428  for(i=1; i<(u32)argc; i+=2){
176429    zPath = (const char*)sqlite3_value_text(argv[i]);
176430    pNode = jsonLookup(&x, zPath, 0, ctx);
176431    if( x.nErr ) goto replace_err;
176432    if( pNode ){
176433      pNode->jnFlags |= (u8)JNODE_REPLACE;
176434      pNode->iVal = (u8)(i+1);
176435    }
176436  }
176437  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
176438    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
176439  }else{
176440    jsonReturnJson(x.aNode, ctx, argv);
176441  }
176442replace_err:
176443  jsonParseReset(&x);
176444}
176445
176446/*
176447** json_set(JSON, PATH, VALUE, ...)
176448**
176449** Set the value at PATH to VALUE.  Create the PATH if it does not already
176450** exist.  Overwrite existing values that do exist.
176451** If JSON or PATH is malformed, throw an error.
176452**
176453** json_insert(JSON, PATH, VALUE, ...)
176454**
176455** Create PATH and initialize it to VALUE.  If PATH already exists, this
176456** routine is a no-op.  If JSON or PATH is malformed, throw an error.
176457*/
176458static void jsonSetFunc(
176459  sqlite3_context *ctx,
176460  int argc,
176461  sqlite3_value **argv
176462){
176463  JsonParse x;          /* The parse */
176464  JsonNode *pNode;
176465  const char *zPath;
176466  u32 i;
176467  int bApnd;
176468  int bIsSet = *(int*)sqlite3_user_data(ctx);
176469
176470  if( argc<1 ) return;
176471  if( (argc&1)==0 ) {
176472    jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
176473    return;
176474  }
176475  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176476  assert( x.nNode );
176477  for(i=1; i<(u32)argc; i+=2){
176478    zPath = (const char*)sqlite3_value_text(argv[i]);
176479    bApnd = 0;
176480    pNode = jsonLookup(&x, zPath, &bApnd, ctx);
176481    if( x.oom ){
176482      sqlite3_result_error_nomem(ctx);
176483      goto jsonSetDone;
176484    }else if( x.nErr ){
176485      goto jsonSetDone;
176486    }else if( pNode && (bApnd || bIsSet) ){
176487      pNode->jnFlags |= (u8)JNODE_REPLACE;
176488      pNode->iVal = (u8)(i+1);
176489    }
176490  }
176491  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
176492    sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
176493  }else{
176494    jsonReturnJson(x.aNode, ctx, argv);
176495  }
176496jsonSetDone:
176497  jsonParseReset(&x);
176498}
176499
176500/*
176501** json_type(JSON)
176502** json_type(JSON, PATH)
176503**
176504** Return the top-level "type" of a JSON string.  Throw an error if
176505** either the JSON or PATH inputs are not well-formed.
176506*/
176507static void jsonTypeFunc(
176508  sqlite3_context *ctx,
176509  int argc,
176510  sqlite3_value **argv
176511){
176512  JsonParse x;          /* The parse */
176513  const char *zPath;
176514  JsonNode *pNode;
176515
176516  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176517  assert( x.nNode );
176518  if( argc==2 ){
176519    zPath = (const char*)sqlite3_value_text(argv[1]);
176520    pNode = jsonLookup(&x, zPath, 0, ctx);
176521  }else{
176522    pNode = x.aNode;
176523  }
176524  if( pNode ){
176525    sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
176526  }
176527  jsonParseReset(&x);
176528}
176529
176530/*
176531** json_valid(JSON)
176532**
176533** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
176534** Return 0 otherwise.
176535*/
176536static void jsonValidFunc(
176537  sqlite3_context *ctx,
176538  int argc,
176539  sqlite3_value **argv
176540){
176541  JsonParse x;          /* The parse */
176542  int rc = 0;
176543
176544  UNUSED_PARAM(argc);
176545  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
176546    rc = 1;
176547  }
176548  jsonParseReset(&x);
176549  sqlite3_result_int(ctx, rc);
176550}
176551
176552
176553/****************************************************************************
176554** Aggregate SQL function implementations
176555****************************************************************************/
176556/*
176557** json_group_array(VALUE)
176558**
176559** Return a JSON array composed of all values in the aggregate.
176560*/
176561static void jsonArrayStep(
176562  sqlite3_context *ctx,
176563  int argc,
176564  sqlite3_value **argv
176565){
176566  JsonString *pStr;
176567  UNUSED_PARAM(argc);
176568  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
176569  if( pStr ){
176570    if( pStr->zBuf==0 ){
176571      jsonInit(pStr, ctx);
176572      jsonAppendChar(pStr, '[');
176573    }else{
176574      jsonAppendChar(pStr, ',');
176575      pStr->pCtx = ctx;
176576    }
176577    jsonAppendValue(pStr, argv[0]);
176578  }
176579}
176580static void jsonArrayFinal(sqlite3_context *ctx){
176581  JsonString *pStr;
176582  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
176583  if( pStr ){
176584    pStr->pCtx = ctx;
176585    jsonAppendChar(pStr, ']');
176586    if( pStr->bErr ){
176587      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
176588      assert( pStr->bStatic );
176589    }else{
176590      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
176591                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
176592      pStr->bStatic = 1;
176593    }
176594  }else{
176595    sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
176596  }
176597  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176598}
176599
176600/*
176601** json_group_obj(NAME,VALUE)
176602**
176603** Return a JSON object composed of all names and values in the aggregate.
176604*/
176605static void jsonObjectStep(
176606  sqlite3_context *ctx,
176607  int argc,
176608  sqlite3_value **argv
176609){
176610  JsonString *pStr;
176611  const char *z;
176612  u32 n;
176613  UNUSED_PARAM(argc);
176614  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
176615  if( pStr ){
176616    if( pStr->zBuf==0 ){
176617      jsonInit(pStr, ctx);
176618      jsonAppendChar(pStr, '{');
176619    }else{
176620      jsonAppendChar(pStr, ',');
176621      pStr->pCtx = ctx;
176622    }
176623    z = (const char*)sqlite3_value_text(argv[0]);
176624    n = (u32)sqlite3_value_bytes(argv[0]);
176625    jsonAppendString(pStr, z, n);
176626    jsonAppendChar(pStr, ':');
176627    jsonAppendValue(pStr, argv[1]);
176628  }
176629}
176630static void jsonObjectFinal(sqlite3_context *ctx){
176631  JsonString *pStr;
176632  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
176633  if( pStr ){
176634    jsonAppendChar(pStr, '}');
176635    if( pStr->bErr ){
176636      if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
176637      assert( pStr->bStatic );
176638    }else{
176639      sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
176640                          pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
176641      pStr->bStatic = 1;
176642    }
176643  }else{
176644    sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
176645  }
176646  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176647}
176648
176649
176650#ifndef SQLITE_OMIT_VIRTUALTABLE
176651/****************************************************************************
176652** The json_each virtual table
176653****************************************************************************/
176654typedef struct JsonEachCursor JsonEachCursor;
176655struct JsonEachCursor {
176656  sqlite3_vtab_cursor base;  /* Base class - must be first */
176657  u32 iRowid;                /* The rowid */
176658  u32 iBegin;                /* The first node of the scan */
176659  u32 i;                     /* Index in sParse.aNode[] of current row */
176660  u32 iEnd;                  /* EOF when i equals or exceeds this value */
176661  u8 eType;                  /* Type of top-level element */
176662  u8 bRecursive;             /* True for json_tree().  False for json_each() */
176663  char *zJson;               /* Input JSON */
176664  char *zRoot;               /* Path by which to filter zJson */
176665  JsonParse sParse;          /* Parse of the input JSON */
176666};
176667
176668/* Constructor for the json_each virtual table */
176669static int jsonEachConnect(
176670  sqlite3 *db,
176671  void *pAux,
176672  int argc, const char *const*argv,
176673  sqlite3_vtab **ppVtab,
176674  char **pzErr
176675){
176676  sqlite3_vtab *pNew;
176677  int rc;
176678
176679/* Column numbers */
176680#define JEACH_KEY     0
176681#define JEACH_VALUE   1
176682#define JEACH_TYPE    2
176683#define JEACH_ATOM    3
176684#define JEACH_ID      4
176685#define JEACH_PARENT  5
176686#define JEACH_FULLKEY 6
176687#define JEACH_PATH    7
176688#define JEACH_JSON    8
176689#define JEACH_ROOT    9
176690
176691  UNUSED_PARAM(pzErr);
176692  UNUSED_PARAM(argv);
176693  UNUSED_PARAM(argc);
176694  UNUSED_PARAM(pAux);
176695  rc = sqlite3_declare_vtab(db,
176696     "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
176697                    "json HIDDEN,root HIDDEN)");
176698  if( rc==SQLITE_OK ){
176699    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
176700    if( pNew==0 ) return SQLITE_NOMEM;
176701    memset(pNew, 0, sizeof(*pNew));
176702  }
176703  return rc;
176704}
176705
176706/* destructor for json_each virtual table */
176707static int jsonEachDisconnect(sqlite3_vtab *pVtab){
176708  sqlite3_free(pVtab);
176709  return SQLITE_OK;
176710}
176711
176712/* constructor for a JsonEachCursor object for json_each(). */
176713static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
176714  JsonEachCursor *pCur;
176715
176716  UNUSED_PARAM(p);
176717  pCur = sqlite3_malloc( sizeof(*pCur) );
176718  if( pCur==0 ) return SQLITE_NOMEM;
176719  memset(pCur, 0, sizeof(*pCur));
176720  *ppCursor = &pCur->base;
176721  return SQLITE_OK;
176722}
176723
176724/* constructor for a JsonEachCursor object for json_tree(). */
176725static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
176726  int rc = jsonEachOpenEach(p, ppCursor);
176727  if( rc==SQLITE_OK ){
176728    JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
176729    pCur->bRecursive = 1;
176730  }
176731  return rc;
176732}
176733
176734/* Reset a JsonEachCursor back to its original state.  Free any memory
176735** held. */
176736static void jsonEachCursorReset(JsonEachCursor *p){
176737  sqlite3_free(p->zJson);
176738  sqlite3_free(p->zRoot);
176739  jsonParseReset(&p->sParse);
176740  p->iRowid = 0;
176741  p->i = 0;
176742  p->iEnd = 0;
176743  p->eType = 0;
176744  p->zJson = 0;
176745  p->zRoot = 0;
176746}
176747
176748/* Destructor for a jsonEachCursor object */
176749static int jsonEachClose(sqlite3_vtab_cursor *cur){
176750  JsonEachCursor *p = (JsonEachCursor*)cur;
176751  jsonEachCursorReset(p);
176752  sqlite3_free(cur);
176753  return SQLITE_OK;
176754}
176755
176756/* Return TRUE if the jsonEachCursor object has been advanced off the end
176757** of the JSON object */
176758static int jsonEachEof(sqlite3_vtab_cursor *cur){
176759  JsonEachCursor *p = (JsonEachCursor*)cur;
176760  return p->i >= p->iEnd;
176761}
176762
176763/* Advance the cursor to the next element for json_tree() */
176764static int jsonEachNext(sqlite3_vtab_cursor *cur){
176765  JsonEachCursor *p = (JsonEachCursor*)cur;
176766  if( p->bRecursive ){
176767    if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
176768    p->i++;
176769    p->iRowid++;
176770    if( p->i<p->iEnd ){
176771      u32 iUp = p->sParse.aUp[p->i];
176772      JsonNode *pUp = &p->sParse.aNode[iUp];
176773      p->eType = pUp->eType;
176774      if( pUp->eType==JSON_ARRAY ){
176775        if( iUp==p->i-1 ){
176776          pUp->u.iKey = 0;
176777        }else{
176778          pUp->u.iKey++;
176779        }
176780      }
176781    }
176782  }else{
176783    switch( p->eType ){
176784      case JSON_ARRAY: {
176785        p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
176786        p->iRowid++;
176787        break;
176788      }
176789      case JSON_OBJECT: {
176790        p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
176791        p->iRowid++;
176792        break;
176793      }
176794      default: {
176795        p->i = p->iEnd;
176796        break;
176797      }
176798    }
176799  }
176800  return SQLITE_OK;
176801}
176802
176803/* Append the name of the path for element i to pStr
176804*/
176805static void jsonEachComputePath(
176806  JsonEachCursor *p,       /* The cursor */
176807  JsonString *pStr,        /* Write the path here */
176808  u32 i                    /* Path to this element */
176809){
176810  JsonNode *pNode, *pUp;
176811  u32 iUp;
176812  if( i==0 ){
176813    jsonAppendChar(pStr, '$');
176814    return;
176815  }
176816  iUp = p->sParse.aUp[i];
176817  jsonEachComputePath(p, pStr, iUp);
176818  pNode = &p->sParse.aNode[i];
176819  pUp = &p->sParse.aNode[iUp];
176820  if( pUp->eType==JSON_ARRAY ){
176821    jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
176822  }else{
176823    assert( pUp->eType==JSON_OBJECT );
176824    if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
176825    assert( pNode->eType==JSON_STRING );
176826    assert( pNode->jnFlags & JNODE_LABEL );
176827    jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
176828  }
176829}
176830
176831/* Return the value of a column */
176832static int jsonEachColumn(
176833  sqlite3_vtab_cursor *cur,   /* The cursor */
176834  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
176835  int i                       /* Which column to return */
176836){
176837  JsonEachCursor *p = (JsonEachCursor*)cur;
176838  JsonNode *pThis = &p->sParse.aNode[p->i];
176839  switch( i ){
176840    case JEACH_KEY: {
176841      if( p->i==0 ) break;
176842      if( p->eType==JSON_OBJECT ){
176843        jsonReturn(pThis, ctx, 0);
176844      }else if( p->eType==JSON_ARRAY ){
176845        u32 iKey;
176846        if( p->bRecursive ){
176847          if( p->iRowid==0 ) break;
176848          iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
176849        }else{
176850          iKey = p->iRowid;
176851        }
176852        sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
176853      }
176854      break;
176855    }
176856    case JEACH_VALUE: {
176857      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176858      jsonReturn(pThis, ctx, 0);
176859      break;
176860    }
176861    case JEACH_TYPE: {
176862      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176863      sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
176864      break;
176865    }
176866    case JEACH_ATOM: {
176867      if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176868      if( pThis->eType>=JSON_ARRAY ) break;
176869      jsonReturn(pThis, ctx, 0);
176870      break;
176871    }
176872    case JEACH_ID: {
176873      sqlite3_result_int64(ctx,
176874         (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
176875      break;
176876    }
176877    case JEACH_PARENT: {
176878      if( p->i>p->iBegin && p->bRecursive ){
176879        sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
176880      }
176881      break;
176882    }
176883    case JEACH_FULLKEY: {
176884      JsonString x;
176885      jsonInit(&x, ctx);
176886      if( p->bRecursive ){
176887        jsonEachComputePath(p, &x, p->i);
176888      }else{
176889        if( p->zRoot ){
176890          jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
176891        }else{
176892          jsonAppendChar(&x, '$');
176893        }
176894        if( p->eType==JSON_ARRAY ){
176895          jsonPrintf(30, &x, "[%d]", p->iRowid);
176896        }else{
176897          jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
176898        }
176899      }
176900      jsonResult(&x);
176901      break;
176902    }
176903    case JEACH_PATH: {
176904      if( p->bRecursive ){
176905        JsonString x;
176906        jsonInit(&x, ctx);
176907        jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
176908        jsonResult(&x);
176909        break;
176910      }
176911      /* For json_each() path and root are the same so fall through
176912      ** into the root case */
176913    }
176914    case JEACH_ROOT: {
176915      const char *zRoot = p->zRoot;
176916       if( zRoot==0 ) zRoot = "$";
176917      sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
176918      break;
176919    }
176920    case JEACH_JSON: {
176921      assert( i==JEACH_JSON );
176922      sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
176923      break;
176924    }
176925  }
176926  return SQLITE_OK;
176927}
176928
176929/* Return the current rowid value */
176930static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
176931  JsonEachCursor *p = (JsonEachCursor*)cur;
176932  *pRowid = p->iRowid;
176933  return SQLITE_OK;
176934}
176935
176936/* The query strategy is to look for an equality constraint on the json
176937** column.  Without such a constraint, the table cannot operate.  idxNum is
176938** 1 if the constraint is found, 3 if the constraint and zRoot are found,
176939** and 0 otherwise.
176940*/
176941static int jsonEachBestIndex(
176942  sqlite3_vtab *tab,
176943  sqlite3_index_info *pIdxInfo
176944){
176945  int i;
176946  int jsonIdx = -1;
176947  int rootIdx = -1;
176948  const struct sqlite3_index_constraint *pConstraint;
176949
176950  UNUSED_PARAM(tab);
176951  pConstraint = pIdxInfo->aConstraint;
176952  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
176953    if( pConstraint->usable==0 ) continue;
176954    if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
176955    switch( pConstraint->iColumn ){
176956      case JEACH_JSON:   jsonIdx = i;    break;
176957      case JEACH_ROOT:   rootIdx = i;    break;
176958      default:           /* no-op */     break;
176959    }
176960  }
176961  if( jsonIdx<0 ){
176962    pIdxInfo->idxNum = 0;
176963    pIdxInfo->estimatedCost = 1e99;
176964  }else{
176965    pIdxInfo->estimatedCost = 1.0;
176966    pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
176967    pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
176968    if( rootIdx<0 ){
176969      pIdxInfo->idxNum = 1;
176970    }else{
176971      pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
176972      pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
176973      pIdxInfo->idxNum = 3;
176974    }
176975  }
176976  return SQLITE_OK;
176977}
176978
176979/* Start a search on a new JSON string */
176980static int jsonEachFilter(
176981  sqlite3_vtab_cursor *cur,
176982  int idxNum, const char *idxStr,
176983  int argc, sqlite3_value **argv
176984){
176985  JsonEachCursor *p = (JsonEachCursor*)cur;
176986  const char *z;
176987  const char *zRoot = 0;
176988  sqlite3_int64 n;
176989
176990  UNUSED_PARAM(idxStr);
176991  UNUSED_PARAM(argc);
176992  jsonEachCursorReset(p);
176993  if( idxNum==0 ) return SQLITE_OK;
176994  z = (const char*)sqlite3_value_text(argv[0]);
176995  if( z==0 ) return SQLITE_OK;
176996  n = sqlite3_value_bytes(argv[0]);
176997  p->zJson = sqlite3_malloc64( n+1 );
176998  if( p->zJson==0 ) return SQLITE_NOMEM;
176999  memcpy(p->zJson, z, (size_t)n+1);
177000  if( jsonParse(&p->sParse, 0, p->zJson) ){
177001    int rc = SQLITE_NOMEM;
177002    if( p->sParse.oom==0 ){
177003      sqlite3_free(cur->pVtab->zErrMsg);
177004      cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
177005      if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
177006    }
177007    jsonEachCursorReset(p);
177008    return rc;
177009  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
177010    jsonEachCursorReset(p);
177011    return SQLITE_NOMEM;
177012  }else{
177013    JsonNode *pNode = 0;
177014    if( idxNum==3 ){
177015      const char *zErr = 0;
177016      zRoot = (const char*)sqlite3_value_text(argv[1]);
177017      if( zRoot==0 ) return SQLITE_OK;
177018      n = sqlite3_value_bytes(argv[1]);
177019      p->zRoot = sqlite3_malloc64( n+1 );
177020      if( p->zRoot==0 ) return SQLITE_NOMEM;
177021      memcpy(p->zRoot, zRoot, (size_t)n+1);
177022      if( zRoot[0]!='$' ){
177023        zErr = zRoot;
177024      }else{
177025        pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
177026      }
177027      if( zErr ){
177028        sqlite3_free(cur->pVtab->zErrMsg);
177029        cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
177030        jsonEachCursorReset(p);
177031        return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
177032      }else if( pNode==0 ){
177033        return SQLITE_OK;
177034      }
177035    }else{
177036      pNode = p->sParse.aNode;
177037    }
177038    p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
177039    p->eType = pNode->eType;
177040    if( p->eType>=JSON_ARRAY ){
177041      pNode->u.iKey = 0;
177042      p->iEnd = p->i + pNode->n + 1;
177043      if( p->bRecursive ){
177044        p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
177045        if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
177046          p->i--;
177047        }
177048      }else{
177049        p->i++;
177050      }
177051    }else{
177052      p->iEnd = p->i+1;
177053    }
177054  }
177055  return SQLITE_OK;
177056}
177057
177058/* The methods of the json_each virtual table */
177059static sqlite3_module jsonEachModule = {
177060  0,                         /* iVersion */
177061  0,                         /* xCreate */
177062  jsonEachConnect,           /* xConnect */
177063  jsonEachBestIndex,         /* xBestIndex */
177064  jsonEachDisconnect,        /* xDisconnect */
177065  0,                         /* xDestroy */
177066  jsonEachOpenEach,          /* xOpen - open a cursor */
177067  jsonEachClose,             /* xClose - close a cursor */
177068  jsonEachFilter,            /* xFilter - configure scan constraints */
177069  jsonEachNext,              /* xNext - advance a cursor */
177070  jsonEachEof,               /* xEof - check for end of scan */
177071  jsonEachColumn,            /* xColumn - read data */
177072  jsonEachRowid,             /* xRowid - read data */
177073  0,                         /* xUpdate */
177074  0,                         /* xBegin */
177075  0,                         /* xSync */
177076  0,                         /* xCommit */
177077  0,                         /* xRollback */
177078  0,                         /* xFindMethod */
177079  0,                         /* xRename */
177080  0,                         /* xSavepoint */
177081  0,                         /* xRelease */
177082  0                          /* xRollbackTo */
177083};
177084
177085/* The methods of the json_tree virtual table. */
177086static sqlite3_module jsonTreeModule = {
177087  0,                         /* iVersion */
177088  0,                         /* xCreate */
177089  jsonEachConnect,           /* xConnect */
177090  jsonEachBestIndex,         /* xBestIndex */
177091  jsonEachDisconnect,        /* xDisconnect */
177092  0,                         /* xDestroy */
177093  jsonEachOpenTree,          /* xOpen - open a cursor */
177094  jsonEachClose,             /* xClose - close a cursor */
177095  jsonEachFilter,            /* xFilter - configure scan constraints */
177096  jsonEachNext,              /* xNext - advance a cursor */
177097  jsonEachEof,               /* xEof - check for end of scan */
177098  jsonEachColumn,            /* xColumn - read data */
177099  jsonEachRowid,             /* xRowid - read data */
177100  0,                         /* xUpdate */
177101  0,                         /* xBegin */
177102  0,                         /* xSync */
177103  0,                         /* xCommit */
177104  0,                         /* xRollback */
177105  0,                         /* xFindMethod */
177106  0,                         /* xRename */
177107  0,                         /* xSavepoint */
177108  0,                         /* xRelease */
177109  0                          /* xRollbackTo */
177110};
177111#endif /* SQLITE_OMIT_VIRTUALTABLE */
177112
177113/****************************************************************************
177114** The following routines are the only publically visible identifiers in this
177115** file.  Call the following routines in order to register the various SQL
177116** functions and the virtual table implemented by this file.
177117****************************************************************************/
177118
177119SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
177120  int rc = SQLITE_OK;
177121  unsigned int i;
177122  static const struct {
177123     const char *zName;
177124     int nArg;
177125     int flag;
177126     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
177127  } aFunc[] = {
177128    { "json",                 1, 0,   jsonRemoveFunc        },
177129    { "json_array",          -1, 0,   jsonArrayFunc         },
177130    { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
177131    { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
177132    { "json_extract",        -1, 0,   jsonExtractFunc       },
177133    { "json_insert",         -1, 0,   jsonSetFunc           },
177134    { "json_object",         -1, 0,   jsonObjectFunc        },
177135    { "json_quote",           1, 0,   jsonQuoteFunc         },
177136    { "json_remove",         -1, 0,   jsonRemoveFunc        },
177137    { "json_replace",        -1, 0,   jsonReplaceFunc       },
177138    { "json_set",            -1, 1,   jsonSetFunc           },
177139    { "json_type",            1, 0,   jsonTypeFunc          },
177140    { "json_type",            2, 0,   jsonTypeFunc          },
177141    { "json_valid",           1, 0,   jsonValidFunc         },
177142
177143#if SQLITE_DEBUG
177144    /* DEBUG and TESTING functions */
177145    { "json_parse",           1, 0,   jsonParseFunc         },
177146    { "json_test1",           1, 0,   jsonTest1Func         },
177147#endif
177148  };
177149  static const struct {
177150     const char *zName;
177151     int nArg;
177152     void (*xStep)(sqlite3_context*,int,sqlite3_value**);
177153     void (*xFinal)(sqlite3_context*);
177154  } aAgg[] = {
177155    { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
177156    { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
177157  };
177158#ifndef SQLITE_OMIT_VIRTUALTABLE
177159  static const struct {
177160     const char *zName;
177161     sqlite3_module *pModule;
177162  } aMod[] = {
177163    { "json_each",            &jsonEachModule               },
177164    { "json_tree",            &jsonTreeModule               },
177165  };
177166#endif
177167  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
177168    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
177169                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
177170                                 (void*)&aFunc[i].flag,
177171                                 aFunc[i].xFunc, 0, 0);
177172  }
177173  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
177174    rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
177175                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
177176                                 0, aAgg[i].xStep, aAgg[i].xFinal);
177177  }
177178#ifndef SQLITE_OMIT_VIRTUALTABLE
177179  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
177180    rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
177181  }
177182#endif
177183  return rc;
177184}
177185
177186
177187#ifndef SQLITE_CORE
177188#ifdef _WIN32
177189__declspec(dllexport)
177190#endif
177191SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
177192  sqlite3 *db,
177193  char **pzErrMsg,
177194  const sqlite3_api_routines *pApi
177195){
177196  SQLITE_EXTENSION_INIT2(pApi);
177197  (void)pzErrMsg;  /* Unused parameter */
177198  return sqlite3Json1Init(db);
177199}
177200#endif
177201#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
177202
177203/************** End of json1.c ***********************************************/
177204/************** Begin file fts5.c ********************************************/
177205
177206
177207#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
177208
177209#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
177210# define NDEBUG 1
177211#endif
177212#if defined(NDEBUG) && defined(SQLITE_DEBUG)
177213# undef NDEBUG
177214#endif
177215
177216/*
177217** 2014 May 31
177218**
177219** The author disclaims copyright to this source code.  In place of
177220** a legal notice, here is a blessing:
177221**
177222**    May you do good and not evil.
177223**    May you find forgiveness for yourself and forgive others.
177224**    May you share freely, never taking more than you give.
177225**
177226******************************************************************************
177227**
177228** Interfaces to extend FTS5. Using the interfaces defined in this file,
177229** FTS5 may be extended with:
177230**
177231**     * custom tokenizers, and
177232**     * custom auxiliary functions.
177233*/
177234
177235
177236#ifndef _FTS5_H
177237#define _FTS5_H
177238
177239/* #include "sqlite3.h" */
177240
177241#if 0
177242extern "C" {
177243#endif
177244
177245/*************************************************************************
177246** CUSTOM AUXILIARY FUNCTIONS
177247**
177248** Virtual table implementations may overload SQL functions by implementing
177249** the sqlite3_module.xFindFunction() method.
177250*/
177251
177252typedef struct Fts5ExtensionApi Fts5ExtensionApi;
177253typedef struct Fts5Context Fts5Context;
177254typedef struct Fts5PhraseIter Fts5PhraseIter;
177255
177256typedef void (*fts5_extension_function)(
177257  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
177258  Fts5Context *pFts,              /* First arg to pass to pApi functions */
177259  sqlite3_context *pCtx,          /* Context for returning result/error */
177260  int nVal,                       /* Number of values in apVal[] array */
177261  sqlite3_value **apVal           /* Array of trailing arguments */
177262);
177263
177264struct Fts5PhraseIter {
177265  const unsigned char *a;
177266  const unsigned char *b;
177267};
177268
177269/*
177270** EXTENSION API FUNCTIONS
177271**
177272** xUserData(pFts):
177273**   Return a copy of the context pointer the extension function was
177274**   registered with.
177275**
177276** xColumnTotalSize(pFts, iCol, pnToken):
177277**   If parameter iCol is less than zero, set output variable *pnToken
177278**   to the total number of tokens in the FTS5 table. Or, if iCol is
177279**   non-negative but less than the number of columns in the table, return
177280**   the total number of tokens in column iCol, considering all rows in
177281**   the FTS5 table.
177282**
177283**   If parameter iCol is greater than or equal to the number of columns
177284**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
177285**   an OOM condition or IO error), an appropriate SQLite error code is
177286**   returned.
177287**
177288** xColumnCount(pFts):
177289**   Return the number of columns in the table.
177290**
177291** xColumnSize(pFts, iCol, pnToken):
177292**   If parameter iCol is less than zero, set output variable *pnToken
177293**   to the total number of tokens in the current row. Or, if iCol is
177294**   non-negative but less than the number of columns in the table, set
177295**   *pnToken to the number of tokens in column iCol of the current row.
177296**
177297**   If parameter iCol is greater than or equal to the number of columns
177298**   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
177299**   an OOM condition or IO error), an appropriate SQLite error code is
177300**   returned.
177301**
177302**   This function may be quite inefficient if used with an FTS5 table
177303**   created with the "columnsize=0" option.
177304**
177305** xColumnText:
177306**   This function attempts to retrieve the text of column iCol of the
177307**   current document. If successful, (*pz) is set to point to a buffer
177308**   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
177309**   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
177310**   if an error occurs, an SQLite error code is returned and the final values
177311**   of (*pz) and (*pn) are undefined.
177312**
177313** xPhraseCount:
177314**   Returns the number of phrases in the current query expression.
177315**
177316** xPhraseSize:
177317**   Returns the number of tokens in phrase iPhrase of the query. Phrases
177318**   are numbered starting from zero.
177319**
177320** xInstCount:
177321**   Set *pnInst to the total number of occurrences of all phrases within
177322**   the query within the current row. Return SQLITE_OK if successful, or
177323**   an error code (i.e. SQLITE_NOMEM) 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. If the FTS5 table is created
177327**   with either "detail=none" or "detail=column" and "content=" option
177328**   (i.e. if it is a contentless table), then this API always returns 0.
177329**
177330** xInst:
177331**   Query for the details of phrase match iIdx within the current row.
177332**   Phrase matches are numbered starting from zero, so the iIdx argument
177333**   should be greater than or equal to zero and smaller than the value
177334**   output by xInstCount().
177335**
177336**   Usually, output parameter *piPhrase is set to the phrase number, *piCol
177337**   to the column in which it occurs and *piOff the token offset of the
177338**   first token of the phrase. The exception is if the table was created
177339**   with the offsets=0 option specified. In this case *piOff is always
177340**   set to -1.
177341**
177342**   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
177343**   if an error occurs.
177344**
177345**   This API can be quite slow if used with an FTS5 table created with the
177346**   "detail=none" or "detail=column" option.
177347**
177348** xRowid:
177349**   Returns the rowid of the current row.
177350**
177351** xTokenize:
177352**   Tokenize text using the tokenizer belonging to the FTS5 table.
177353**
177354** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
177355**   This API function is used to query the FTS table for phrase iPhrase
177356**   of the current query. Specifically, a query equivalent to:
177357**
177358**       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
177359**
177360**   with $p set to a phrase equivalent to the phrase iPhrase of the
177361**   current query is executed. Any column filter that applies to
177362**   phrase iPhrase of the current query is included in $p. For each
177363**   row visited, the callback function passed as the fourth argument
177364**   is invoked. The context and API objects passed to the callback
177365**   function may be used to access the properties of each matched row.
177366**   Invoking Api.xUserData() returns a copy of the pointer passed as
177367**   the third argument to pUserData.
177368**
177369**   If the callback function returns any value other than SQLITE_OK, the
177370**   query is abandoned and the xQueryPhrase function returns immediately.
177371**   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
177372**   Otherwise, the error code is propagated upwards.
177373**
177374**   If the query runs to completion without incident, SQLITE_OK is returned.
177375**   Or, if some error occurs before the query completes or is aborted by
177376**   the callback, an SQLite error code is returned.
177377**
177378**
177379** xSetAuxdata(pFts5, pAux, xDelete)
177380**
177381**   Save the pointer passed as the second argument as the extension functions
177382**   "auxiliary data". The pointer may then be retrieved by the current or any
177383**   future invocation of the same fts5 extension function made as part of
177384**   of the same MATCH query using the xGetAuxdata() API.
177385**
177386**   Each extension function is allocated a single auxiliary data slot for
177387**   each FTS query (MATCH expression). If the extension function is invoked
177388**   more than once for a single FTS query, then all invocations share a
177389**   single auxiliary data context.
177390**
177391**   If there is already an auxiliary data pointer when this function is
177392**   invoked, then it is replaced by the new pointer. If an xDelete callback
177393**   was specified along with the original pointer, it is invoked at this
177394**   point.
177395**
177396**   The xDelete callback, if one is specified, is also invoked on the
177397**   auxiliary data pointer after the FTS5 query has finished.
177398**
177399**   If an error (e.g. an OOM condition) occurs within this function, an
177400**   the auxiliary data is set to NULL and an error code returned. If the
177401**   xDelete parameter was not NULL, it is invoked on the auxiliary data
177402**   pointer before returning.
177403**
177404**
177405** xGetAuxdata(pFts5, bClear)
177406**
177407**   Returns the current auxiliary data pointer for the fts5 extension
177408**   function. See the xSetAuxdata() method for details.
177409**
177410**   If the bClear argument is non-zero, then the auxiliary data is cleared
177411**   (set to NULL) before this function returns. In this case the xDelete,
177412**   if any, is not invoked.
177413**
177414**
177415** xRowCount(pFts5, pnRow)
177416**
177417**   This function is used to retrieve the total number of rows in the table.
177418**   In other words, the same value that would be returned by:
177419**
177420**        SELECT count(*) FROM ftstable;
177421**
177422** xPhraseFirst()
177423**   This function is used, along with type Fts5PhraseIter and the xPhraseNext
177424**   method, to iterate through all instances of a single query phrase within
177425**   the current row. This is the same information as is accessible via the
177426**   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
177427**   to use, this API may be faster under some circumstances. To iterate
177428**   through instances of phrase iPhrase, use the following code:
177429**
177430**       Fts5PhraseIter iter;
177431**       int iCol, iOff;
177432**       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
177433**           iCol>=0;
177434**           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
177435**       ){
177436**         // An instance of phrase iPhrase at offset iOff of column iCol
177437**       }
177438**
177439**   The Fts5PhraseIter structure is defined above. Applications should not
177440**   modify this structure directly - it should only be used as shown above
177441**   with the xPhraseFirst() and xPhraseNext() API methods (and by
177442**   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
177443**
177444**   This API can be quite slow if used with an FTS5 table created with the
177445**   "detail=none" or "detail=column" option. If the FTS5 table is created
177446**   with either "detail=none" or "detail=column" and "content=" option
177447**   (i.e. if it is a contentless table), then this API always iterates
177448**   through an empty set (all calls to xPhraseFirst() set iCol to -1).
177449**
177450** xPhraseNext()
177451**   See xPhraseFirst above.
177452**
177453** xPhraseFirstColumn()
177454**   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
177455**   and xPhraseNext() APIs described above. The difference is that instead
177456**   of iterating through all instances of a phrase in the current row, these
177457**   APIs are used to iterate through the set of columns in the current row
177458**   that contain one or more instances of a specified phrase. For example:
177459**
177460**       Fts5PhraseIter iter;
177461**       int iCol;
177462**       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
177463**           iCol>=0;
177464**           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
177465**       ){
177466**         // Column iCol contains at least one instance of phrase iPhrase
177467**       }
177468**
177469**   This API can be quite slow if used with an FTS5 table created with the
177470**   "detail=none" option. If the FTS5 table is created with either
177471**   "detail=none" "content=" option (i.e. if it is a contentless table),
177472**   then this API always iterates through an empty set (all calls to
177473**   xPhraseFirstColumn() set iCol to -1).
177474**
177475**   The information accessed using this API and its companion
177476**   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
177477**   (or xInst/xInstCount). The chief advantage of this API is that it is
177478**   significantly more efficient than those alternatives when used with
177479**   "detail=column" tables.
177480**
177481** xPhraseNextColumn()
177482**   See xPhraseFirstColumn above.
177483*/
177484struct Fts5ExtensionApi {
177485  int iVersion;                   /* Currently always set to 3 */
177486
177487  void *(*xUserData)(Fts5Context*);
177488
177489  int (*xColumnCount)(Fts5Context*);
177490  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
177491  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
177492
177493  int (*xTokenize)(Fts5Context*,
177494    const char *pText, int nText, /* Text to tokenize */
177495    void *pCtx,                   /* Context passed to xToken() */
177496    int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
177497  );
177498
177499  int (*xPhraseCount)(Fts5Context*);
177500  int (*xPhraseSize)(Fts5Context*, int iPhrase);
177501
177502  int (*xInstCount)(Fts5Context*, int *pnInst);
177503  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
177504
177505  sqlite3_int64 (*xRowid)(Fts5Context*);
177506  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
177507  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
177508
177509  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
177510    int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
177511  );
177512  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
177513  void *(*xGetAuxdata)(Fts5Context*, int bClear);
177514
177515  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
177516  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
177517
177518  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
177519  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
177520};
177521
177522/*
177523** CUSTOM AUXILIARY FUNCTIONS
177524*************************************************************************/
177525
177526/*************************************************************************
177527** CUSTOM TOKENIZERS
177528**
177529** Applications may also register custom tokenizer types. A tokenizer
177530** is registered by providing fts5 with a populated instance of the
177531** following structure. All structure methods must be defined, setting
177532** any member of the fts5_tokenizer struct to NULL leads to undefined
177533** behaviour. The structure methods are expected to function as follows:
177534**
177535** xCreate:
177536**   This function is used to allocate and initialize a tokenizer instance.
177537**   A tokenizer instance is required to actually tokenize text.
177538**
177539**   The first argument passed to this function is a copy of the (void*)
177540**   pointer provided by the application when the fts5_tokenizer object
177541**   was registered with FTS5 (the third argument to xCreateTokenizer()).
177542**   The second and third arguments are an array of nul-terminated strings
177543**   containing the tokenizer arguments, if any, specified following the
177544**   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
177545**   to create the FTS5 table.
177546**
177547**   The final argument is an output variable. If successful, (*ppOut)
177548**   should be set to point to the new tokenizer handle and SQLITE_OK
177549**   returned. If an error occurs, some value other than SQLITE_OK should
177550**   be returned. In this case, fts5 assumes that the final value of *ppOut
177551**   is undefined.
177552**
177553** xDelete:
177554**   This function is invoked to delete a tokenizer handle previously
177555**   allocated using xCreate(). Fts5 guarantees that this function will
177556**   be invoked exactly once for each successful call to xCreate().
177557**
177558** xTokenize:
177559**   This function is expected to tokenize the nText byte string indicated
177560**   by argument pText. pText may or may not be nul-terminated. The first
177561**   argument passed to this function is a pointer to an Fts5Tokenizer object
177562**   returned by an earlier call to xCreate().
177563**
177564**   The second argument indicates the reason that FTS5 is requesting
177565**   tokenization of the supplied text. This is always one of the following
177566**   four values:
177567**
177568**   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
177569**            or removed from the FTS table. The tokenizer is being invoked to
177570**            determine the set of tokens to add to (or delete from) the
177571**            FTS index.
177572**
177573**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
177574**            against the FTS index. The tokenizer is being called to tokenize
177575**            a bareword or quoted string specified as part of the query.
177576**
177577**       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
177578**            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
177579**            followed by a "*" character, indicating that the last token
177580**            returned by the tokenizer will be treated as a token prefix.
177581**
177582**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
177583**            satisfy an fts5_api.xTokenize() request made by an auxiliary
177584**            function. Or an fts5_api.xColumnSize() request made by the same
177585**            on a columnsize=0 database.
177586**   </ul>
177587**
177588**   For each token in the input string, the supplied callback xToken() must
177589**   be invoked. The first argument to it should be a copy of the pointer
177590**   passed as the second argument to xTokenize(). The third and fourth
177591**   arguments are a pointer to a buffer containing the token text, and the
177592**   size of the token in bytes. The 4th and 5th arguments are the byte offsets
177593**   of the first byte of and first byte immediately following the text from
177594**   which the token is derived within the input.
177595**
177596**   The second argument passed to the xToken() callback ("tflags") should
177597**   normally be set to 0. The exception is if the tokenizer supports
177598**   synonyms. In this case see the discussion below for details.
177599**
177600**   FTS5 assumes the xToken() callback is invoked for each token in the
177601**   order that they occur within the input text.
177602**
177603**   If an xToken() callback returns any value other than SQLITE_OK, then
177604**   the tokenization should be abandoned and the xTokenize() method should
177605**   immediately return a copy of the xToken() return value. Or, if the
177606**   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
177607**   if an error occurs with the xTokenize() implementation itself, it
177608**   may abandon the tokenization and return any error code other than
177609**   SQLITE_OK or SQLITE_DONE.
177610**
177611** SYNONYM SUPPORT
177612**
177613**   Custom tokenizers may also support synonyms. Consider a case in which a
177614**   user wishes to query for a phrase such as "first place". Using the
177615**   built-in tokenizers, the FTS5 query 'first + place' will match instances
177616**   of "first place" within the document set, but not alternative forms
177617**   such as "1st place". In some applications, it would be better to match
177618**   all instances of "first place" or "1st place" regardless of which form
177619**   the user specified in the MATCH query text.
177620**
177621**   There are several ways to approach this in FTS5:
177622**
177623**   <ol><li> By mapping all synonyms to a single token. In this case, the
177624**            In the above example, this means that the tokenizer returns the
177625**            same token for inputs "first" and "1st". Say that token is in
177626**            fact "first", so that when the user inserts the document "I won
177627**            1st place" entries are added to the index for tokens "i", "won",
177628**            "first" and "place". If the user then queries for '1st + place',
177629**            the tokenizer substitutes "first" for "1st" and the query works
177630**            as expected.
177631**
177632**       <li> By adding multiple synonyms for a single term to the FTS index.
177633**            In this case, when tokenizing query text, the tokenizer may
177634**            provide multiple synonyms for a single term within the document.
177635**            FTS5 then queries the index for each synonym individually. For
177636**            example, faced with the query:
177637**
177638**   <codeblock>
177639**     ... MATCH 'first place'</codeblock>
177640**
177641**            the tokenizer offers both "1st" and "first" as synonyms for the
177642**            first token in the MATCH query and FTS5 effectively runs a query
177643**            similar to:
177644**
177645**   <codeblock>
177646**     ... MATCH '(first OR 1st) place'</codeblock>
177647**
177648**            except that, for the purposes of auxiliary functions, the query
177649**            still appears to contain just two phrases - "(first OR 1st)"
177650**            being treated as a single phrase.
177651**
177652**       <li> By adding multiple synonyms for a single term to the FTS index.
177653**            Using this method, when tokenizing document text, the tokenizer
177654**            provides multiple synonyms for each token. So that when a
177655**            document such as "I won first place" is tokenized, entries are
177656**            added to the FTS index for "i", "won", "first", "1st" and
177657**            "place".
177658**
177659**            This way, even if the tokenizer does not provide synonyms
177660**            when tokenizing query text (it should not - to do would be
177661**            inefficient), it doesn't matter if the user queries for
177662**            'first + place' or '1st + place', as there are entires in the
177663**            FTS index corresponding to both forms of the first token.
177664**   </ol>
177665**
177666**   Whether it is parsing document or query text, any call to xToken that
177667**   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
177668**   is considered to supply a synonym for the previous token. For example,
177669**   when parsing the document "I won first place", a tokenizer that supports
177670**   synonyms would call xToken() 5 times, as follows:
177671**
177672**   <codeblock>
177673**       xToken(pCtx, 0, "i",                      1,  0,  1);
177674**       xToken(pCtx, 0, "won",                    3,  2,  5);
177675**       xToken(pCtx, 0, "first",                  5,  6, 11);
177676**       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
177677**       xToken(pCtx, 0, "place",                  5, 12, 17);
177678**</codeblock>
177679**
177680**   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
177681**   xToken() is called. Multiple synonyms may be specified for a single token
177682**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
177683**   There is no limit to the number of synonyms that may be provided for a
177684**   single token.
177685**
177686**   In many cases, method (1) above is the best approach. It does not add
177687**   extra data to the FTS index or require FTS5 to query for multiple terms,
177688**   so it is efficient in terms of disk space and query speed. However, it
177689**   does not support prefix queries very well. If, as suggested above, the
177690**   token "first" is subsituted for "1st" by the tokenizer, then the query:
177691**
177692**   <codeblock>
177693**     ... MATCH '1s*'</codeblock>
177694**
177695**   will not match documents that contain the token "1st" (as the tokenizer
177696**   will probably not map "1s" to any prefix of "first").
177697**
177698**   For full prefix support, method (3) may be preferred. In this case,
177699**   because the index contains entries for both "first" and "1st", prefix
177700**   queries such as 'fi*' or '1s*' will match correctly. However, because
177701**   extra entries are added to the FTS index, this method uses more space
177702**   within the database.
177703**
177704**   Method (2) offers a midpoint between (1) and (3). Using this method,
177705**   a query such as '1s*' will match documents that contain the literal
177706**   token "1st", but not "first" (assuming the tokenizer is not able to
177707**   provide synonyms for prefixes). However, a non-prefix query like '1st'
177708**   will match against "1st" and "first". This method does not require
177709**   extra disk space, as no extra entries are added to the FTS index.
177710**   On the other hand, it may require more CPU cycles to run MATCH queries,
177711**   as separate queries of the FTS index are required for each synonym.
177712**
177713**   When using methods (2) or (3), it is important that the tokenizer only
177714**   provide synonyms when tokenizing document text (method (2)) or query
177715**   text (method (3)), not both. Doing so will not cause any errors, but is
177716**   inefficient.
177717*/
177718typedef struct Fts5Tokenizer Fts5Tokenizer;
177719typedef struct fts5_tokenizer fts5_tokenizer;
177720struct fts5_tokenizer {
177721  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
177722  void (*xDelete)(Fts5Tokenizer*);
177723  int (*xTokenize)(Fts5Tokenizer*,
177724      void *pCtx,
177725      int flags,            /* Mask of FTS5_TOKENIZE_* flags */
177726      const char *pText, int nText,
177727      int (*xToken)(
177728        void *pCtx,         /* Copy of 2nd argument to xTokenize() */
177729        int tflags,         /* Mask of FTS5_TOKEN_* flags */
177730        const char *pToken, /* Pointer to buffer containing token */
177731        int nToken,         /* Size of token in bytes */
177732        int iStart,         /* Byte offset of token within input text */
177733        int iEnd            /* Byte offset of end of token within input text */
177734      )
177735  );
177736};
177737
177738/* Flags that may be passed as the third argument to xTokenize() */
177739#define FTS5_TOKENIZE_QUERY     0x0001
177740#define FTS5_TOKENIZE_PREFIX    0x0002
177741#define FTS5_TOKENIZE_DOCUMENT  0x0004
177742#define FTS5_TOKENIZE_AUX       0x0008
177743
177744/* Flags that may be passed by the tokenizer implementation back to FTS5
177745** as the third argument to the supplied xToken callback. */
177746#define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
177747
177748/*
177749** END OF CUSTOM TOKENIZERS
177750*************************************************************************/
177751
177752/*************************************************************************
177753** FTS5 EXTENSION REGISTRATION API
177754*/
177755typedef struct fts5_api fts5_api;
177756struct fts5_api {
177757  int iVersion;                   /* Currently always set to 2 */
177758
177759  /* Create a new tokenizer */
177760  int (*xCreateTokenizer)(
177761    fts5_api *pApi,
177762    const char *zName,
177763    void *pContext,
177764    fts5_tokenizer *pTokenizer,
177765    void (*xDestroy)(void*)
177766  );
177767
177768  /* Find an existing tokenizer */
177769  int (*xFindTokenizer)(
177770    fts5_api *pApi,
177771    const char *zName,
177772    void **ppContext,
177773    fts5_tokenizer *pTokenizer
177774  );
177775
177776  /* Create a new auxiliary function */
177777  int (*xCreateFunction)(
177778    fts5_api *pApi,
177779    const char *zName,
177780    void *pContext,
177781    fts5_extension_function xFunction,
177782    void (*xDestroy)(void*)
177783  );
177784};
177785
177786/*
177787** END OF REGISTRATION API
177788*************************************************************************/
177789
177790#if 0
177791}  /* end of the 'extern "C"' block */
177792#endif
177793
177794#endif /* _FTS5_H */
177795
177796/*
177797** 2014 May 31
177798**
177799** The author disclaims copyright to this source code.  In place of
177800** a legal notice, here is a blessing:
177801**
177802**    May you do good and not evil.
177803**    May you find forgiveness for yourself and forgive others.
177804**    May you share freely, never taking more than you give.
177805**
177806******************************************************************************
177807**
177808*/
177809#ifndef _FTS5INT_H
177810#define _FTS5INT_H
177811
177812/* #include "fts5.h" */
177813/* #include "sqlite3ext.h" */
177814SQLITE_EXTENSION_INIT1
177815
177816/* #include <string.h> */
177817/* #include <assert.h> */
177818
177819#ifndef SQLITE_AMALGAMATION
177820
177821typedef unsigned char  u8;
177822typedef unsigned int   u32;
177823typedef unsigned short u16;
177824typedef short i16;
177825typedef sqlite3_int64 i64;
177826typedef sqlite3_uint64 u64;
177827
177828#define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
177829
177830#define testcase(x)
177831#define ALWAYS(x) 1
177832#define NEVER(x) 0
177833
177834#define MIN(x,y) (((x) < (y)) ? (x) : (y))
177835#define MAX(x,y) (((x) > (y)) ? (x) : (y))
177836
177837/*
177838** Constants for the largest and smallest possible 64-bit signed integers.
177839*/
177840# define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
177841# define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
177842
177843#endif
177844
177845/* Truncate very long tokens to this many bytes. Hard limit is
177846** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
177847** field that occurs at the start of each leaf page (see fts5_index.c). */
177848#define FTS5_MAX_TOKEN_SIZE 32768
177849
177850/*
177851** Maximum number of prefix indexes on single FTS5 table. This must be
177852** less than 32. If it is set to anything large than that, an #error
177853** directive in fts5_index.c will cause the build to fail.
177854*/
177855#define FTS5_MAX_PREFIX_INDEXES 31
177856
177857#define FTS5_DEFAULT_NEARDIST 10
177858#define FTS5_DEFAULT_RANK     "bm25"
177859
177860/* Name of rank and rowid columns */
177861#define FTS5_RANK_NAME "rank"
177862#define FTS5_ROWID_NAME "rowid"
177863
177864#ifdef SQLITE_DEBUG
177865# define FTS5_CORRUPT sqlite3Fts5Corrupt()
177866static int sqlite3Fts5Corrupt(void);
177867#else
177868# define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
177869#endif
177870
177871/*
177872** The assert_nc() macro is similar to the assert() macro, except that it
177873** is used for assert() conditions that are true only if it can be
177874** guranteed that the database is not corrupt.
177875*/
177876#ifdef SQLITE_DEBUG
177877SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
177878# define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
177879#else
177880# define assert_nc(x) assert(x)
177881#endif
177882
177883/* Mark a function parameter as unused, to suppress nuisance compiler
177884** warnings. */
177885#ifndef UNUSED_PARAM
177886# define UNUSED_PARAM(X)  (void)(X)
177887#endif
177888
177889#ifndef UNUSED_PARAM2
177890# define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
177891#endif
177892
177893typedef struct Fts5Global Fts5Global;
177894typedef struct Fts5Colset Fts5Colset;
177895
177896/* If a NEAR() clump or phrase may only match a specific set of columns,
177897** then an object of the following type is used to record the set of columns.
177898** Each entry in the aiCol[] array is a column that may be matched.
177899**
177900** This object is used by fts5_expr.c and fts5_index.c.
177901*/
177902struct Fts5Colset {
177903  int nCol;
177904  int aiCol[1];
177905};
177906
177907
177908
177909/**************************************************************************
177910** Interface to code in fts5_config.c. fts5_config.c contains contains code
177911** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
177912*/
177913
177914typedef struct Fts5Config Fts5Config;
177915
177916/*
177917** An instance of the following structure encodes all information that can
177918** be gleaned from the CREATE VIRTUAL TABLE statement.
177919**
177920** And all information loaded from the %_config table.
177921**
177922** nAutomerge:
177923**   The minimum number of segments that an auto-merge operation should
177924**   attempt to merge together. A value of 1 sets the object to use the
177925**   compile time default. Zero disables auto-merge altogether.
177926**
177927** zContent:
177928**
177929** zContentRowid:
177930**   The value of the content_rowid= option, if one was specified. Or
177931**   the string "rowid" otherwise. This text is not quoted - if it is
177932**   used as part of an SQL statement it needs to be quoted appropriately.
177933**
177934** zContentExprlist:
177935**
177936** pzErrmsg:
177937**   This exists in order to allow the fts5_index.c module to return a
177938**   decent error message if it encounters a file-format version it does
177939**   not understand.
177940**
177941** bColumnsize:
177942**   True if the %_docsize table is created.
177943**
177944** bPrefixIndex:
177945**   This is only used for debugging. If set to false, any prefix indexes
177946**   are ignored. This value is configured using:
177947**
177948**       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
177949**
177950*/
177951struct Fts5Config {
177952  sqlite3 *db;                    /* Database handle */
177953  char *zDb;                      /* Database holding FTS index (e.g. "main") */
177954  char *zName;                    /* Name of FTS index */
177955  int nCol;                       /* Number of columns */
177956  char **azCol;                   /* Column names */
177957  u8 *abUnindexed;                /* True for unindexed columns */
177958  int nPrefix;                    /* Number of prefix indexes */
177959  int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
177960  int eContent;                   /* An FTS5_CONTENT value */
177961  char *zContent;                 /* content table */
177962  char *zContentRowid;            /* "content_rowid=" option value */
177963  int bColumnsize;                /* "columnsize=" option value (dflt==1) */
177964  int eDetail;                    /* FTS5_DETAIL_XXX value */
177965  char *zContentExprlist;
177966  Fts5Tokenizer *pTok;
177967  fts5_tokenizer *pTokApi;
177968
177969  /* Values loaded from the %_config table */
177970  int iCookie;                    /* Incremented when %_config is modified */
177971  int pgsz;                       /* Approximate page size used in %_data */
177972  int nAutomerge;                 /* 'automerge' setting */
177973  int nCrisisMerge;               /* Maximum allowed segments per level */
177974  int nUsermerge;                 /* 'usermerge' setting */
177975  int nHashSize;                  /* Bytes of memory for in-memory hash */
177976  char *zRank;                    /* Name of rank function */
177977  char *zRankArgs;                /* Arguments to rank function */
177978
177979  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
177980  char **pzErrmsg;
177981
177982#ifdef SQLITE_DEBUG
177983  int bPrefixIndex;               /* True to use prefix-indexes */
177984#endif
177985};
177986
177987/* Current expected value of %_config table 'version' field */
177988#define FTS5_CURRENT_VERSION 4
177989
177990#define FTS5_CONTENT_NORMAL   0
177991#define FTS5_CONTENT_NONE     1
177992#define FTS5_CONTENT_EXTERNAL 2
177993
177994#define FTS5_DETAIL_FULL    0
177995#define FTS5_DETAIL_NONE    1
177996#define FTS5_DETAIL_COLUMNS 2
177997
177998
177999
178000static int sqlite3Fts5ConfigParse(
178001    Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
178002);
178003static void sqlite3Fts5ConfigFree(Fts5Config*);
178004
178005static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
178006
178007static int sqlite3Fts5Tokenize(
178008  Fts5Config *pConfig,            /* FTS5 Configuration object */
178009  int flags,                      /* FTS5_TOKENIZE_* flags */
178010  const char *pText, int nText,   /* Text to tokenize */
178011  void *pCtx,                     /* Context passed to xToken() */
178012  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
178013);
178014
178015static void sqlite3Fts5Dequote(char *z);
178016
178017/* Load the contents of the %_config table */
178018static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
178019
178020/* Set the value of a single config attribute */
178021static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
178022
178023static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
178024
178025/*
178026** End of interface to code in fts5_config.c.
178027**************************************************************************/
178028
178029/**************************************************************************
178030** Interface to code in fts5_buffer.c.
178031*/
178032
178033/*
178034** Buffer object for the incremental building of string data.
178035*/
178036typedef struct Fts5Buffer Fts5Buffer;
178037struct Fts5Buffer {
178038  u8 *p;
178039  int n;
178040  int nSpace;
178041};
178042
178043static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
178044static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
178045static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
178046static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
178047static void sqlite3Fts5BufferFree(Fts5Buffer*);
178048static void sqlite3Fts5BufferZero(Fts5Buffer*);
178049static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
178050static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
178051
178052static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
178053
178054#define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
178055#define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
178056#define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
178057#define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
178058#define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
178059
178060#define fts5BufferGrow(pRc,pBuf,nn) ( \
178061  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
178062    sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
178063)
178064
178065/* Write and decode big-endian 32-bit integer values */
178066static void sqlite3Fts5Put32(u8*, int);
178067static int sqlite3Fts5Get32(const u8*);
178068
178069#define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
178070#define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
178071
178072typedef struct Fts5PoslistReader Fts5PoslistReader;
178073struct Fts5PoslistReader {
178074  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
178075  const u8 *a;                    /* Position list to iterate through */
178076  int n;                          /* Size of buffer at a[] in bytes */
178077  int i;                          /* Current offset in a[] */
178078
178079  u8 bFlag;                       /* For client use (any custom purpose) */
178080
178081  /* Output variables */
178082  u8 bEof;                        /* Set to true at EOF */
178083  i64 iPos;                       /* (iCol<<32) + iPos */
178084};
178085static int sqlite3Fts5PoslistReaderInit(
178086  const u8 *a, int n,             /* Poslist buffer to iterate through */
178087  Fts5PoslistReader *pIter        /* Iterator object to initialize */
178088);
178089static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
178090
178091typedef struct Fts5PoslistWriter Fts5PoslistWriter;
178092struct Fts5PoslistWriter {
178093  i64 iPrev;
178094};
178095static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
178096static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
178097
178098static int sqlite3Fts5PoslistNext64(
178099  const u8 *a, int n,             /* Buffer containing poslist */
178100  int *pi,                        /* IN/OUT: Offset within a[] */
178101  i64 *piOff                      /* IN/OUT: Current offset */
178102);
178103
178104/* Malloc utility */
178105static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
178106static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
178107
178108/* Character set tests (like isspace(), isalpha() etc.) */
178109static int sqlite3Fts5IsBareword(char t);
178110
178111
178112/* Bucket of terms object used by the integrity-check in offsets=0 mode. */
178113typedef struct Fts5Termset Fts5Termset;
178114static int sqlite3Fts5TermsetNew(Fts5Termset**);
178115static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
178116static void sqlite3Fts5TermsetFree(Fts5Termset*);
178117
178118/*
178119** End of interface to code in fts5_buffer.c.
178120**************************************************************************/
178121
178122/**************************************************************************
178123** Interface to code in fts5_index.c. fts5_index.c contains contains code
178124** to access the data stored in the %_data table.
178125*/
178126
178127typedef struct Fts5Index Fts5Index;
178128typedef struct Fts5IndexIter Fts5IndexIter;
178129
178130struct Fts5IndexIter {
178131  i64 iRowid;
178132  const u8 *pData;
178133  int nData;
178134  u8 bEof;
178135};
178136
178137#define sqlite3Fts5IterEof(x) ((x)->bEof)
178138
178139/*
178140** Values used as part of the flags argument passed to IndexQuery().
178141*/
178142#define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
178143#define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
178144#define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
178145#define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
178146
178147/* The following are used internally by the fts5_index.c module. They are
178148** defined here only to make it easier to avoid clashes with the flags
178149** above. */
178150#define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
178151#define FTS5INDEX_QUERY_NOOUTPUT   0x0020
178152
178153/*
178154** Create/destroy an Fts5Index object.
178155*/
178156static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
178157static int sqlite3Fts5IndexClose(Fts5Index *p);
178158
178159/*
178160** Return a simple checksum value based on the arguments.
178161*/
178162static u64 sqlite3Fts5IndexEntryCksum(
178163  i64 iRowid,
178164  int iCol,
178165  int iPos,
178166  int iIdx,
178167  const char *pTerm,
178168  int nTerm
178169);
178170
178171/*
178172** Argument p points to a buffer containing utf-8 text that is n bytes in
178173** size. Return the number of bytes in the nChar character prefix of the
178174** buffer, or 0 if there are less than nChar characters in total.
178175*/
178176static int sqlite3Fts5IndexCharlenToBytelen(
178177  const char *p,
178178  int nByte,
178179  int nChar
178180);
178181
178182/*
178183** Open a new iterator to iterate though all rowids that match the
178184** specified token or token prefix.
178185*/
178186static int sqlite3Fts5IndexQuery(
178187  Fts5Index *p,                   /* FTS index to query */
178188  const char *pToken, int nToken, /* Token (or prefix) to query for */
178189  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
178190  Fts5Colset *pColset,            /* Match these columns only */
178191  Fts5IndexIter **ppIter          /* OUT: New iterator object */
178192);
178193
178194/*
178195** The various operations on open token or token prefix iterators opened
178196** using sqlite3Fts5IndexQuery().
178197*/
178198static int sqlite3Fts5IterNext(Fts5IndexIter*);
178199static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
178200
178201/*
178202** Close an iterator opened by sqlite3Fts5IndexQuery().
178203*/
178204static void sqlite3Fts5IterClose(Fts5IndexIter*);
178205
178206/*
178207** This interface is used by the fts5vocab module.
178208*/
178209static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
178210static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
178211
178212
178213/*
178214** Insert or remove data to or from the index. Each time a document is
178215** added to or removed from the index, this function is called one or more
178216** times.
178217**
178218** For an insert, it must be called once for each token in the new document.
178219** If the operation is a delete, it must be called (at least) once for each
178220** unique token in the document with an iCol value less than zero. The iPos
178221** argument is ignored for a delete.
178222*/
178223static int sqlite3Fts5IndexWrite(
178224  Fts5Index *p,                   /* Index to write to */
178225  int iCol,                       /* Column token appears in (-ve -> delete) */
178226  int iPos,                       /* Position of token within column */
178227  const char *pToken, int nToken  /* Token to add or remove to or from index */
178228);
178229
178230/*
178231** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
178232** document iDocid.
178233*/
178234static int sqlite3Fts5IndexBeginWrite(
178235  Fts5Index *p,                   /* Index to write to */
178236  int bDelete,                    /* True if current operation is a delete */
178237  i64 iDocid                      /* Docid to add or remove data from */
178238);
178239
178240/*
178241** Flush any data stored in the in-memory hash tables to the database.
178242** If the bCommit flag is true, also close any open blob handles.
178243*/
178244static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
178245
178246/*
178247** Discard any data stored in the in-memory hash tables. Do not write it
178248** to the database. Additionally, assume that the contents of the %_data
178249** table may have changed on disk. So any in-memory caches of %_data
178250** records must be invalidated.
178251*/
178252static int sqlite3Fts5IndexRollback(Fts5Index *p);
178253
178254/*
178255** Get or set the "averages" values.
178256*/
178257static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
178258static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
178259
178260/*
178261** Functions called by the storage module as part of integrity-check.
178262*/
178263static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
178264
178265/*
178266** Called during virtual module initialization to register UDF
178267** fts5_decode() with SQLite
178268*/
178269static int sqlite3Fts5IndexInit(sqlite3*);
178270
178271static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
178272
178273/*
178274** Return the total number of entries read from the %_data table by
178275** this connection since it was created.
178276*/
178277static int sqlite3Fts5IndexReads(Fts5Index *p);
178278
178279static int sqlite3Fts5IndexReinit(Fts5Index *p);
178280static int sqlite3Fts5IndexOptimize(Fts5Index *p);
178281static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
178282static int sqlite3Fts5IndexReset(Fts5Index *p);
178283
178284static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
178285
178286/*
178287** End of interface to code in fts5_index.c.
178288**************************************************************************/
178289
178290/**************************************************************************
178291** Interface to code in fts5_varint.c.
178292*/
178293static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
178294static int sqlite3Fts5GetVarintLen(u32 iVal);
178295static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
178296static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
178297
178298#define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
178299#define fts5GetVarint    sqlite3Fts5GetVarint
178300
178301#define fts5FastGetVarint32(a, iOff, nVal) {      \
178302  nVal = (a)[iOff++];                             \
178303  if( nVal & 0x80 ){                              \
178304    iOff--;                                       \
178305    iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
178306  }                                               \
178307}
178308
178309
178310/*
178311** End of interface to code in fts5_varint.c.
178312**************************************************************************/
178313
178314
178315/**************************************************************************
178316** Interface to code in fts5.c.
178317*/
178318
178319static int sqlite3Fts5GetTokenizer(
178320  Fts5Global*,
178321  const char **azArg,
178322  int nArg,
178323  Fts5Tokenizer**,
178324  fts5_tokenizer**,
178325  char **pzErr
178326);
178327
178328static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
178329
178330/*
178331** End of interface to code in fts5.c.
178332**************************************************************************/
178333
178334/**************************************************************************
178335** Interface to code in fts5_hash.c.
178336*/
178337typedef struct Fts5Hash Fts5Hash;
178338
178339/*
178340** Create a hash table, free a hash table.
178341*/
178342static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
178343static void sqlite3Fts5HashFree(Fts5Hash*);
178344
178345static int sqlite3Fts5HashWrite(
178346  Fts5Hash*,
178347  i64 iRowid,                     /* Rowid for this entry */
178348  int iCol,                       /* Column token appears in (-ve -> delete) */
178349  int iPos,                       /* Position of token within column */
178350  char bByte,
178351  const char *pToken, int nToken  /* Token to add or remove to or from index */
178352);
178353
178354/*
178355** Empty (but do not delete) a hash table.
178356*/
178357static void sqlite3Fts5HashClear(Fts5Hash*);
178358
178359static int sqlite3Fts5HashQuery(
178360  Fts5Hash*,                      /* Hash table to query */
178361  const char *pTerm, int nTerm,   /* Query term */
178362  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
178363  int *pnDoclist                  /* OUT: Size of doclist in bytes */
178364);
178365
178366static int sqlite3Fts5HashScanInit(
178367  Fts5Hash*,                      /* Hash table to query */
178368  const char *pTerm, int nTerm    /* Query prefix */
178369);
178370static void sqlite3Fts5HashScanNext(Fts5Hash*);
178371static int sqlite3Fts5HashScanEof(Fts5Hash*);
178372static void sqlite3Fts5HashScanEntry(Fts5Hash *,
178373  const char **pzTerm,            /* OUT: term (nul-terminated) */
178374  const u8 **ppDoclist,           /* OUT: pointer to doclist */
178375  int *pnDoclist                  /* OUT: size of doclist in bytes */
178376);
178377
178378
178379/*
178380** End of interface to code in fts5_hash.c.
178381**************************************************************************/
178382
178383/**************************************************************************
178384** Interface to code in fts5_storage.c. fts5_storage.c contains contains
178385** code to access the data stored in the %_content and %_docsize tables.
178386*/
178387
178388#define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
178389#define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
178390#define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
178391
178392typedef struct Fts5Storage Fts5Storage;
178393
178394static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
178395static int sqlite3Fts5StorageClose(Fts5Storage *p);
178396static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
178397
178398static int sqlite3Fts5DropAll(Fts5Config*);
178399static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
178400
178401static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
178402static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
178403static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
178404
178405static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
178406
178407static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
178408static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
178409
178410static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
178411static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
178412static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
178413
178414static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
178415static int sqlite3Fts5StorageRollback(Fts5Storage *p);
178416
178417static int sqlite3Fts5StorageConfigValue(
178418    Fts5Storage *p, const char*, sqlite3_value*, int
178419);
178420
178421static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
178422static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
178423static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
178424static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
178425static int sqlite3Fts5StorageReset(Fts5Storage *p);
178426
178427/*
178428** End of interface to code in fts5_storage.c.
178429**************************************************************************/
178430
178431
178432/**************************************************************************
178433** Interface to code in fts5_expr.c.
178434*/
178435typedef struct Fts5Expr Fts5Expr;
178436typedef struct Fts5ExprNode Fts5ExprNode;
178437typedef struct Fts5Parse Fts5Parse;
178438typedef struct Fts5Token Fts5Token;
178439typedef struct Fts5ExprPhrase Fts5ExprPhrase;
178440typedef struct Fts5ExprNearset Fts5ExprNearset;
178441
178442struct Fts5Token {
178443  const char *p;                  /* Token text (not NULL terminated) */
178444  int n;                          /* Size of buffer p in bytes */
178445};
178446
178447/* Parse a MATCH expression. */
178448static int sqlite3Fts5ExprNew(
178449  Fts5Config *pConfig,
178450  const char *zExpr,
178451  Fts5Expr **ppNew,
178452  char **pzErr
178453);
178454
178455/*
178456** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
178457**     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
178458**     rc = sqlite3Fts5ExprNext(pExpr)
178459** ){
178460**   // The document with rowid iRowid matches the expression!
178461**   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
178462** }
178463*/
178464static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
178465static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
178466static int sqlite3Fts5ExprEof(Fts5Expr*);
178467static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
178468
178469static void sqlite3Fts5ExprFree(Fts5Expr*);
178470
178471/* Called during startup to register a UDF with SQLite */
178472static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
178473
178474static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
178475static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
178476static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
178477
178478typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
178479static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
178480static int sqlite3Fts5ExprPopulatePoslists(
178481    Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
178482);
178483static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
178484
178485static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
178486
178487static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
178488
178489/*******************************************
178490** The fts5_expr.c API above this point is used by the other hand-written
178491** C code in this module. The interfaces below this point are called by
178492** the parser code in fts5parse.y.  */
178493
178494static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
178495
178496static Fts5ExprNode *sqlite3Fts5ParseNode(
178497  Fts5Parse *pParse,
178498  int eType,
178499  Fts5ExprNode *pLeft,
178500  Fts5ExprNode *pRight,
178501  Fts5ExprNearset *pNear
178502);
178503
178504static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
178505  Fts5Parse *pParse,
178506  Fts5ExprNode *pLeft,
178507  Fts5ExprNode *pRight
178508);
178509
178510static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
178511  Fts5Parse *pParse,
178512  Fts5ExprPhrase *pPhrase,
178513  Fts5Token *pToken,
178514  int bPrefix
178515);
178516
178517static Fts5ExprNearset *sqlite3Fts5ParseNearset(
178518  Fts5Parse*,
178519  Fts5ExprNearset*,
178520  Fts5ExprPhrase*
178521);
178522
178523static Fts5Colset *sqlite3Fts5ParseColset(
178524  Fts5Parse*,
178525  Fts5Colset*,
178526  Fts5Token *
178527);
178528
178529static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
178530static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
178531static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
178532
178533static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
178534static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
178535static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
178536static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
178537
178538/*
178539** End of interface to code in fts5_expr.c.
178540**************************************************************************/
178541
178542
178543
178544/**************************************************************************
178545** Interface to code in fts5_aux.c.
178546*/
178547
178548static int sqlite3Fts5AuxInit(fts5_api*);
178549/*
178550** End of interface to code in fts5_aux.c.
178551**************************************************************************/
178552
178553/**************************************************************************
178554** Interface to code in fts5_tokenizer.c.
178555*/
178556
178557static int sqlite3Fts5TokenizerInit(fts5_api*);
178558/*
178559** End of interface to code in fts5_tokenizer.c.
178560**************************************************************************/
178561
178562/**************************************************************************
178563** Interface to code in fts5_vocab.c.
178564*/
178565
178566static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
178567
178568/*
178569** End of interface to code in fts5_vocab.c.
178570**************************************************************************/
178571
178572
178573/**************************************************************************
178574** Interface to automatically generated code in fts5_unicode2.c.
178575*/
178576static int sqlite3Fts5UnicodeIsalnum(int c);
178577static int sqlite3Fts5UnicodeIsdiacritic(int c);
178578static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
178579/*
178580** End of interface to code in fts5_unicode2.c.
178581**************************************************************************/
178582
178583#endif
178584
178585#define FTS5_OR                               1
178586#define FTS5_AND                              2
178587#define FTS5_NOT                              3
178588#define FTS5_TERM                             4
178589#define FTS5_COLON                            5
178590#define FTS5_LP                               6
178591#define FTS5_RP                               7
178592#define FTS5_LCP                              8
178593#define FTS5_RCP                              9
178594#define FTS5_STRING                          10
178595#define FTS5_COMMA                           11
178596#define FTS5_PLUS                            12
178597#define FTS5_STAR                            13
178598
178599/*
178600** 2000-05-29
178601**
178602** The author disclaims copyright to this source code.  In place of
178603** a legal notice, here is a blessing:
178604**
178605**    May you do good and not evil.
178606**    May you find forgiveness for yourself and forgive others.
178607**    May you share freely, never taking more than you give.
178608**
178609*************************************************************************
178610** Driver template for the LEMON parser generator.
178611**
178612** The "lemon" program processes an LALR(1) input grammar file, then uses
178613** this template to construct a parser.  The "lemon" program inserts text
178614** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
178615** interstitial "-" characters) contained in this template is changed into
178616** the value of the %name directive from the grammar.  Otherwise, the content
178617** of this template is copied straight through into the generate parser
178618** source file.
178619**
178620** The following is the concatenation of all %include directives from the
178621** input grammar file:
178622*/
178623/* #include <stdio.h> */
178624/************ Begin %include sections from the grammar ************************/
178625
178626/* #include "fts5Int.h" */
178627/* #include "fts5parse.h" */
178628
178629/*
178630** Disable all error recovery processing in the parser push-down
178631** automaton.
178632*/
178633#define fts5YYNOERRORRECOVERY 1
178634
178635/*
178636** Make fts5yytestcase() the same as testcase()
178637*/
178638#define fts5yytestcase(X) testcase(X)
178639
178640/*
178641** Indicate that sqlite3ParserFree() will never be called with a null
178642** pointer.
178643*/
178644#define fts5YYPARSEFREENOTNULL 1
178645
178646/*
178647** Alternative datatype for the argument to the malloc() routine passed
178648** into sqlite3ParserAlloc().  The default is size_t.
178649*/
178650#define fts5YYMALLOCARGTYPE  u64
178651
178652/**************** End of %include directives **********************************/
178653/* These constants specify the various numeric values for terminal symbols
178654** in a format understandable to "makeheaders".  This section is blank unless
178655** "lemon" is run with the "-m" command-line option.
178656***************** Begin makeheaders token definitions *************************/
178657/**************** End makeheaders token definitions ***************************/
178658
178659/* The next sections is a series of control #defines.
178660** various aspects of the generated parser.
178661**    fts5YYCODETYPE         is the data type used to store the integer codes
178662**                       that represent terminal and non-terminal symbols.
178663**                       "unsigned char" is used if there are fewer than
178664**                       256 symbols.  Larger types otherwise.
178665**    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
178666**                       any terminal or nonterminal symbol.
178667**    fts5YYFALLBACK         If defined, this indicates that one or more tokens
178668**                       (also known as: "terminal symbols") have fall-back
178669**                       values which should be used if the original symbol
178670**                       would not parse.  This permits keywords to sometimes
178671**                       be used as identifiers, for example.
178672**    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
178673**                       that indicate what to do in response to the next
178674**                       token.
178675**    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
178676**                       symbols.  Background: A "minor type" is a semantic
178677**                       value associated with a terminal or non-terminal
178678**                       symbols.  For example, for an "ID" terminal symbol,
178679**                       the minor type might be the name of the identifier.
178680**                       Each non-terminal can have a different minor type.
178681**                       Terminal symbols all have the same minor type, though.
178682**                       This macros defines the minor type for terminal
178683**                       symbols.
178684**    fts5YYMINORTYPE        is the data type used for all minor types.
178685**                       This is typically a union of many types, one of
178686**                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
178687**                       for terminal symbols is called "fts5yy0".
178688**    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
178689**                       zero the stack is dynamically sized using realloc()
178690**    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
178691**    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
178692**    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
178693**    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
178694**    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
178695**                       defined, then do no error processing.
178696**    fts5YYNSTATE           the combined number of states.
178697**    fts5YYNRULE            the number of rules in the grammar
178698**    fts5YY_MAX_SHIFT       Maximum value for shift actions
178699**    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
178700**    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
178701**    fts5YY_MIN_REDUCE      Maximum value for reduce actions
178702**    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
178703**    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
178704**    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
178705*/
178706#ifndef INTERFACE
178707# define INTERFACE 1
178708#endif
178709/************* Begin control #defines *****************************************/
178710#define fts5YYCODETYPE unsigned char
178711#define fts5YYNOCODE 27
178712#define fts5YYACTIONTYPE unsigned char
178713#define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
178714typedef union {
178715  int fts5yyinit;
178716  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
178717  Fts5Colset* fts5yy3;
178718  Fts5ExprPhrase* fts5yy11;
178719  Fts5ExprNode* fts5yy18;
178720  int fts5yy20;
178721  Fts5ExprNearset* fts5yy26;
178722} fts5YYMINORTYPE;
178723#ifndef fts5YYSTACKDEPTH
178724#define fts5YYSTACKDEPTH 100
178725#endif
178726#define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
178727#define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
178728#define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
178729#define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
178730#define fts5YYNSTATE             26
178731#define fts5YYNRULE              24
178732#define fts5YY_MAX_SHIFT         25
178733#define fts5YY_MIN_SHIFTREDUCE   40
178734#define fts5YY_MAX_SHIFTREDUCE   63
178735#define fts5YY_MIN_REDUCE        64
178736#define fts5YY_MAX_REDUCE        87
178737#define fts5YY_ERROR_ACTION      88
178738#define fts5YY_ACCEPT_ACTION     89
178739#define fts5YY_NO_ACTION         90
178740/************* End control #defines *******************************************/
178741
178742/* Define the fts5yytestcase() macro to be a no-op if is not already defined
178743** otherwise.
178744**
178745** Applications can choose to define fts5yytestcase() in the %include section
178746** to a macro that can assist in verifying code coverage.  For production
178747** code the fts5yytestcase() macro should be turned off.  But it is useful
178748** for testing.
178749*/
178750#ifndef fts5yytestcase
178751# define fts5yytestcase(X)
178752#endif
178753
178754
178755/* Next are the tables used to determine what action to take based on the
178756** current state and lookahead token.  These tables are used to implement
178757** functions that take a state number and lookahead value and return an
178758** action integer.
178759**
178760** Suppose the action integer is N.  Then the action is determined as
178761** follows
178762**
178763**   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
178764**                                      token onto the stack and goto state N.
178765**
178766**   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
178767**     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
178768**
178769**   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
178770**     and fts5YY_MAX_REDUCE
178771
178772**   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
178773**
178774**   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
178775**
178776**   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
178777**                                      slots in the fts5yy_action[] table.
178778**
178779** The action table is constructed as a single large table named fts5yy_action[].
178780** Given state S and lookahead X, the action is computed as
178781**
178782**      fts5yy_action[ fts5yy_shift_ofst[S] + X ]
178783**
178784** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
178785** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
178786** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
178787** and that fts5yy_default[S] should be used instead.
178788**
178789** The formula above is for computing the action when the lookahead is
178790** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
178791** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
178792** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
178793** fts5YY_SHIFT_USE_DFLT.
178794**
178795** The following are the tables generated in this section:
178796**
178797**  fts5yy_action[]        A single table containing all actions.
178798**  fts5yy_lookahead[]     A table containing the lookahead for each entry in
178799**                     fts5yy_action.  Used to detect hash collisions.
178800**  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
178801**                     shifting terminals.
178802**  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
178803**                     shifting non-terminals after a reduce.
178804**  fts5yy_default[]       Default action for each state.
178805**
178806*********** Begin parsing tables **********************************************/
178807#define fts5YY_ACTTAB_COUNT (78)
178808static const fts5YYACTIONTYPE fts5yy_action[] = {
178809 /*     0 */    89,   15,   46,    5,   48,   24,   12,   19,   23,   14,
178810 /*    10 */    46,    5,   48,   24,   20,   21,   23,   43,   46,    5,
178811 /*    20 */    48,   24,    6,   18,   23,   17,   46,    5,   48,   24,
178812 /*    30 */    75,    7,   23,   25,   46,    5,   48,   24,   62,   47,
178813 /*    40 */    23,   48,   24,    7,   11,   23,    9,    3,    4,    2,
178814 /*    50 */    62,   50,   52,   44,   64,    3,    4,    2,   49,    4,
178815 /*    60 */     2,    1,   23,   11,   16,    9,   12,    2,   10,   61,
178816 /*    70 */    53,   59,   62,   60,   22,   13,   55,    8,
178817};
178818static const fts5YYCODETYPE fts5yy_lookahead[] = {
178819 /*     0 */    15,   16,   17,   18,   19,   20,   10,   11,   23,   16,
178820 /*    10 */    17,   18,   19,   20,   23,   24,   23,   16,   17,   18,
178821 /*    20 */    19,   20,   22,   23,   23,   16,   17,   18,   19,   20,
178822 /*    30 */     5,    6,   23,   16,   17,   18,   19,   20,   13,   17,
178823 /*    40 */    23,   19,   20,    6,    8,   23,   10,    1,    2,    3,
178824 /*    50 */    13,    9,   10,    7,    0,    1,    2,    3,   19,    2,
178825 /*    60 */     3,    6,   23,    8,   21,   10,   10,    3,   10,   25,
178826 /*    70 */    10,   10,   13,   25,   12,   10,    7,    5,
178827};
178828#define fts5YY_SHIFT_USE_DFLT (-5)
178829#define fts5YY_SHIFT_COUNT (25)
178830#define fts5YY_SHIFT_MIN   (-4)
178831#define fts5YY_SHIFT_MAX   (72)
178832static const signed char fts5yy_shift_ofst[] = {
178833 /*     0 */    55,   55,   55,   55,   55,   36,   -4,   56,   58,   25,
178834 /*    10 */    37,   60,   59,   59,   46,   54,   42,   57,   62,   61,
178835 /*    20 */    62,   69,   65,   62,   72,   64,
178836};
178837#define fts5YY_REDUCE_USE_DFLT (-16)
178838#define fts5YY_REDUCE_COUNT (13)
178839#define fts5YY_REDUCE_MIN   (-15)
178840#define fts5YY_REDUCE_MAX   (48)
178841static const signed char fts5yy_reduce_ofst[] = {
178842 /*     0 */   -15,   -7,    1,    9,   17,   22,   -9,    0,   39,   44,
178843 /*    10 */    44,   43,   44,   48,
178844};
178845static const fts5YYACTIONTYPE fts5yy_default[] = {
178846 /*     0 */    88,   88,   88,   88,   88,   69,   82,   88,   88,   87,
178847 /*    10 */    87,   88,   87,   87,   88,   88,   88,   66,   80,   88,
178848 /*    20 */    81,   88,   88,   78,   88,   65,
178849};
178850/********** End of lemon-generated parsing tables *****************************/
178851
178852/* The next table maps tokens (terminal symbols) into fallback tokens.
178853** If a construct like the following:
178854**
178855**      %fallback ID X Y Z.
178856**
178857** appears in the grammar, then ID becomes a fallback token for X, Y,
178858** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
178859** but it does not parse, the type of the token is changed to ID and
178860** the parse is retried before an error is thrown.
178861**
178862** This feature can be used, for example, to cause some keywords in a language
178863** to revert to identifiers if they keyword does not apply in the context where
178864** it appears.
178865*/
178866#ifdef fts5YYFALLBACK
178867static const fts5YYCODETYPE fts5yyFallback[] = {
178868};
178869#endif /* fts5YYFALLBACK */
178870
178871/* The following structure represents a single element of the
178872** parser's stack.  Information stored includes:
178873**
178874**   +  The state number for the parser at this level of the stack.
178875**
178876**   +  The value of the token stored at this level of the stack.
178877**      (In other words, the "major" token.)
178878**
178879**   +  The semantic value stored at this level of the stack.  This is
178880**      the information used by the action routines in the grammar.
178881**      It is sometimes called the "minor" token.
178882**
178883** After the "shift" half of a SHIFTREDUCE action, the stateno field
178884** actually contains the reduce action for the second half of the
178885** SHIFTREDUCE.
178886*/
178887struct fts5yyStackEntry {
178888  fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
178889  fts5YYCODETYPE major;      /* The major token value.  This is the code
178890                         ** number for the token at this stack level */
178891  fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
178892                         ** is the value of the token  */
178893};
178894typedef struct fts5yyStackEntry fts5yyStackEntry;
178895
178896/* The state of the parser is completely contained in an instance of
178897** the following structure */
178898struct fts5yyParser {
178899  fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
178900#ifdef fts5YYTRACKMAXSTACKDEPTH
178901  int fts5yyhwm;                    /* High-water mark of the stack */
178902#endif
178903#ifndef fts5YYNOERRORRECOVERY
178904  int fts5yyerrcnt;                 /* Shifts left before out of the error */
178905#endif
178906  sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
178907#if fts5YYSTACKDEPTH<=0
178908  int fts5yystksz;                  /* Current side of the stack */
178909  fts5yyStackEntry *fts5yystack;        /* The parser's stack */
178910  fts5yyStackEntry fts5yystk0;          /* First stack entry */
178911#else
178912  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
178913#endif
178914};
178915typedef struct fts5yyParser fts5yyParser;
178916
178917#ifndef NDEBUG
178918/* #include <stdio.h> */
178919static FILE *fts5yyTraceFILE = 0;
178920static char *fts5yyTracePrompt = 0;
178921#endif /* NDEBUG */
178922
178923#ifndef NDEBUG
178924/*
178925** Turn parser tracing on by giving a stream to which to write the trace
178926** and a prompt to preface each trace message.  Tracing is turned off
178927** by making either argument NULL
178928**
178929** Inputs:
178930** <ul>
178931** <li> A FILE* to which trace output should be written.
178932**      If NULL, then tracing is turned off.
178933** <li> A prefix string written at the beginning of every
178934**      line of trace output.  If NULL, then tracing is
178935**      turned off.
178936** </ul>
178937**
178938** Outputs:
178939** None.
178940*/
178941static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
178942  fts5yyTraceFILE = TraceFILE;
178943  fts5yyTracePrompt = zTracePrompt;
178944  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
178945  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
178946}
178947#endif /* NDEBUG */
178948
178949#ifndef NDEBUG
178950/* For tracing shifts, the names of all terminals and nonterminals
178951** are required.  The following table supplies these names */
178952static const char *const fts5yyTokenName[] = {
178953  "$",             "OR",            "AND",           "NOT",
178954  "TERM",          "COLON",         "LP",            "RP",
178955  "LCP",           "RCP",           "STRING",        "COMMA",
178956  "PLUS",          "STAR",          "error",         "input",
178957  "expr",          "cnearset",      "exprlist",      "nearset",
178958  "colset",        "colsetlist",    "nearphrases",   "phrase",
178959  "neardist_opt",  "star_opt",
178960};
178961#endif /* NDEBUG */
178962
178963#ifndef NDEBUG
178964/* For tracing reduce actions, the names of all rules are required.
178965*/
178966static const char *const fts5yyRuleName[] = {
178967 /*   0 */ "input ::= expr",
178968 /*   1 */ "expr ::= expr AND expr",
178969 /*   2 */ "expr ::= expr OR expr",
178970 /*   3 */ "expr ::= expr NOT expr",
178971 /*   4 */ "expr ::= LP expr RP",
178972 /*   5 */ "expr ::= exprlist",
178973 /*   6 */ "exprlist ::= cnearset",
178974 /*   7 */ "exprlist ::= exprlist cnearset",
178975 /*   8 */ "cnearset ::= nearset",
178976 /*   9 */ "cnearset ::= colset COLON nearset",
178977 /*  10 */ "colset ::= LCP colsetlist RCP",
178978 /*  11 */ "colset ::= STRING",
178979 /*  12 */ "colsetlist ::= colsetlist STRING",
178980 /*  13 */ "colsetlist ::= STRING",
178981 /*  14 */ "nearset ::= phrase",
178982 /*  15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
178983 /*  16 */ "nearphrases ::= phrase",
178984 /*  17 */ "nearphrases ::= nearphrases phrase",
178985 /*  18 */ "neardist_opt ::=",
178986 /*  19 */ "neardist_opt ::= COMMA STRING",
178987 /*  20 */ "phrase ::= phrase PLUS STRING star_opt",
178988 /*  21 */ "phrase ::= STRING star_opt",
178989 /*  22 */ "star_opt ::= STAR",
178990 /*  23 */ "star_opt ::=",
178991};
178992#endif /* NDEBUG */
178993
178994
178995#if fts5YYSTACKDEPTH<=0
178996/*
178997** Try to increase the size of the parser stack.  Return the number
178998** of errors.  Return 0 on success.
178999*/
179000static int fts5yyGrowStack(fts5yyParser *p){
179001  int newSize;
179002  int idx;
179003  fts5yyStackEntry *pNew;
179004
179005  newSize = p->fts5yystksz*2 + 100;
179006  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
179007  if( p->fts5yystack==&p->fts5yystk0 ){
179008    pNew = malloc(newSize*sizeof(pNew[0]));
179009    if( pNew ) pNew[0] = p->fts5yystk0;
179010  }else{
179011    pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
179012  }
179013  if( pNew ){
179014    p->fts5yystack = pNew;
179015    p->fts5yytos = &p->fts5yystack[idx];
179016#ifndef NDEBUG
179017    if( fts5yyTraceFILE ){
179018      fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
179019              fts5yyTracePrompt, p->fts5yystksz, newSize);
179020    }
179021#endif
179022    p->fts5yystksz = newSize;
179023  }
179024  return pNew==0;
179025}
179026#endif
179027
179028/* Datatype of the argument to the memory allocated passed as the
179029** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
179030** putting an appropriate #define in the %include section of the input
179031** grammar.
179032*/
179033#ifndef fts5YYMALLOCARGTYPE
179034# define fts5YYMALLOCARGTYPE size_t
179035#endif
179036
179037/*
179038** This function allocates a new parser.
179039** The only argument is a pointer to a function which works like
179040** malloc.
179041**
179042** Inputs:
179043** A pointer to the function used to allocate memory.
179044**
179045** Outputs:
179046** A pointer to a parser.  This pointer is used in subsequent calls
179047** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
179048*/
179049static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
179050  fts5yyParser *pParser;
179051  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
179052  if( pParser ){
179053#ifdef fts5YYTRACKMAXSTACKDEPTH
179054    pParser->fts5yyhwm = 0;
179055#endif
179056#if fts5YYSTACKDEPTH<=0
179057    pParser->fts5yytos = NULL;
179058    pParser->fts5yystack = NULL;
179059    pParser->fts5yystksz = 0;
179060    if( fts5yyGrowStack(pParser) ){
179061      pParser->fts5yystack = &pParser->fts5yystk0;
179062      pParser->fts5yystksz = 1;
179063    }
179064#endif
179065#ifndef fts5YYNOERRORRECOVERY
179066    pParser->fts5yyerrcnt = -1;
179067#endif
179068    pParser->fts5yytos = pParser->fts5yystack;
179069    pParser->fts5yystack[0].stateno = 0;
179070    pParser->fts5yystack[0].major = 0;
179071  }
179072  return pParser;
179073}
179074
179075/* The following function deletes the "minor type" or semantic value
179076** associated with a symbol.  The symbol can be either a terminal
179077** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
179078** a pointer to the value to be deleted.  The code used to do the
179079** deletions is derived from the %destructor and/or %token_destructor
179080** directives of the input grammar.
179081*/
179082static void fts5yy_destructor(
179083  fts5yyParser *fts5yypParser,    /* The parser */
179084  fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
179085  fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
179086){
179087  sqlite3Fts5ParserARG_FETCH;
179088  switch( fts5yymajor ){
179089    /* Here is inserted the actions which take place when a
179090    ** terminal or non-terminal is destroyed.  This can happen
179091    ** when the symbol is popped from the stack during a
179092    ** reduce or during error processing or when a parser is
179093    ** being destroyed before it is finished parsing.
179094    **
179095    ** Note: during a reduce, the only symbols destroyed are those
179096    ** which appear on the RHS of the rule, but which are *not* used
179097    ** inside the C code.
179098    */
179099/********* Begin destructor definitions ***************************************/
179100    case 15: /* input */
179101{
179102 (void)pParse;
179103}
179104      break;
179105    case 16: /* expr */
179106    case 17: /* cnearset */
179107    case 18: /* exprlist */
179108{
179109 sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
179110}
179111      break;
179112    case 19: /* nearset */
179113    case 22: /* nearphrases */
179114{
179115 sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
179116}
179117      break;
179118    case 20: /* colset */
179119    case 21: /* colsetlist */
179120{
179121 sqlite3_free((fts5yypminor->fts5yy3));
179122}
179123      break;
179124    case 23: /* phrase */
179125{
179126 sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
179127}
179128      break;
179129/********* End destructor definitions *****************************************/
179130    default:  break;   /* If no destructor action specified: do nothing */
179131  }
179132}
179133
179134/*
179135** Pop the parser's stack once.
179136**
179137** If there is a destructor routine associated with the token which
179138** is popped from the stack, then call it.
179139*/
179140static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
179141  fts5yyStackEntry *fts5yytos;
179142  assert( pParser->fts5yytos!=0 );
179143  assert( pParser->fts5yytos > pParser->fts5yystack );
179144  fts5yytos = pParser->fts5yytos--;
179145#ifndef NDEBUG
179146  if( fts5yyTraceFILE ){
179147    fprintf(fts5yyTraceFILE,"%sPopping %s\n",
179148      fts5yyTracePrompt,
179149      fts5yyTokenName[fts5yytos->major]);
179150  }
179151#endif
179152  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
179153}
179154
179155/*
179156** Deallocate and destroy a parser.  Destructors are called for
179157** all stack elements before shutting the parser down.
179158**
179159** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
179160** is defined in a %include section of the input grammar) then it is
179161** assumed that the input pointer is never NULL.
179162*/
179163static void sqlite3Fts5ParserFree(
179164  void *p,                    /* The parser to be deleted */
179165  void (*freeProc)(void*)     /* Function used to reclaim memory */
179166){
179167  fts5yyParser *pParser = (fts5yyParser*)p;
179168#ifndef fts5YYPARSEFREENEVERNULL
179169  if( pParser==0 ) return;
179170#endif
179171  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
179172#if fts5YYSTACKDEPTH<=0
179173  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
179174#endif
179175  (*freeProc)((void*)pParser);
179176}
179177
179178/*
179179** Return the peak depth of the stack for a parser.
179180*/
179181#ifdef fts5YYTRACKMAXSTACKDEPTH
179182static int sqlite3Fts5ParserStackPeak(void *p){
179183  fts5yyParser *pParser = (fts5yyParser*)p;
179184  return pParser->fts5yyhwm;
179185}
179186#endif
179187
179188/*
179189** Find the appropriate action for a parser given the terminal
179190** look-ahead token iLookAhead.
179191*/
179192static unsigned int fts5yy_find_shift_action(
179193  fts5yyParser *pParser,        /* The parser */
179194  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
179195){
179196  int i;
179197  int stateno = pParser->fts5yytos->stateno;
179198
179199  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
179200  assert( stateno <= fts5YY_SHIFT_COUNT );
179201  do{
179202    i = fts5yy_shift_ofst[stateno];
179203    if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
179204    assert( iLookAhead!=fts5YYNOCODE );
179205    i += iLookAhead;
179206    if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
179207      if( iLookAhead>0 ){
179208#ifdef fts5YYFALLBACK
179209        fts5YYCODETYPE iFallback;            /* Fallback token */
179210        if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
179211               && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
179212#ifndef NDEBUG
179213          if( fts5yyTraceFILE ){
179214            fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
179215               fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
179216          }
179217#endif
179218          assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
179219          iLookAhead = iFallback;
179220          continue;
179221        }
179222#endif
179223#ifdef fts5YYWILDCARD
179224        {
179225          int j = i - iLookAhead + fts5YYWILDCARD;
179226          if(
179227#if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
179228            j>=0 &&
179229#endif
179230#if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
179231            j<fts5YY_ACTTAB_COUNT &&
179232#endif
179233            fts5yy_lookahead[j]==fts5YYWILDCARD
179234          ){
179235#ifndef NDEBUG
179236            if( fts5yyTraceFILE ){
179237              fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
179238                 fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
179239                 fts5yyTokenName[fts5YYWILDCARD]);
179240            }
179241#endif /* NDEBUG */
179242            return fts5yy_action[j];
179243          }
179244        }
179245#endif /* fts5YYWILDCARD */
179246      }
179247      return fts5yy_default[stateno];
179248    }else{
179249      return fts5yy_action[i];
179250    }
179251  }while(1);
179252}
179253
179254/*
179255** Find the appropriate action for a parser given the non-terminal
179256** look-ahead token iLookAhead.
179257*/
179258static int fts5yy_find_reduce_action(
179259  int stateno,              /* Current state number */
179260  fts5YYCODETYPE iLookAhead     /* The look-ahead token */
179261){
179262  int i;
179263#ifdef fts5YYERRORSYMBOL
179264  if( stateno>fts5YY_REDUCE_COUNT ){
179265    return fts5yy_default[stateno];
179266  }
179267#else
179268  assert( stateno<=fts5YY_REDUCE_COUNT );
179269#endif
179270  i = fts5yy_reduce_ofst[stateno];
179271  assert( i!=fts5YY_REDUCE_USE_DFLT );
179272  assert( iLookAhead!=fts5YYNOCODE );
179273  i += iLookAhead;
179274#ifdef fts5YYERRORSYMBOL
179275  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
179276    return fts5yy_default[stateno];
179277  }
179278#else
179279  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
179280  assert( fts5yy_lookahead[i]==iLookAhead );
179281#endif
179282  return fts5yy_action[i];
179283}
179284
179285/*
179286** The following routine is called if the stack overflows.
179287*/
179288static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
179289   sqlite3Fts5ParserARG_FETCH;
179290   fts5yypParser->fts5yytos--;
179291#ifndef NDEBUG
179292   if( fts5yyTraceFILE ){
179293     fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
179294   }
179295#endif
179296   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
179297   /* Here code is inserted which will execute if the parser
179298   ** stack every overflows */
179299/******** Begin %stack_overflow code ******************************************/
179300
179301  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
179302/******** End %stack_overflow code ********************************************/
179303   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
179304}
179305
179306/*
179307** Print tracing information for a SHIFT action
179308*/
179309#ifndef NDEBUG
179310static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
179311  if( fts5yyTraceFILE ){
179312    if( fts5yyNewState<fts5YYNSTATE ){
179313      fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
179314         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
179315         fts5yyNewState);
179316    }else{
179317      fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
179318         fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
179319    }
179320  }
179321}
179322#else
179323# define fts5yyTraceShift(X,Y)
179324#endif
179325
179326/*
179327** Perform a shift action.
179328*/
179329static void fts5yy_shift(
179330  fts5yyParser *fts5yypParser,          /* The parser to be shifted */
179331  int fts5yyNewState,               /* The new state to shift in */
179332  int fts5yyMajor,                  /* The major token to shift in */
179333  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
179334){
179335  fts5yyStackEntry *fts5yytos;
179336  fts5yypParser->fts5yytos++;
179337#ifdef fts5YYTRACKMAXSTACKDEPTH
179338  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
179339    fts5yypParser->fts5yyhwm++;
179340    assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
179341  }
179342#endif
179343#if fts5YYSTACKDEPTH>0
179344  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
179345    fts5yyStackOverflow(fts5yypParser);
179346    return;
179347  }
179348#else
179349  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
179350    if( fts5yyGrowStack(fts5yypParser) ){
179351      fts5yyStackOverflow(fts5yypParser);
179352      return;
179353    }
179354  }
179355#endif
179356  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
179357    fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
179358  }
179359  fts5yytos = fts5yypParser->fts5yytos;
179360  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
179361  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
179362  fts5yytos->minor.fts5yy0 = fts5yyMinor;
179363  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
179364}
179365
179366/* The following table contains information about every rule that
179367** is used during the reduce.
179368*/
179369static const struct {
179370  fts5YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
179371  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
179372} fts5yyRuleInfo[] = {
179373  { 15, 1 },
179374  { 16, 3 },
179375  { 16, 3 },
179376  { 16, 3 },
179377  { 16, 3 },
179378  { 16, 1 },
179379  { 18, 1 },
179380  { 18, 2 },
179381  { 17, 1 },
179382  { 17, 3 },
179383  { 20, 3 },
179384  { 20, 1 },
179385  { 21, 2 },
179386  { 21, 1 },
179387  { 19, 1 },
179388  { 19, 5 },
179389  { 22, 1 },
179390  { 22, 2 },
179391  { 24, 0 },
179392  { 24, 2 },
179393  { 23, 4 },
179394  { 23, 2 },
179395  { 25, 1 },
179396  { 25, 0 },
179397};
179398
179399static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
179400
179401/*
179402** Perform a reduce action and the shift that must immediately
179403** follow the reduce.
179404*/
179405static void fts5yy_reduce(
179406  fts5yyParser *fts5yypParser,         /* The parser */
179407  unsigned int fts5yyruleno        /* Number of the rule by which to reduce */
179408){
179409  int fts5yygoto;                     /* The next state */
179410  int fts5yyact;                      /* The next action */
179411  fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
179412  int fts5yysize;                     /* Amount to pop the stack */
179413  sqlite3Fts5ParserARG_FETCH;
179414  fts5yymsp = fts5yypParser->fts5yytos;
179415#ifndef NDEBUG
179416  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
179417    fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
179418    fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
179419      fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
179420  }
179421#endif /* NDEBUG */
179422
179423  /* Check that the stack is large enough to grow by a single entry
179424  ** if the RHS of the rule is empty.  This ensures that there is room
179425  ** enough on the stack to push the LHS value */
179426  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
179427#ifdef fts5YYTRACKMAXSTACKDEPTH
179428    if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
179429      fts5yypParser->fts5yyhwm++;
179430      assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
179431    }
179432#endif
179433#if fts5YYSTACKDEPTH>0
179434    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
179435      fts5yyStackOverflow(fts5yypParser);
179436      return;
179437    }
179438#else
179439    if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
179440      if( fts5yyGrowStack(fts5yypParser) ){
179441        fts5yyStackOverflow(fts5yypParser);
179442        return;
179443      }
179444      fts5yymsp = fts5yypParser->fts5yytos;
179445    }
179446#endif
179447  }
179448
179449  switch( fts5yyruleno ){
179450  /* Beginning here are the reduction cases.  A typical example
179451  ** follows:
179452  **   case 0:
179453  **  #line <lineno> <grammarfile>
179454  **     { ... }           // User supplied code
179455  **  #line <lineno> <thisfile>
179456  **     break;
179457  */
179458/********** Begin reduce actions **********************************************/
179459        fts5YYMINORTYPE fts5yylhsminor;
179460      case 0: /* input ::= expr */
179461{ sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
179462        break;
179463      case 1: /* expr ::= expr AND expr */
179464{
179465  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179466}
179467  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179468        break;
179469      case 2: /* expr ::= expr OR expr */
179470{
179471  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179472}
179473  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179474        break;
179475      case 3: /* expr ::= expr NOT expr */
179476{
179477  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179478}
179479  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179480        break;
179481      case 4: /* expr ::= LP expr RP */
179482{fts5yymsp[-2].minor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
179483        break;
179484      case 5: /* expr ::= exprlist */
179485      case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
179486{fts5yylhsminor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
179487  fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179488        break;
179489      case 7: /* exprlist ::= exprlist cnearset */
179490{
179491  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18);
179492}
179493  fts5yymsp[-1].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179494        break;
179495      case 8: /* cnearset ::= nearset */
179496{
179497  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
179498}
179499  fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179500        break;
179501      case 9: /* cnearset ::= colset COLON nearset */
179502{
179503  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
179504  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
179505}
179506  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179507        break;
179508      case 10: /* colset ::= LCP colsetlist RCP */
179509{ fts5yymsp[-2].minor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
179510        break;
179511      case 11: /* colset ::= STRING */
179512{
179513  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
179514}
179515  fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179516        break;
179517      case 12: /* colsetlist ::= colsetlist STRING */
179518{
179519  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
179520  fts5yymsp[-1].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179521        break;
179522      case 13: /* colsetlist ::= STRING */
179523{
179524  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
179525}
179526  fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179527        break;
179528      case 14: /* nearset ::= phrase */
179529{ fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
179530  fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179531        break;
179532      case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
179533{
179534  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
179535  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
179536  fts5yylhsminor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
179537}
179538  fts5yymsp[-4].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179539        break;
179540      case 16: /* nearphrases ::= phrase */
179541{
179542  fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
179543}
179544  fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179545        break;
179546      case 17: /* nearphrases ::= nearphrases phrase */
179547{
179548  fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
179549}
179550  fts5yymsp[-1].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179551        break;
179552      case 18: /* neardist_opt ::= */
179553{ fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
179554        break;
179555      case 19: /* neardist_opt ::= COMMA STRING */
179556{ fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
179557        break;
179558      case 20: /* phrase ::= phrase PLUS STRING star_opt */
179559{
179560  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
179561}
179562  fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
179563        break;
179564      case 21: /* phrase ::= STRING star_opt */
179565{
179566  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
179567}
179568  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
179569        break;
179570      case 22: /* star_opt ::= STAR */
179571{ fts5yymsp[0].minor.fts5yy20 = 1; }
179572        break;
179573      case 23: /* star_opt ::= */
179574{ fts5yymsp[1].minor.fts5yy20 = 0; }
179575        break;
179576      default:
179577        break;
179578/********** End reduce actions ************************************************/
179579  };
179580  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
179581  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
179582  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
179583  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
179584  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
179585    if( fts5yyact>fts5YY_MAX_SHIFT ){
179586      fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
179587    }
179588    fts5yymsp -= fts5yysize-1;
179589    fts5yypParser->fts5yytos = fts5yymsp;
179590    fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
179591    fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
179592    fts5yyTraceShift(fts5yypParser, fts5yyact);
179593  }else{
179594    assert( fts5yyact == fts5YY_ACCEPT_ACTION );
179595    fts5yypParser->fts5yytos -= fts5yysize;
179596    fts5yy_accept(fts5yypParser);
179597  }
179598}
179599
179600/*
179601** The following code executes when the parse fails
179602*/
179603#ifndef fts5YYNOERRORRECOVERY
179604static void fts5yy_parse_failed(
179605  fts5yyParser *fts5yypParser           /* The parser */
179606){
179607  sqlite3Fts5ParserARG_FETCH;
179608#ifndef NDEBUG
179609  if( fts5yyTraceFILE ){
179610    fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
179611  }
179612#endif
179613  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
179614  /* Here code is inserted which will be executed whenever the
179615  ** parser fails */
179616/************ Begin %parse_failure code ***************************************/
179617/************ End %parse_failure code *****************************************/
179618  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179619}
179620#endif /* fts5YYNOERRORRECOVERY */
179621
179622/*
179623** The following code executes when a syntax error first occurs.
179624*/
179625static void fts5yy_syntax_error(
179626  fts5yyParser *fts5yypParser,           /* The parser */
179627  int fts5yymajor,                   /* The major type of the error token */
179628  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
179629){
179630  sqlite3Fts5ParserARG_FETCH;
179631#define FTS5TOKEN fts5yyminor
179632/************ Begin %syntax_error code ****************************************/
179633
179634  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
179635  sqlite3Fts5ParseError(
179636    pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
179637  );
179638/************ End %syntax_error code ******************************************/
179639  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179640}
179641
179642/*
179643** The following is executed when the parser accepts
179644*/
179645static void fts5yy_accept(
179646  fts5yyParser *fts5yypParser           /* The parser */
179647){
179648  sqlite3Fts5ParserARG_FETCH;
179649#ifndef NDEBUG
179650  if( fts5yyTraceFILE ){
179651    fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
179652  }
179653#endif
179654#ifndef fts5YYNOERRORRECOVERY
179655  fts5yypParser->fts5yyerrcnt = -1;
179656#endif
179657  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
179658  /* Here code is inserted which will be executed whenever the
179659  ** parser accepts */
179660/*********** Begin %parse_accept code *****************************************/
179661/*********** End %parse_accept code *******************************************/
179662  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179663}
179664
179665/* The main parser program.
179666** The first argument is a pointer to a structure obtained from
179667** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
179668** The second argument is the major token number.  The third is
179669** the minor token.  The fourth optional argument is whatever the
179670** user wants (and specified in the grammar) and is available for
179671** use by the action routines.
179672**
179673** Inputs:
179674** <ul>
179675** <li> A pointer to the parser (an opaque structure.)
179676** <li> The major token number.
179677** <li> The minor token number.
179678** <li> An option argument of a grammar-specified type.
179679** </ul>
179680**
179681** Outputs:
179682** None.
179683*/
179684static void sqlite3Fts5Parser(
179685  void *fts5yyp,                   /* The parser */
179686  int fts5yymajor,                 /* The major token code number */
179687  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
179688  sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
179689){
179690  fts5YYMINORTYPE fts5yyminorunion;
179691  unsigned int fts5yyact;   /* The parser action. */
179692#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
179693  int fts5yyendofinput;     /* True if we are at the end of input */
179694#endif
179695#ifdef fts5YYERRORSYMBOL
179696  int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
179697#endif
179698  fts5yyParser *fts5yypParser;  /* The parser */
179699
179700  fts5yypParser = (fts5yyParser*)fts5yyp;
179701  assert( fts5yypParser->fts5yytos!=0 );
179702#if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
179703  fts5yyendofinput = (fts5yymajor==0);
179704#endif
179705  sqlite3Fts5ParserARG_STORE;
179706
179707#ifndef NDEBUG
179708  if( fts5yyTraceFILE ){
179709    fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
179710  }
179711#endif
179712
179713  do{
179714    fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
179715    if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
179716      fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
179717#ifndef fts5YYNOERRORRECOVERY
179718      fts5yypParser->fts5yyerrcnt--;
179719#endif
179720      fts5yymajor = fts5YYNOCODE;
179721    }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
179722      fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
179723    }else{
179724      assert( fts5yyact == fts5YY_ERROR_ACTION );
179725      fts5yyminorunion.fts5yy0 = fts5yyminor;
179726#ifdef fts5YYERRORSYMBOL
179727      int fts5yymx;
179728#endif
179729#ifndef NDEBUG
179730      if( fts5yyTraceFILE ){
179731        fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
179732      }
179733#endif
179734#ifdef fts5YYERRORSYMBOL
179735      /* A syntax error has occurred.
179736      ** The response to an error depends upon whether or not the
179737      ** grammar defines an error token "ERROR".
179738      **
179739      ** This is what we do if the grammar does define ERROR:
179740      **
179741      **  * Call the %syntax_error function.
179742      **
179743      **  * Begin popping the stack until we enter a state where
179744      **    it is legal to shift the error symbol, then shift
179745      **    the error symbol.
179746      **
179747      **  * Set the error count to three.
179748      **
179749      **  * Begin accepting and shifting new tokens.  No new error
179750      **    processing will occur until three tokens have been
179751      **    shifted successfully.
179752      **
179753      */
179754      if( fts5yypParser->fts5yyerrcnt<0 ){
179755        fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
179756      }
179757      fts5yymx = fts5yypParser->fts5yytos->major;
179758      if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
179759#ifndef NDEBUG
179760        if( fts5yyTraceFILE ){
179761          fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
179762             fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
179763        }
179764#endif
179765        fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
179766        fts5yymajor = fts5YYNOCODE;
179767      }else{
179768        while( fts5yypParser->fts5yytos >= &fts5yypParser->fts5yystack
179769            && fts5yymx != fts5YYERRORSYMBOL
179770            && (fts5yyact = fts5yy_find_reduce_action(
179771                        fts5yypParser->fts5yytos->stateno,
179772                        fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
179773        ){
179774          fts5yy_pop_parser_stack(fts5yypParser);
179775        }
179776        if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
179777          fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179778          fts5yy_parse_failed(fts5yypParser);
179779#ifndef fts5YYNOERRORRECOVERY
179780          fts5yypParser->fts5yyerrcnt = -1;
179781#endif
179782          fts5yymajor = fts5YYNOCODE;
179783        }else if( fts5yymx!=fts5YYERRORSYMBOL ){
179784          fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
179785        }
179786      }
179787      fts5yypParser->fts5yyerrcnt = 3;
179788      fts5yyerrorhit = 1;
179789#elif defined(fts5YYNOERRORRECOVERY)
179790      /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
179791      ** do any kind of error recovery.  Instead, simply invoke the syntax
179792      ** error routine and continue going as if nothing had happened.
179793      **
179794      ** Applications can set this macro (for example inside %include) if
179795      ** they intend to abandon the parse upon the first syntax error seen.
179796      */
179797      fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
179798      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179799      fts5yymajor = fts5YYNOCODE;
179800
179801#else  /* fts5YYERRORSYMBOL is not defined */
179802      /* This is what we do if the grammar does not define ERROR:
179803      **
179804      **  * Report an error message, and throw away the input token.
179805      **
179806      **  * If the input token is $, then fail the parse.
179807      **
179808      ** As before, subsequent error messages are suppressed until
179809      ** three input tokens have been successfully shifted.
179810      */
179811      if( fts5yypParser->fts5yyerrcnt<=0 ){
179812        fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
179813      }
179814      fts5yypParser->fts5yyerrcnt = 3;
179815      fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179816      if( fts5yyendofinput ){
179817        fts5yy_parse_failed(fts5yypParser);
179818#ifndef fts5YYNOERRORRECOVERY
179819        fts5yypParser->fts5yyerrcnt = -1;
179820#endif
179821      }
179822      fts5yymajor = fts5YYNOCODE;
179823#endif
179824    }
179825  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
179826#ifndef NDEBUG
179827  if( fts5yyTraceFILE ){
179828    fts5yyStackEntry *i;
179829    char cDiv = '[';
179830    fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
179831    for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
179832      fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
179833      cDiv = ' ';
179834    }
179835    fprintf(fts5yyTraceFILE,"]\n");
179836  }
179837#endif
179838  return;
179839}
179840
179841/*
179842** 2014 May 31
179843**
179844** The author disclaims copyright to this source code.  In place of
179845** a legal notice, here is a blessing:
179846**
179847**    May you do good and not evil.
179848**    May you find forgiveness for yourself and forgive others.
179849**    May you share freely, never taking more than you give.
179850**
179851******************************************************************************
179852*/
179853
179854
179855/* #include "fts5Int.h" */
179856#include <math.h>                 /* amalgamator: keep */
179857
179858/*
179859** Object used to iterate through all "coalesced phrase instances" in
179860** a single column of the current row. If the phrase instances in the
179861** column being considered do not overlap, this object simply iterates
179862** through them. Or, if they do overlap (share one or more tokens in
179863** common), each set of overlapping instances is treated as a single
179864** match. See documentation for the highlight() auxiliary function for
179865** details.
179866**
179867** Usage is:
179868**
179869**   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
179870**      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
179871**      rc = fts5CInstIterNext(&iter)
179872**   ){
179873**     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
179874**   }
179875**
179876*/
179877typedef struct CInstIter CInstIter;
179878struct CInstIter {
179879  const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
179880  Fts5Context *pFts;              /* First arg to pass to pApi functions */
179881  int iCol;                       /* Column to search */
179882  int iInst;                      /* Next phrase instance index */
179883  int nInst;                      /* Total number of phrase instances */
179884
179885  /* Output variables */
179886  int iStart;                     /* First token in coalesced phrase instance */
179887  int iEnd;                       /* Last token in coalesced phrase instance */
179888};
179889
179890/*
179891** Advance the iterator to the next coalesced phrase instance. Return
179892** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
179893*/
179894static int fts5CInstIterNext(CInstIter *pIter){
179895  int rc = SQLITE_OK;
179896  pIter->iStart = -1;
179897  pIter->iEnd = -1;
179898
179899  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
179900    int ip; int ic; int io;
179901    rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
179902    if( rc==SQLITE_OK ){
179903      if( ic==pIter->iCol ){
179904        int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
179905        if( pIter->iStart<0 ){
179906          pIter->iStart = io;
179907          pIter->iEnd = iEnd;
179908        }else if( io<=pIter->iEnd ){
179909          if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
179910        }else{
179911          break;
179912        }
179913      }
179914      pIter->iInst++;
179915    }
179916  }
179917
179918  return rc;
179919}
179920
179921/*
179922** Initialize the iterator object indicated by the final parameter to
179923** iterate through coalesced phrase instances in column iCol.
179924*/
179925static int fts5CInstIterInit(
179926  const Fts5ExtensionApi *pApi,
179927  Fts5Context *pFts,
179928  int iCol,
179929  CInstIter *pIter
179930){
179931  int rc;
179932
179933  memset(pIter, 0, sizeof(CInstIter));
179934  pIter->pApi = pApi;
179935  pIter->pFts = pFts;
179936  pIter->iCol = iCol;
179937  rc = pApi->xInstCount(pFts, &pIter->nInst);
179938
179939  if( rc==SQLITE_OK ){
179940    rc = fts5CInstIterNext(pIter);
179941  }
179942
179943  return rc;
179944}
179945
179946
179947
179948/*************************************************************************
179949** Start of highlight() implementation.
179950*/
179951typedef struct HighlightContext HighlightContext;
179952struct HighlightContext {
179953  CInstIter iter;                 /* Coalesced Instance Iterator */
179954  int iPos;                       /* Current token offset in zIn[] */
179955  int iRangeStart;                /* First token to include */
179956  int iRangeEnd;                  /* If non-zero, last token to include */
179957  const char *zOpen;              /* Opening highlight */
179958  const char *zClose;             /* Closing highlight */
179959  const char *zIn;                /* Input text */
179960  int nIn;                        /* Size of input text in bytes */
179961  int iOff;                       /* Current offset within zIn[] */
179962  char *zOut;                     /* Output value */
179963};
179964
179965/*
179966** Append text to the HighlightContext output string - p->zOut. Argument
179967** z points to a buffer containing n bytes of text to append. If n is
179968** negative, everything up until the first '\0' is appended to the output.
179969**
179970** If *pRc is set to any value other than SQLITE_OK when this function is
179971** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
179972** *pRc is set to an error code before returning.
179973*/
179974static void fts5HighlightAppend(
179975  int *pRc,
179976  HighlightContext *p,
179977  const char *z, int n
179978){
179979  if( *pRc==SQLITE_OK ){
179980    if( n<0 ) n = (int)strlen(z);
179981    p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
179982    if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
179983  }
179984}
179985
179986/*
179987** Tokenizer callback used by implementation of highlight() function.
179988*/
179989static int fts5HighlightCb(
179990  void *pContext,                 /* Pointer to HighlightContext object */
179991  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
179992  const char *pToken,             /* Buffer containing token */
179993  int nToken,                     /* Size of token in bytes */
179994  int iStartOff,                  /* Start offset of token */
179995  int iEndOff                     /* End offset of token */
179996){
179997  HighlightContext *p = (HighlightContext*)pContext;
179998  int rc = SQLITE_OK;
179999  int iPos;
180000
180001  UNUSED_PARAM2(pToken, nToken);
180002
180003  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
180004  iPos = p->iPos++;
180005
180006  if( p->iRangeEnd>0 ){
180007    if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
180008    if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
180009  }
180010
180011  if( iPos==p->iter.iStart ){
180012    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
180013    fts5HighlightAppend(&rc, p, p->zOpen, -1);
180014    p->iOff = iStartOff;
180015  }
180016
180017  if( iPos==p->iter.iEnd ){
180018    if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
180019      fts5HighlightAppend(&rc, p, p->zOpen, -1);
180020    }
180021    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
180022    fts5HighlightAppend(&rc, p, p->zClose, -1);
180023    p->iOff = iEndOff;
180024    if( rc==SQLITE_OK ){
180025      rc = fts5CInstIterNext(&p->iter);
180026    }
180027  }
180028
180029  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
180030    fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
180031    p->iOff = iEndOff;
180032    if( iPos<p->iter.iEnd ){
180033      fts5HighlightAppend(&rc, p, p->zClose, -1);
180034    }
180035  }
180036
180037  return rc;
180038}
180039
180040/*
180041** Implementation of highlight() function.
180042*/
180043static void fts5HighlightFunction(
180044  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180045  Fts5Context *pFts,              /* First arg to pass to pApi functions */
180046  sqlite3_context *pCtx,          /* Context for returning result/error */
180047  int nVal,                       /* Number of values in apVal[] array */
180048  sqlite3_value **apVal           /* Array of trailing arguments */
180049){
180050  HighlightContext ctx;
180051  int rc;
180052  int iCol;
180053
180054  if( nVal!=3 ){
180055    const char *zErr = "wrong number of arguments to function highlight()";
180056    sqlite3_result_error(pCtx, zErr, -1);
180057    return;
180058  }
180059
180060  iCol = sqlite3_value_int(apVal[0]);
180061  memset(&ctx, 0, sizeof(HighlightContext));
180062  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
180063  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
180064  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
180065
180066  if( ctx.zIn ){
180067    if( rc==SQLITE_OK ){
180068      rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
180069    }
180070
180071    if( rc==SQLITE_OK ){
180072      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
180073    }
180074    fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
180075
180076    if( rc==SQLITE_OK ){
180077      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
180078    }
180079    sqlite3_free(ctx.zOut);
180080  }
180081  if( rc!=SQLITE_OK ){
180082    sqlite3_result_error_code(pCtx, rc);
180083  }
180084}
180085/*
180086** End of highlight() implementation.
180087**************************************************************************/
180088
180089/*
180090** Implementation of snippet() function.
180091*/
180092static void fts5SnippetFunction(
180093  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180094  Fts5Context *pFts,              /* First arg to pass to pApi functions */
180095  sqlite3_context *pCtx,          /* Context for returning result/error */
180096  int nVal,                       /* Number of values in apVal[] array */
180097  sqlite3_value **apVal           /* Array of trailing arguments */
180098){
180099  HighlightContext ctx;
180100  int rc = SQLITE_OK;             /* Return code */
180101  int iCol;                       /* 1st argument to snippet() */
180102  const char *zEllips;            /* 4th argument to snippet() */
180103  int nToken;                     /* 5th argument to snippet() */
180104  int nInst = 0;                  /* Number of instance matches this row */
180105  int i;                          /* Used to iterate through instances */
180106  int nPhrase;                    /* Number of phrases in query */
180107  unsigned char *aSeen;           /* Array of "seen instance" flags */
180108  int iBestCol;                   /* Column containing best snippet */
180109  int iBestStart = 0;             /* First token of best snippet */
180110  int iBestLast;                  /* Last token of best snippet */
180111  int nBestScore = 0;             /* Score of best snippet */
180112  int nColSize = 0;               /* Total size of iBestCol in tokens */
180113
180114  if( nVal!=5 ){
180115    const char *zErr = "wrong number of arguments to function snippet()";
180116    sqlite3_result_error(pCtx, zErr, -1);
180117    return;
180118  }
180119
180120  memset(&ctx, 0, sizeof(HighlightContext));
180121  iCol = sqlite3_value_int(apVal[0]);
180122  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
180123  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
180124  zEllips = (const char*)sqlite3_value_text(apVal[3]);
180125  nToken = sqlite3_value_int(apVal[4]);
180126  iBestLast = nToken-1;
180127
180128  iBestCol = (iCol>=0 ? iCol : 0);
180129  nPhrase = pApi->xPhraseCount(pFts);
180130  aSeen = sqlite3_malloc(nPhrase);
180131  if( aSeen==0 ){
180132    rc = SQLITE_NOMEM;
180133  }
180134
180135  if( rc==SQLITE_OK ){
180136    rc = pApi->xInstCount(pFts, &nInst);
180137  }
180138  for(i=0; rc==SQLITE_OK && i<nInst; i++){
180139    int ip, iSnippetCol, iStart;
180140    memset(aSeen, 0, nPhrase);
180141    rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
180142    if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
180143      int nScore = 1000;
180144      int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
180145      int j;
180146      aSeen[ip] = 1;
180147
180148      for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
180149        int ic; int io; int iFinal;
180150        rc = pApi->xInst(pFts, j, &ip, &ic, &io);
180151        iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
180152        if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
180153          nScore += aSeen[ip] ? 1000 : 1;
180154          aSeen[ip] = 1;
180155          if( iFinal>iLast ) iLast = iFinal;
180156        }
180157      }
180158
180159      if( rc==SQLITE_OK && nScore>nBestScore ){
180160        iBestCol = iSnippetCol;
180161        iBestStart = iStart;
180162        iBestLast = iLast;
180163        nBestScore = nScore;
180164      }
180165    }
180166  }
180167
180168  if( rc==SQLITE_OK ){
180169    rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
180170  }
180171  if( rc==SQLITE_OK ){
180172    rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
180173  }
180174  if( ctx.zIn ){
180175    if( rc==SQLITE_OK ){
180176      rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
180177    }
180178
180179    if( (iBestStart+nToken-1)>iBestLast ){
180180      iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
180181    }
180182    if( iBestStart+nToken>nColSize ){
180183      iBestStart = nColSize - nToken;
180184    }
180185    if( iBestStart<0 ) iBestStart = 0;
180186
180187    ctx.iRangeStart = iBestStart;
180188    ctx.iRangeEnd = iBestStart + nToken - 1;
180189
180190    if( iBestStart>0 ){
180191      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
180192    }
180193    if( rc==SQLITE_OK ){
180194      rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
180195    }
180196    if( ctx.iRangeEnd>=(nColSize-1) ){
180197      fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
180198    }else{
180199      fts5HighlightAppend(&rc, &ctx, zEllips, -1);
180200    }
180201
180202    if( rc==SQLITE_OK ){
180203      sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
180204    }else{
180205      sqlite3_result_error_code(pCtx, rc);
180206    }
180207    sqlite3_free(ctx.zOut);
180208  }
180209  sqlite3_free(aSeen);
180210}
180211
180212/************************************************************************/
180213
180214/*
180215** The first time the bm25() function is called for a query, an instance
180216** of the following structure is allocated and populated.
180217*/
180218typedef struct Fts5Bm25Data Fts5Bm25Data;
180219struct Fts5Bm25Data {
180220  int nPhrase;                    /* Number of phrases in query */
180221  double avgdl;                   /* Average number of tokens in each row */
180222  double *aIDF;                   /* IDF for each phrase */
180223  double *aFreq;                  /* Array used to calculate phrase freq. */
180224};
180225
180226/*
180227** Callback used by fts5Bm25GetData() to count the number of rows in the
180228** table matched by each individual phrase within the query.
180229*/
180230static int fts5CountCb(
180231  const Fts5ExtensionApi *pApi,
180232  Fts5Context *pFts,
180233  void *pUserData                 /* Pointer to sqlite3_int64 variable */
180234){
180235  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
180236  UNUSED_PARAM2(pApi, pFts);
180237  (*pn)++;
180238  return SQLITE_OK;
180239}
180240
180241/*
180242** Set *ppData to point to the Fts5Bm25Data object for the current query.
180243** If the object has not already been allocated, allocate and populate it
180244** now.
180245*/
180246static int fts5Bm25GetData(
180247  const Fts5ExtensionApi *pApi,
180248  Fts5Context *pFts,
180249  Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
180250){
180251  int rc = SQLITE_OK;             /* Return code */
180252  Fts5Bm25Data *p;                /* Object to return */
180253
180254  p = pApi->xGetAuxdata(pFts, 0);
180255  if( p==0 ){
180256    int nPhrase;                  /* Number of phrases in query */
180257    sqlite3_int64 nRow = 0;       /* Number of rows in table */
180258    sqlite3_int64 nToken = 0;     /* Number of tokens in table */
180259    int nByte;                    /* Bytes of space to allocate */
180260    int i;
180261
180262    /* Allocate the Fts5Bm25Data object */
180263    nPhrase = pApi->xPhraseCount(pFts);
180264    nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
180265    p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
180266    if( p==0 ){
180267      rc = SQLITE_NOMEM;
180268    }else{
180269      memset(p, 0, nByte);
180270      p->nPhrase = nPhrase;
180271      p->aIDF = (double*)&p[1];
180272      p->aFreq = &p->aIDF[nPhrase];
180273    }
180274
180275    /* Calculate the average document length for this FTS5 table */
180276    if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
180277    if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
180278    if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
180279
180280    /* Calculate an IDF for each phrase in the query */
180281    for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
180282      sqlite3_int64 nHit = 0;
180283      rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
180284      if( rc==SQLITE_OK ){
180285        /* Calculate the IDF (Inverse Document Frequency) for phrase i.
180286        ** This is done using the standard BM25 formula as found on wikipedia:
180287        **
180288        **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
180289        **
180290        ** where "N" is the total number of documents in the set and nHit
180291        ** is the number that contain at least one instance of the phrase
180292        ** under consideration.
180293        **
180294        ** The problem with this is that if (N < 2*nHit), the IDF is
180295        ** negative. Which is undesirable. So the mimimum allowable IDF is
180296        ** (1e-6) - roughly the same as a term that appears in just over
180297        ** half of set of 5,000,000 documents.  */
180298        double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
180299        if( idf<=0.0 ) idf = 1e-6;
180300        p->aIDF[i] = idf;
180301      }
180302    }
180303
180304    if( rc!=SQLITE_OK ){
180305      sqlite3_free(p);
180306    }else{
180307      rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
180308    }
180309    if( rc!=SQLITE_OK ) p = 0;
180310  }
180311  *ppData = p;
180312  return rc;
180313}
180314
180315/*
180316** Implementation of bm25() function.
180317*/
180318static void fts5Bm25Function(
180319  const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180320  Fts5Context *pFts,              /* First arg to pass to pApi functions */
180321  sqlite3_context *pCtx,          /* Context for returning result/error */
180322  int nVal,                       /* Number of values in apVal[] array */
180323  sqlite3_value **apVal           /* Array of trailing arguments */
180324){
180325  const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
180326  const double b = 0.75;          /* Constant "b" from BM25 formula */
180327  int rc = SQLITE_OK;             /* Error code */
180328  double score = 0.0;             /* SQL function return value */
180329  Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
180330  int i;                          /* Iterator variable */
180331  int nInst = 0;                  /* Value returned by xInstCount() */
180332  double D = 0.0;                 /* Total number of tokens in row */
180333  double *aFreq = 0;              /* Array of phrase freq. for current row */
180334
180335  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
180336  ** for each phrase in the query for the current row. */
180337  rc = fts5Bm25GetData(pApi, pFts, &pData);
180338  if( rc==SQLITE_OK ){
180339    aFreq = pData->aFreq;
180340    memset(aFreq, 0, sizeof(double) * pData->nPhrase);
180341    rc = pApi->xInstCount(pFts, &nInst);
180342  }
180343  for(i=0; rc==SQLITE_OK && i<nInst; i++){
180344    int ip; int ic; int io;
180345    rc = pApi->xInst(pFts, i, &ip, &ic, &io);
180346    if( rc==SQLITE_OK ){
180347      double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
180348      aFreq[ip] += w;
180349    }
180350  }
180351
180352  /* Figure out the total size of the current row in tokens. */
180353  if( rc==SQLITE_OK ){
180354    int nTok;
180355    rc = pApi->xColumnSize(pFts, -1, &nTok);
180356    D = (double)nTok;
180357  }
180358
180359  /* Determine the BM25 score for the current row. */
180360  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
180361    score += pData->aIDF[i] * (
180362      ( aFreq[i] * (k1 + 1.0) ) /
180363      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
180364    );
180365  }
180366
180367  /* If no error has occurred, return the calculated score. Otherwise,
180368  ** throw an SQL exception.  */
180369  if( rc==SQLITE_OK ){
180370    sqlite3_result_double(pCtx, -1.0 * score);
180371  }else{
180372    sqlite3_result_error_code(pCtx, rc);
180373  }
180374}
180375
180376static int sqlite3Fts5AuxInit(fts5_api *pApi){
180377  struct Builtin {
180378    const char *zFunc;            /* Function name (nul-terminated) */
180379    void *pUserData;              /* User-data pointer */
180380    fts5_extension_function xFunc;/* Callback function */
180381    void (*xDestroy)(void*);      /* Destructor function */
180382  } aBuiltin [] = {
180383    { "snippet",   0, fts5SnippetFunction, 0 },
180384    { "highlight", 0, fts5HighlightFunction, 0 },
180385    { "bm25",      0, fts5Bm25Function,    0 },
180386  };
180387  int rc = SQLITE_OK;             /* Return code */
180388  int i;                          /* To iterate through builtin functions */
180389
180390  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
180391    rc = pApi->xCreateFunction(pApi,
180392        aBuiltin[i].zFunc,
180393        aBuiltin[i].pUserData,
180394        aBuiltin[i].xFunc,
180395        aBuiltin[i].xDestroy
180396    );
180397  }
180398
180399  return rc;
180400}
180401
180402
180403
180404/*
180405** 2014 May 31
180406**
180407** The author disclaims copyright to this source code.  In place of
180408** a legal notice, here is a blessing:
180409**
180410**    May you do good and not evil.
180411**    May you find forgiveness for yourself and forgive others.
180412**    May you share freely, never taking more than you give.
180413**
180414******************************************************************************
180415*/
180416
180417
180418
180419/* #include "fts5Int.h" */
180420
180421static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
180422  if( (u32)pBuf->nSpace<nByte ){
180423    u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
180424    u8 *pNew;
180425    while( nNew<nByte ){
180426      nNew = nNew * 2;
180427    }
180428    pNew = sqlite3_realloc(pBuf->p, nNew);
180429    if( pNew==0 ){
180430      *pRc = SQLITE_NOMEM;
180431      return 1;
180432    }else{
180433      pBuf->nSpace = nNew;
180434      pBuf->p = pNew;
180435    }
180436  }
180437  return 0;
180438}
180439
180440
180441/*
180442** Encode value iVal as an SQLite varint and append it to the buffer object
180443** pBuf. If an OOM error occurs, set the error code in p.
180444*/
180445static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
180446  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
180447  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
180448}
180449
180450static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
180451  aBuf[0] = (iVal>>24) & 0x00FF;
180452  aBuf[1] = (iVal>>16) & 0x00FF;
180453  aBuf[2] = (iVal>> 8) & 0x00FF;
180454  aBuf[3] = (iVal>> 0) & 0x00FF;
180455}
180456
180457static int sqlite3Fts5Get32(const u8 *aBuf){
180458  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
180459}
180460
180461/*
180462** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
180463** the error code in p. If an error has already occurred when this function
180464** is called, it is a no-op.
180465*/
180466static void sqlite3Fts5BufferAppendBlob(
180467  int *pRc,
180468  Fts5Buffer *pBuf,
180469  u32 nData,
180470  const u8 *pData
180471){
180472  assert_nc( *pRc || nData>=0 );
180473  if( fts5BufferGrow(pRc, pBuf, nData) ) return;
180474  memcpy(&pBuf->p[pBuf->n], pData, nData);
180475  pBuf->n += nData;
180476}
180477
180478/*
180479** Append the nul-terminated string zStr to the buffer pBuf. This function
180480** ensures that the byte following the buffer data is set to 0x00, even
180481** though this byte is not included in the pBuf->n count.
180482*/
180483static void sqlite3Fts5BufferAppendString(
180484  int *pRc,
180485  Fts5Buffer *pBuf,
180486  const char *zStr
180487){
180488  int nStr = (int)strlen(zStr);
180489  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
180490  pBuf->n--;
180491}
180492
180493/*
180494** Argument zFmt is a printf() style format string. This function performs
180495** the printf() style processing, then appends the results to buffer pBuf.
180496**
180497** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
180498** following the buffer data is set to 0x00, even though this byte is not
180499** included in the pBuf->n count.
180500*/
180501static void sqlite3Fts5BufferAppendPrintf(
180502  int *pRc,
180503  Fts5Buffer *pBuf,
180504  char *zFmt, ...
180505){
180506  if( *pRc==SQLITE_OK ){
180507    char *zTmp;
180508    va_list ap;
180509    va_start(ap, zFmt);
180510    zTmp = sqlite3_vmprintf(zFmt, ap);
180511    va_end(ap);
180512
180513    if( zTmp==0 ){
180514      *pRc = SQLITE_NOMEM;
180515    }else{
180516      sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
180517      sqlite3_free(zTmp);
180518    }
180519  }
180520}
180521
180522static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
180523  char *zRet = 0;
180524  if( *pRc==SQLITE_OK ){
180525    va_list ap;
180526    va_start(ap, zFmt);
180527    zRet = sqlite3_vmprintf(zFmt, ap);
180528    va_end(ap);
180529    if( zRet==0 ){
180530      *pRc = SQLITE_NOMEM;
180531    }
180532  }
180533  return zRet;
180534}
180535
180536
180537/*
180538** Free any buffer allocated by pBuf. Zero the structure before returning.
180539*/
180540static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
180541  sqlite3_free(pBuf->p);
180542  memset(pBuf, 0, sizeof(Fts5Buffer));
180543}
180544
180545/*
180546** Zero the contents of the buffer object. But do not free the associated
180547** memory allocation.
180548*/
180549static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
180550  pBuf->n = 0;
180551}
180552
180553/*
180554** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
180555** the error code in p. If an error has already occurred when this function
180556** is called, it is a no-op.
180557*/
180558static void sqlite3Fts5BufferSet(
180559  int *pRc,
180560  Fts5Buffer *pBuf,
180561  int nData,
180562  const u8 *pData
180563){
180564  pBuf->n = 0;
180565  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
180566}
180567
180568static int sqlite3Fts5PoslistNext64(
180569  const u8 *a, int n,             /* Buffer containing poslist */
180570  int *pi,                        /* IN/OUT: Offset within a[] */
180571  i64 *piOff                      /* IN/OUT: Current offset */
180572){
180573  int i = *pi;
180574  if( i>=n ){
180575    /* EOF */
180576    *piOff = -1;
180577    return 1;
180578  }else{
180579    i64 iOff = *piOff;
180580    int iVal;
180581    fts5FastGetVarint32(a, i, iVal);
180582    if( iVal==1 ){
180583      fts5FastGetVarint32(a, i, iVal);
180584      iOff = ((i64)iVal) << 32;
180585      fts5FastGetVarint32(a, i, iVal);
180586    }
180587    *piOff = iOff + (iVal-2);
180588    *pi = i;
180589    return 0;
180590  }
180591}
180592
180593
180594/*
180595** Advance the iterator object passed as the only argument. Return true
180596** if the iterator reaches EOF, or false otherwise.
180597*/
180598static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
180599  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
180600    pIter->bEof = 1;
180601  }
180602  return pIter->bEof;
180603}
180604
180605static int sqlite3Fts5PoslistReaderInit(
180606  const u8 *a, int n,             /* Poslist buffer to iterate through */
180607  Fts5PoslistReader *pIter        /* Iterator object to initialize */
180608){
180609  memset(pIter, 0, sizeof(*pIter));
180610  pIter->a = a;
180611  pIter->n = n;
180612  sqlite3Fts5PoslistReaderNext(pIter);
180613  return pIter->bEof;
180614}
180615
180616/*
180617** Append position iPos to the position list being accumulated in buffer
180618** pBuf, which must be already be large enough to hold the new data.
180619** The previous position written to this list is *piPrev. *piPrev is set
180620** to iPos before returning.
180621*/
180622static void sqlite3Fts5PoslistSafeAppend(
180623  Fts5Buffer *pBuf,
180624  i64 *piPrev,
180625  i64 iPos
180626){
180627  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
180628  if( (iPos & colmask) != (*piPrev & colmask) ){
180629    pBuf->p[pBuf->n++] = 1;
180630    pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
180631    *piPrev = (iPos & colmask);
180632  }
180633  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
180634  *piPrev = iPos;
180635}
180636
180637static int sqlite3Fts5PoslistWriterAppend(
180638  Fts5Buffer *pBuf,
180639  Fts5PoslistWriter *pWriter,
180640  i64 iPos
180641){
180642  int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
180643  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
180644  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
180645  return SQLITE_OK;
180646}
180647
180648static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
180649  void *pRet = 0;
180650  if( *pRc==SQLITE_OK ){
180651    pRet = sqlite3_malloc(nByte);
180652    if( pRet==0 && nByte>0 ){
180653      *pRc = SQLITE_NOMEM;
180654    }else{
180655      memset(pRet, 0, nByte);
180656    }
180657  }
180658  return pRet;
180659}
180660
180661/*
180662** Return a nul-terminated copy of the string indicated by pIn. If nIn
180663** is non-negative, then it is the length of the string in bytes. Otherwise,
180664** the length of the string is determined using strlen().
180665**
180666** It is the responsibility of the caller to eventually free the returned
180667** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
180668*/
180669static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
180670  char *zRet = 0;
180671  if( *pRc==SQLITE_OK ){
180672    if( nIn<0 ){
180673      nIn = (int)strlen(pIn);
180674    }
180675    zRet = (char*)sqlite3_malloc(nIn+1);
180676    if( zRet ){
180677      memcpy(zRet, pIn, nIn);
180678      zRet[nIn] = '\0';
180679    }else{
180680      *pRc = SQLITE_NOMEM;
180681    }
180682  }
180683  return zRet;
180684}
180685
180686
180687/*
180688** Return true if character 't' may be part of an FTS5 bareword, or false
180689** otherwise. Characters that may be part of barewords:
180690**
180691**   * All non-ASCII characters,
180692**   * The 52 upper and lower case ASCII characters, and
180693**   * The 10 integer ASCII characters.
180694**   * The underscore character "_" (0x5F).
180695**   * The unicode "subsitute" character (0x1A).
180696*/
180697static int sqlite3Fts5IsBareword(char t){
180698  u8 aBareword[128] = {
180699    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
180700    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
180701    0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
180702    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
180703    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
180704    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
180705    0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
180706    1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
180707  };
180708
180709  return (t & 0x80) || aBareword[(int)t];
180710}
180711
180712
180713/*************************************************************************
180714*/
180715typedef struct Fts5TermsetEntry Fts5TermsetEntry;
180716struct Fts5TermsetEntry {
180717  char *pTerm;
180718  int nTerm;
180719  int iIdx;                       /* Index (main or aPrefix[] entry) */
180720  Fts5TermsetEntry *pNext;
180721};
180722
180723struct Fts5Termset {
180724  Fts5TermsetEntry *apHash[512];
180725};
180726
180727static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
180728  int rc = SQLITE_OK;
180729  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
180730  return rc;
180731}
180732
180733static int sqlite3Fts5TermsetAdd(
180734  Fts5Termset *p,
180735  int iIdx,
180736  const char *pTerm, int nTerm,
180737  int *pbPresent
180738){
180739  int rc = SQLITE_OK;
180740  *pbPresent = 0;
180741  if( p ){
180742    int i;
180743    u32 hash = 13;
180744    Fts5TermsetEntry *pEntry;
180745
180746    /* Calculate a hash value for this term. This is the same hash checksum
180747    ** used by the fts5_hash.c module. This is not important for correct
180748    ** operation of the module, but is necessary to ensure that some tests
180749    ** designed to produce hash table collisions really do work.  */
180750    for(i=nTerm-1; i>=0; i--){
180751      hash = (hash << 3) ^ hash ^ pTerm[i];
180752    }
180753    hash = (hash << 3) ^ hash ^ iIdx;
180754    hash = hash % ArraySize(p->apHash);
180755
180756    for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
180757      if( pEntry->iIdx==iIdx
180758          && pEntry->nTerm==nTerm
180759          && memcmp(pEntry->pTerm, pTerm, nTerm)==0
180760      ){
180761        *pbPresent = 1;
180762        break;
180763      }
180764    }
180765
180766    if( pEntry==0 ){
180767      pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
180768      if( pEntry ){
180769        pEntry->pTerm = (char*)&pEntry[1];
180770        pEntry->nTerm = nTerm;
180771        pEntry->iIdx = iIdx;
180772        memcpy(pEntry->pTerm, pTerm, nTerm);
180773        pEntry->pNext = p->apHash[hash];
180774        p->apHash[hash] = pEntry;
180775      }
180776    }
180777  }
180778
180779  return rc;
180780}
180781
180782static void sqlite3Fts5TermsetFree(Fts5Termset *p){
180783  if( p ){
180784    u32 i;
180785    for(i=0; i<ArraySize(p->apHash); i++){
180786      Fts5TermsetEntry *pEntry = p->apHash[i];
180787      while( pEntry ){
180788        Fts5TermsetEntry *pDel = pEntry;
180789        pEntry = pEntry->pNext;
180790        sqlite3_free(pDel);
180791      }
180792    }
180793    sqlite3_free(p);
180794  }
180795}
180796
180797/*
180798** 2014 Jun 09
180799**
180800** The author disclaims copyright to this source code.  In place of
180801** a legal notice, here is a blessing:
180802**
180803**    May you do good and not evil.
180804**    May you find forgiveness for yourself and forgive others.
180805**    May you share freely, never taking more than you give.
180806**
180807******************************************************************************
180808**
180809** This is an SQLite module implementing full-text search.
180810*/
180811
180812
180813/* #include "fts5Int.h" */
180814
180815#define FTS5_DEFAULT_PAGE_SIZE   4050
180816#define FTS5_DEFAULT_AUTOMERGE      4
180817#define FTS5_DEFAULT_USERMERGE      4
180818#define FTS5_DEFAULT_CRISISMERGE   16
180819#define FTS5_DEFAULT_HASHSIZE    (1024*1024)
180820
180821/* Maximum allowed page size */
180822#define FTS5_MAX_PAGE_SIZE (128*1024)
180823
180824static int fts5_iswhitespace(char x){
180825  return (x==' ');
180826}
180827
180828static int fts5_isopenquote(char x){
180829  return (x=='"' || x=='\'' || x=='[' || x=='`');
180830}
180831
180832/*
180833** Argument pIn points to a character that is part of a nul-terminated
180834** string. Return a pointer to the first character following *pIn in
180835** the string that is not a white-space character.
180836*/
180837static const char *fts5ConfigSkipWhitespace(const char *pIn){
180838  const char *p = pIn;
180839  if( p ){
180840    while( fts5_iswhitespace(*p) ){ p++; }
180841  }
180842  return p;
180843}
180844
180845/*
180846** Argument pIn points to a character that is part of a nul-terminated
180847** string. Return a pointer to the first character following *pIn in
180848** the string that is not a "bareword" character.
180849*/
180850static const char *fts5ConfigSkipBareword(const char *pIn){
180851  const char *p = pIn;
180852  while ( sqlite3Fts5IsBareword(*p) ) p++;
180853  if( p==pIn ) p = 0;
180854  return p;
180855}
180856
180857static int fts5_isdigit(char a){
180858  return (a>='0' && a<='9');
180859}
180860
180861
180862
180863static const char *fts5ConfigSkipLiteral(const char *pIn){
180864  const char *p = pIn;
180865  switch( *p ){
180866    case 'n': case 'N':
180867      if( sqlite3_strnicmp("null", p, 4)==0 ){
180868        p = &p[4];
180869      }else{
180870        p = 0;
180871      }
180872      break;
180873
180874    case 'x': case 'X':
180875      p++;
180876      if( *p=='\'' ){
180877        p++;
180878        while( (*p>='a' && *p<='f')
180879            || (*p>='A' && *p<='F')
180880            || (*p>='0' && *p<='9')
180881            ){
180882          p++;
180883        }
180884        if( *p=='\'' && 0==((p-pIn)%2) ){
180885          p++;
180886        }else{
180887          p = 0;
180888        }
180889      }else{
180890        p = 0;
180891      }
180892      break;
180893
180894    case '\'':
180895      p++;
180896      while( p ){
180897        if( *p=='\'' ){
180898          p++;
180899          if( *p!='\'' ) break;
180900        }
180901        p++;
180902        if( *p==0 ) p = 0;
180903      }
180904      break;
180905
180906    default:
180907      /* maybe a number */
180908      if( *p=='+' || *p=='-' ) p++;
180909      while( fts5_isdigit(*p) ) p++;
180910
180911      /* At this point, if the literal was an integer, the parse is
180912      ** finished. Or, if it is a floating point value, it may continue
180913      ** with either a decimal point or an 'E' character. */
180914      if( *p=='.' && fts5_isdigit(p[1]) ){
180915        p += 2;
180916        while( fts5_isdigit(*p) ) p++;
180917      }
180918      if( p==pIn ) p = 0;
180919
180920      break;
180921  }
180922
180923  return p;
180924}
180925
180926/*
180927** The first character of the string pointed to by argument z is guaranteed
180928** to be an open-quote character (see function fts5_isopenquote()).
180929**
180930** This function searches for the corresponding close-quote character within
180931** the string and, if found, dequotes the string in place and adds a new
180932** nul-terminator byte.
180933**
180934** If the close-quote is found, the value returned is the byte offset of
180935** the character immediately following it. Or, if the close-quote is not
180936** found, -1 is returned. If -1 is returned, the buffer is left in an
180937** undefined state.
180938*/
180939static int fts5Dequote(char *z){
180940  char q;
180941  int iIn = 1;
180942  int iOut = 0;
180943  q = z[0];
180944
180945  /* Set stack variable q to the close-quote character */
180946  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
180947  if( q=='[' ) q = ']';
180948
180949  while( ALWAYS(z[iIn]) ){
180950    if( z[iIn]==q ){
180951      if( z[iIn+1]!=q ){
180952        /* Character iIn was the close quote. */
180953        iIn++;
180954        break;
180955      }else{
180956        /* Character iIn and iIn+1 form an escaped quote character. Skip
180957        ** the input cursor past both and copy a single quote character
180958        ** to the output buffer. */
180959        iIn += 2;
180960        z[iOut++] = q;
180961      }
180962    }else{
180963      z[iOut++] = z[iIn++];
180964    }
180965  }
180966
180967  z[iOut] = '\0';
180968  return iIn;
180969}
180970
180971/*
180972** Convert an SQL-style quoted string into a normal string by removing
180973** the quote characters.  The conversion is done in-place.  If the
180974** input does not begin with a quote character, then this routine
180975** is a no-op.
180976**
180977** Examples:
180978**
180979**     "abc"   becomes   abc
180980**     'xyz'   becomes   xyz
180981**     [pqr]   becomes   pqr
180982**     `mno`   becomes   mno
180983*/
180984static void sqlite3Fts5Dequote(char *z){
180985  char quote;                     /* Quote character (if any ) */
180986
180987  assert( 0==fts5_iswhitespace(z[0]) );
180988  quote = z[0];
180989  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
180990    fts5Dequote(z);
180991  }
180992}
180993
180994
180995struct Fts5Enum {
180996  const char *zName;
180997  int eVal;
180998};
180999typedef struct Fts5Enum Fts5Enum;
181000
181001static int fts5ConfigSetEnum(
181002  const Fts5Enum *aEnum,
181003  const char *zEnum,
181004  int *peVal
181005){
181006  int nEnum = (int)strlen(zEnum);
181007  int i;
181008  int iVal = -1;
181009
181010  for(i=0; aEnum[i].zName; i++){
181011    if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
181012      if( iVal>=0 ) return SQLITE_ERROR;
181013      iVal = aEnum[i].eVal;
181014    }
181015  }
181016
181017  *peVal = iVal;
181018  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
181019}
181020
181021/*
181022** Parse a "special" CREATE VIRTUAL TABLE directive and update
181023** configuration object pConfig as appropriate.
181024**
181025** If successful, object pConfig is updated and SQLITE_OK returned. If
181026** an error occurs, an SQLite error code is returned and an error message
181027** may be left in *pzErr. It is the responsibility of the caller to
181028** eventually free any such error message using sqlite3_free().
181029*/
181030static int fts5ConfigParseSpecial(
181031  Fts5Global *pGlobal,
181032  Fts5Config *pConfig,            /* Configuration object to update */
181033  const char *zCmd,               /* Special command to parse */
181034  const char *zArg,               /* Argument to parse */
181035  char **pzErr                    /* OUT: Error message */
181036){
181037  int rc = SQLITE_OK;
181038  int nCmd = (int)strlen(zCmd);
181039  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
181040    const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
181041    const char *p;
181042    int bFirst = 1;
181043    if( pConfig->aPrefix==0 ){
181044      pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
181045      if( rc ) return rc;
181046    }
181047
181048    p = zArg;
181049    while( 1 ){
181050      int nPre = 0;
181051
181052      while( p[0]==' ' ) p++;
181053      if( bFirst==0 && p[0]==',' ){
181054        p++;
181055        while( p[0]==' ' ) p++;
181056      }else if( p[0]=='\0' ){
181057        break;
181058      }
181059      if( p[0]<'0' || p[0]>'9' ){
181060        *pzErr = sqlite3_mprintf("malformed prefix=... directive");
181061        rc = SQLITE_ERROR;
181062        break;
181063      }
181064
181065      if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
181066        *pzErr = sqlite3_mprintf(
181067            "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
181068        );
181069        rc = SQLITE_ERROR;
181070        break;
181071      }
181072
181073      while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
181074        nPre = nPre*10 + (p[0] - '0');
181075        p++;
181076      }
181077
181078      if( nPre<=0 || nPre>=1000 ){
181079        *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
181080        rc = SQLITE_ERROR;
181081        break;
181082      }
181083
181084      pConfig->aPrefix[pConfig->nPrefix] = nPre;
181085      pConfig->nPrefix++;
181086      bFirst = 0;
181087    }
181088    assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
181089    return rc;
181090  }
181091
181092  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
181093    const char *p = (const char*)zArg;
181094    int nArg = (int)strlen(zArg) + 1;
181095    char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
181096    char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
181097    char *pSpace = pDel;
181098
181099    if( azArg && pSpace ){
181100      if( pConfig->pTok ){
181101        *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
181102        rc = SQLITE_ERROR;
181103      }else{
181104        for(nArg=0; p && *p; nArg++){
181105          const char *p2 = fts5ConfigSkipWhitespace(p);
181106          if( *p2=='\'' ){
181107            p = fts5ConfigSkipLiteral(p2);
181108          }else{
181109            p = fts5ConfigSkipBareword(p2);
181110          }
181111          if( p ){
181112            memcpy(pSpace, p2, p-p2);
181113            azArg[nArg] = pSpace;
181114            sqlite3Fts5Dequote(pSpace);
181115            pSpace += (p - p2) + 1;
181116            p = fts5ConfigSkipWhitespace(p);
181117          }
181118        }
181119        if( p==0 ){
181120          *pzErr = sqlite3_mprintf("parse error in tokenize directive");
181121          rc = SQLITE_ERROR;
181122        }else{
181123          rc = sqlite3Fts5GetTokenizer(pGlobal,
181124              (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
181125              pzErr
181126          );
181127        }
181128      }
181129    }
181130
181131    sqlite3_free(azArg);
181132    sqlite3_free(pDel);
181133    return rc;
181134  }
181135
181136  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
181137    if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
181138      *pzErr = sqlite3_mprintf("multiple content=... directives");
181139      rc = SQLITE_ERROR;
181140    }else{
181141      if( zArg[0] ){
181142        pConfig->eContent = FTS5_CONTENT_EXTERNAL;
181143        pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
181144      }else{
181145        pConfig->eContent = FTS5_CONTENT_NONE;
181146      }
181147    }
181148    return rc;
181149  }
181150
181151  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
181152    if( pConfig->zContentRowid ){
181153      *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
181154      rc = SQLITE_ERROR;
181155    }else{
181156      pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
181157    }
181158    return rc;
181159  }
181160
181161  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
181162    if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
181163      *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
181164      rc = SQLITE_ERROR;
181165    }else{
181166      pConfig->bColumnsize = (zArg[0]=='1');
181167    }
181168    return rc;
181169  }
181170
181171  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
181172    const Fts5Enum aDetail[] = {
181173      { "none", FTS5_DETAIL_NONE },
181174      { "full", FTS5_DETAIL_FULL },
181175      { "columns", FTS5_DETAIL_COLUMNS },
181176      { 0, 0 }
181177    };
181178
181179    if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
181180      *pzErr = sqlite3_mprintf("malformed detail=... directive");
181181    }
181182    return rc;
181183  }
181184
181185  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
181186  return SQLITE_ERROR;
181187}
181188
181189/*
181190** Allocate an instance of the default tokenizer ("simple") at
181191** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
181192** code if an error occurs.
181193*/
181194static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
181195  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
181196  return sqlite3Fts5GetTokenizer(
181197      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
181198  );
181199}
181200
181201/*
181202** Gobble up the first bareword or quoted word from the input buffer zIn.
181203** Return a pointer to the character immediately following the last in
181204** the gobbled word if successful, or a NULL pointer otherwise (failed
181205** to find close-quote character).
181206**
181207** Before returning, set pzOut to point to a new buffer containing a
181208** nul-terminated, dequoted copy of the gobbled word. If the word was
181209** quoted, *pbQuoted is also set to 1 before returning.
181210**
181211** If *pRc is other than SQLITE_OK when this function is called, it is
181212** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
181213** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
181214** set if a parse error (failed to find close quote) occurs.
181215*/
181216static const char *fts5ConfigGobbleWord(
181217  int *pRc,                       /* IN/OUT: Error code */
181218  const char *zIn,                /* Buffer to gobble string/bareword from */
181219  char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
181220  int *pbQuoted                   /* OUT: Set to true if dequoting required */
181221){
181222  const char *zRet = 0;
181223
181224  int nIn = (int)strlen(zIn);
181225  char *zOut = sqlite3_malloc(nIn+1);
181226
181227  assert( *pRc==SQLITE_OK );
181228  *pbQuoted = 0;
181229  *pzOut = 0;
181230
181231  if( zOut==0 ){
181232    *pRc = SQLITE_NOMEM;
181233  }else{
181234    memcpy(zOut, zIn, nIn+1);
181235    if( fts5_isopenquote(zOut[0]) ){
181236      int ii = fts5Dequote(zOut);
181237      zRet = &zIn[ii];
181238      *pbQuoted = 1;
181239    }else{
181240      zRet = fts5ConfigSkipBareword(zIn);
181241      if( zRet ){
181242        zOut[zRet-zIn] = '\0';
181243      }
181244    }
181245  }
181246
181247  if( zRet==0 ){
181248    sqlite3_free(zOut);
181249  }else{
181250    *pzOut = zOut;
181251  }
181252
181253  return zRet;
181254}
181255
181256static int fts5ConfigParseColumn(
181257  Fts5Config *p,
181258  char *zCol,
181259  char *zArg,
181260  char **pzErr
181261){
181262  int rc = SQLITE_OK;
181263  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
181264   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
181265  ){
181266    *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
181267    rc = SQLITE_ERROR;
181268  }else if( zArg ){
181269    if( 0==sqlite3_stricmp(zArg, "unindexed") ){
181270      p->abUnindexed[p->nCol] = 1;
181271    }else{
181272      *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
181273      rc = SQLITE_ERROR;
181274    }
181275  }
181276
181277  p->azCol[p->nCol++] = zCol;
181278  return rc;
181279}
181280
181281/*
181282** Populate the Fts5Config.zContentExprlist string.
181283*/
181284static int fts5ConfigMakeExprlist(Fts5Config *p){
181285  int i;
181286  int rc = SQLITE_OK;
181287  Fts5Buffer buf = {0, 0, 0};
181288
181289  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
181290  if( p->eContent!=FTS5_CONTENT_NONE ){
181291    for(i=0; i<p->nCol; i++){
181292      if( p->eContent==FTS5_CONTENT_EXTERNAL ){
181293        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
181294      }else{
181295        sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
181296      }
181297    }
181298  }
181299
181300  assert( p->zContentExprlist==0 );
181301  p->zContentExprlist = (char*)buf.p;
181302  return rc;
181303}
181304
181305/*
181306** Arguments nArg/azArg contain the string arguments passed to the xCreate
181307** or xConnect method of the virtual table. This function attempts to
181308** allocate an instance of Fts5Config containing the results of parsing
181309** those arguments.
181310**
181311** If successful, SQLITE_OK is returned and *ppOut is set to point to the
181312** new Fts5Config object. If an error occurs, an SQLite error code is
181313** returned, *ppOut is set to NULL and an error message may be left in
181314** *pzErr. It is the responsibility of the caller to eventually free any
181315** such error message using sqlite3_free().
181316*/
181317static int sqlite3Fts5ConfigParse(
181318  Fts5Global *pGlobal,
181319  sqlite3 *db,
181320  int nArg,                       /* Number of arguments */
181321  const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
181322  Fts5Config **ppOut,             /* OUT: Results of parse */
181323  char **pzErr                    /* OUT: Error message */
181324){
181325  int rc = SQLITE_OK;             /* Return code */
181326  Fts5Config *pRet;               /* New object to return */
181327  int i;
181328  int nByte;
181329
181330  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
181331  if( pRet==0 ) return SQLITE_NOMEM;
181332  memset(pRet, 0, sizeof(Fts5Config));
181333  pRet->db = db;
181334  pRet->iCookie = -1;
181335
181336  nByte = nArg * (sizeof(char*) + sizeof(u8));
181337  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
181338  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
181339  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
181340  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
181341  pRet->bColumnsize = 1;
181342  pRet->eDetail = FTS5_DETAIL_FULL;
181343#ifdef SQLITE_DEBUG
181344  pRet->bPrefixIndex = 1;
181345#endif
181346  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
181347    *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
181348    rc = SQLITE_ERROR;
181349  }
181350
181351  for(i=3; rc==SQLITE_OK && i<nArg; i++){
181352    const char *zOrig = azArg[i];
181353    const char *z;
181354    char *zOne = 0;
181355    char *zTwo = 0;
181356    int bOption = 0;
181357    int bMustBeCol = 0;
181358
181359    z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
181360    z = fts5ConfigSkipWhitespace(z);
181361    if( z && *z=='=' ){
181362      bOption = 1;
181363      z++;
181364      if( bMustBeCol ) z = 0;
181365    }
181366    z = fts5ConfigSkipWhitespace(z);
181367    if( z && z[0] ){
181368      int bDummy;
181369      z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
181370      if( z && z[0] ) z = 0;
181371    }
181372
181373    if( rc==SQLITE_OK ){
181374      if( z==0 ){
181375        *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
181376        rc = SQLITE_ERROR;
181377      }else{
181378        if( bOption ){
181379          rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
181380        }else{
181381          rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
181382          zOne = 0;
181383        }
181384      }
181385    }
181386
181387    sqlite3_free(zOne);
181388    sqlite3_free(zTwo);
181389  }
181390
181391  /* If a tokenizer= option was successfully parsed, the tokenizer has
181392  ** already been allocated. Otherwise, allocate an instance of the default
181393  ** tokenizer (unicode61) now.  */
181394  if( rc==SQLITE_OK && pRet->pTok==0 ){
181395    rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
181396  }
181397
181398  /* If no zContent option was specified, fill in the default values. */
181399  if( rc==SQLITE_OK && pRet->zContent==0 ){
181400    const char *zTail = 0;
181401    assert( pRet->eContent==FTS5_CONTENT_NORMAL
181402         || pRet->eContent==FTS5_CONTENT_NONE
181403    );
181404    if( pRet->eContent==FTS5_CONTENT_NORMAL ){
181405      zTail = "content";
181406    }else if( pRet->bColumnsize ){
181407      zTail = "docsize";
181408    }
181409
181410    if( zTail ){
181411      pRet->zContent = sqlite3Fts5Mprintf(
181412          &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
181413      );
181414    }
181415  }
181416
181417  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
181418    pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
181419  }
181420
181421  /* Formulate the zContentExprlist text */
181422  if( rc==SQLITE_OK ){
181423    rc = fts5ConfigMakeExprlist(pRet);
181424  }
181425
181426  if( rc!=SQLITE_OK ){
181427    sqlite3Fts5ConfigFree(pRet);
181428    *ppOut = 0;
181429  }
181430  return rc;
181431}
181432
181433/*
181434** Free the configuration object passed as the only argument.
181435*/
181436static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
181437  if( pConfig ){
181438    int i;
181439    if( pConfig->pTok ){
181440      pConfig->pTokApi->xDelete(pConfig->pTok);
181441    }
181442    sqlite3_free(pConfig->zDb);
181443    sqlite3_free(pConfig->zName);
181444    for(i=0; i<pConfig->nCol; i++){
181445      sqlite3_free(pConfig->azCol[i]);
181446    }
181447    sqlite3_free(pConfig->azCol);
181448    sqlite3_free(pConfig->aPrefix);
181449    sqlite3_free(pConfig->zRank);
181450    sqlite3_free(pConfig->zRankArgs);
181451    sqlite3_free(pConfig->zContent);
181452    sqlite3_free(pConfig->zContentRowid);
181453    sqlite3_free(pConfig->zContentExprlist);
181454    sqlite3_free(pConfig);
181455  }
181456}
181457
181458/*
181459** Call sqlite3_declare_vtab() based on the contents of the configuration
181460** object passed as the only argument. Return SQLITE_OK if successful, or
181461** an SQLite error code if an error occurs.
181462*/
181463static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
181464  int i;
181465  int rc = SQLITE_OK;
181466  char *zSql;
181467
181468  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
181469  for(i=0; zSql && i<pConfig->nCol; i++){
181470    const char *zSep = (i==0?"":", ");
181471    zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
181472  }
181473  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
181474      zSql, pConfig->zName, FTS5_RANK_NAME
181475  );
181476
181477  assert( zSql || rc==SQLITE_NOMEM );
181478  if( zSql ){
181479    rc = sqlite3_declare_vtab(pConfig->db, zSql);
181480    sqlite3_free(zSql);
181481  }
181482
181483  return rc;
181484}
181485
181486/*
181487** Tokenize the text passed via the second and third arguments.
181488**
181489** The callback is invoked once for each token in the input text. The
181490** arguments passed to it are, in order:
181491**
181492**     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
181493**     const char *pToken  // Pointer to buffer containing token
181494**     int nToken          // Size of token in bytes
181495**     int iStart          // Byte offset of start of token within input text
181496**     int iEnd            // Byte offset of end of token within input text
181497**     int iPos            // Position of token in input (first token is 0)
181498**
181499** If the callback returns a non-zero value the tokenization is abandoned
181500** and no further callbacks are issued.
181501**
181502** This function returns SQLITE_OK if successful or an SQLite error code
181503** if an error occurs. If the tokenization was abandoned early because
181504** the callback returned SQLITE_DONE, this is not an error and this function
181505** still returns SQLITE_OK. Or, if the tokenization was abandoned early
181506** because the callback returned another non-zero value, it is assumed
181507** to be an SQLite error code and returned to the caller.
181508*/
181509static int sqlite3Fts5Tokenize(
181510  Fts5Config *pConfig,            /* FTS5 Configuration object */
181511  int flags,                      /* FTS5_TOKENIZE_* flags */
181512  const char *pText, int nText,   /* Text to tokenize */
181513  void *pCtx,                     /* Context passed to xToken() */
181514  int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
181515){
181516  if( pText==0 ) return SQLITE_OK;
181517  return pConfig->pTokApi->xTokenize(
181518      pConfig->pTok, pCtx, flags, pText, nText, xToken
181519  );
181520}
181521
181522/*
181523** Argument pIn points to the first character in what is expected to be
181524** a comma-separated list of SQL literals followed by a ')' character.
181525** If it actually is this, return a pointer to the ')'. Otherwise, return
181526** NULL to indicate a parse error.
181527*/
181528static const char *fts5ConfigSkipArgs(const char *pIn){
181529  const char *p = pIn;
181530
181531  while( 1 ){
181532    p = fts5ConfigSkipWhitespace(p);
181533    p = fts5ConfigSkipLiteral(p);
181534    p = fts5ConfigSkipWhitespace(p);
181535    if( p==0 || *p==')' ) break;
181536    if( *p!=',' ){
181537      p = 0;
181538      break;
181539    }
181540    p++;
181541  }
181542
181543  return p;
181544}
181545
181546/*
181547** Parameter zIn contains a rank() function specification. The format of
181548** this is:
181549**
181550**   + Bareword (function name)
181551**   + Open parenthesis - "("
181552**   + Zero or more SQL literals in a comma separated list
181553**   + Close parenthesis - ")"
181554*/
181555static int sqlite3Fts5ConfigParseRank(
181556  const char *zIn,                /* Input string */
181557  char **pzRank,                  /* OUT: Rank function name */
181558  char **pzRankArgs               /* OUT: Rank function arguments */
181559){
181560  const char *p = zIn;
181561  const char *pRank;
181562  char *zRank = 0;
181563  char *zRankArgs = 0;
181564  int rc = SQLITE_OK;
181565
181566  *pzRank = 0;
181567  *pzRankArgs = 0;
181568
181569  if( p==0 ){
181570    rc = SQLITE_ERROR;
181571  }else{
181572    p = fts5ConfigSkipWhitespace(p);
181573    pRank = p;
181574    p = fts5ConfigSkipBareword(p);
181575
181576    if( p ){
181577      zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
181578      if( zRank ) memcpy(zRank, pRank, p-pRank);
181579    }else{
181580      rc = SQLITE_ERROR;
181581    }
181582
181583    if( rc==SQLITE_OK ){
181584      p = fts5ConfigSkipWhitespace(p);
181585      if( *p!='(' ) rc = SQLITE_ERROR;
181586      p++;
181587    }
181588    if( rc==SQLITE_OK ){
181589      const char *pArgs;
181590      p = fts5ConfigSkipWhitespace(p);
181591      pArgs = p;
181592      if( *p!=')' ){
181593        p = fts5ConfigSkipArgs(p);
181594        if( p==0 ){
181595          rc = SQLITE_ERROR;
181596        }else{
181597          zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
181598          if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
181599        }
181600      }
181601    }
181602  }
181603
181604  if( rc!=SQLITE_OK ){
181605    sqlite3_free(zRank);
181606    assert( zRankArgs==0 );
181607  }else{
181608    *pzRank = zRank;
181609    *pzRankArgs = zRankArgs;
181610  }
181611  return rc;
181612}
181613
181614static int sqlite3Fts5ConfigSetValue(
181615  Fts5Config *pConfig,
181616  const char *zKey,
181617  sqlite3_value *pVal,
181618  int *pbBadkey
181619){
181620  int rc = SQLITE_OK;
181621
181622  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
181623    int pgsz = 0;
181624    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181625      pgsz = sqlite3_value_int(pVal);
181626    }
181627    if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
181628      *pbBadkey = 1;
181629    }else{
181630      pConfig->pgsz = pgsz;
181631    }
181632  }
181633
181634  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
181635    int nHashSize = -1;
181636    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181637      nHashSize = sqlite3_value_int(pVal);
181638    }
181639    if( nHashSize<=0 ){
181640      *pbBadkey = 1;
181641    }else{
181642      pConfig->nHashSize = nHashSize;
181643    }
181644  }
181645
181646  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
181647    int nAutomerge = -1;
181648    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181649      nAutomerge = sqlite3_value_int(pVal);
181650    }
181651    if( nAutomerge<0 || nAutomerge>64 ){
181652      *pbBadkey = 1;
181653    }else{
181654      if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
181655      pConfig->nAutomerge = nAutomerge;
181656    }
181657  }
181658
181659  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
181660    int nUsermerge = -1;
181661    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181662      nUsermerge = sqlite3_value_int(pVal);
181663    }
181664    if( nUsermerge<2 || nUsermerge>16 ){
181665      *pbBadkey = 1;
181666    }else{
181667      pConfig->nUsermerge = nUsermerge;
181668    }
181669  }
181670
181671  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
181672    int nCrisisMerge = -1;
181673    if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181674      nCrisisMerge = sqlite3_value_int(pVal);
181675    }
181676    if( nCrisisMerge<0 ){
181677      *pbBadkey = 1;
181678    }else{
181679      if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
181680      pConfig->nCrisisMerge = nCrisisMerge;
181681    }
181682  }
181683
181684  else if( 0==sqlite3_stricmp(zKey, "rank") ){
181685    const char *zIn = (const char*)sqlite3_value_text(pVal);
181686    char *zRank;
181687    char *zRankArgs;
181688    rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
181689    if( rc==SQLITE_OK ){
181690      sqlite3_free(pConfig->zRank);
181691      sqlite3_free(pConfig->zRankArgs);
181692      pConfig->zRank = zRank;
181693      pConfig->zRankArgs = zRankArgs;
181694    }else if( rc==SQLITE_ERROR ){
181695      rc = SQLITE_OK;
181696      *pbBadkey = 1;
181697    }
181698  }else{
181699    *pbBadkey = 1;
181700  }
181701  return rc;
181702}
181703
181704/*
181705** Load the contents of the %_config table into memory.
181706*/
181707static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
181708  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
181709  char *zSql;
181710  sqlite3_stmt *p = 0;
181711  int rc = SQLITE_OK;
181712  int iVersion = 0;
181713
181714  /* Set default values */
181715  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
181716  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
181717  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
181718  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
181719  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
181720
181721  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
181722  if( zSql ){
181723    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
181724    sqlite3_free(zSql);
181725  }
181726
181727  assert( rc==SQLITE_OK || p==0 );
181728  if( rc==SQLITE_OK ){
181729    while( SQLITE_ROW==sqlite3_step(p) ){
181730      const char *zK = (const char*)sqlite3_column_text(p, 0);
181731      sqlite3_value *pVal = sqlite3_column_value(p, 1);
181732      if( 0==sqlite3_stricmp(zK, "version") ){
181733        iVersion = sqlite3_value_int(pVal);
181734      }else{
181735        int bDummy = 0;
181736        sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
181737      }
181738    }
181739    rc = sqlite3_finalize(p);
181740  }
181741
181742  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
181743    rc = SQLITE_ERROR;
181744    if( pConfig->pzErrmsg ){
181745      assert( 0==*pConfig->pzErrmsg );
181746      *pConfig->pzErrmsg = sqlite3_mprintf(
181747          "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
181748          iVersion, FTS5_CURRENT_VERSION
181749      );
181750    }
181751  }
181752
181753  if( rc==SQLITE_OK ){
181754    pConfig->iCookie = iCookie;
181755  }
181756  return rc;
181757}
181758
181759/*
181760** 2014 May 31
181761**
181762** The author disclaims copyright to this source code.  In place of
181763** a legal notice, here is a blessing:
181764**
181765**    May you do good and not evil.
181766**    May you find forgiveness for yourself and forgive others.
181767**    May you share freely, never taking more than you give.
181768**
181769******************************************************************************
181770**
181771*/
181772
181773
181774
181775/* #include "fts5Int.h" */
181776/* #include "fts5parse.h" */
181777
181778/*
181779** All token types in the generated fts5parse.h file are greater than 0.
181780*/
181781#define FTS5_EOF 0
181782
181783#define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
181784
181785typedef struct Fts5ExprTerm Fts5ExprTerm;
181786
181787/*
181788** Functions generated by lemon from fts5parse.y.
181789*/
181790static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
181791static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
181792static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
181793#ifndef NDEBUG
181794/* #include <stdio.h> */
181795static void sqlite3Fts5ParserTrace(FILE*, char*);
181796#endif
181797
181798
181799struct Fts5Expr {
181800  Fts5Index *pIndex;
181801  Fts5Config *pConfig;
181802  Fts5ExprNode *pRoot;
181803  int bDesc;                      /* Iterate in descending rowid order */
181804  int nPhrase;                    /* Number of phrases in expression */
181805  Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
181806};
181807
181808/*
181809** eType:
181810**   Expression node type. Always one of:
181811**
181812**       FTS5_AND                 (nChild, apChild valid)
181813**       FTS5_OR                  (nChild, apChild valid)
181814**       FTS5_NOT                 (nChild, apChild valid)
181815**       FTS5_STRING              (pNear valid)
181816**       FTS5_TERM                (pNear valid)
181817*/
181818struct Fts5ExprNode {
181819  int eType;                      /* Node type */
181820  int bEof;                       /* True at EOF */
181821  int bNomatch;                   /* True if entry is not a match */
181822
181823  /* Next method for this node. */
181824  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
181825
181826  i64 iRowid;                     /* Current rowid */
181827  Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
181828
181829  /* Child nodes. For a NOT node, this array always contains 2 entries. For
181830  ** AND or OR nodes, it contains 2 or more entries.  */
181831  int nChild;                     /* Number of child nodes */
181832  Fts5ExprNode *apChild[1];       /* Array of child nodes */
181833};
181834
181835#define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
181836
181837/*
181838** Invoke the xNext method of an Fts5ExprNode object. This macro should be
181839** used as if it has the same signature as the xNext() methods themselves.
181840*/
181841#define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
181842
181843/*
181844** An instance of the following structure represents a single search term
181845** or term prefix.
181846*/
181847struct Fts5ExprTerm {
181848  int bPrefix;                    /* True for a prefix term */
181849  char *zTerm;                    /* nul-terminated term */
181850  Fts5IndexIter *pIter;           /* Iterator for this term */
181851  Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
181852};
181853
181854/*
181855** A phrase. One or more terms that must appear in a contiguous sequence
181856** within a document for it to match.
181857*/
181858struct Fts5ExprPhrase {
181859  Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
181860  Fts5Buffer poslist;             /* Current position list */
181861  int nTerm;                      /* Number of entries in aTerm[] */
181862  Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
181863};
181864
181865/*
181866** One or more phrases that must appear within a certain token distance of
181867** each other within each matching document.
181868*/
181869struct Fts5ExprNearset {
181870  int nNear;                      /* NEAR parameter */
181871  Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
181872  int nPhrase;                    /* Number of entries in aPhrase[] array */
181873  Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
181874};
181875
181876
181877/*
181878** Parse context.
181879*/
181880struct Fts5Parse {
181881  Fts5Config *pConfig;
181882  char *zErr;
181883  int rc;
181884  int nPhrase;                    /* Size of apPhrase array */
181885  Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
181886  Fts5ExprNode *pExpr;            /* Result of a successful parse */
181887};
181888
181889static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
181890  va_list ap;
181891  va_start(ap, zFmt);
181892  if( pParse->rc==SQLITE_OK ){
181893    pParse->zErr = sqlite3_vmprintf(zFmt, ap);
181894    pParse->rc = SQLITE_ERROR;
181895  }
181896  va_end(ap);
181897}
181898
181899static int fts5ExprIsspace(char t){
181900  return t==' ' || t=='\t' || t=='\n' || t=='\r';
181901}
181902
181903/*
181904** Read the first token from the nul-terminated string at *pz.
181905*/
181906static int fts5ExprGetToken(
181907  Fts5Parse *pParse,
181908  const char **pz,                /* IN/OUT: Pointer into buffer */
181909  Fts5Token *pToken
181910){
181911  const char *z = *pz;
181912  int tok;
181913
181914  /* Skip past any whitespace */
181915  while( fts5ExprIsspace(*z) ) z++;
181916
181917  pToken->p = z;
181918  pToken->n = 1;
181919  switch( *z ){
181920    case '(':  tok = FTS5_LP;    break;
181921    case ')':  tok = FTS5_RP;    break;
181922    case '{':  tok = FTS5_LCP;   break;
181923    case '}':  tok = FTS5_RCP;   break;
181924    case ':':  tok = FTS5_COLON; break;
181925    case ',':  tok = FTS5_COMMA; break;
181926    case '+':  tok = FTS5_PLUS;  break;
181927    case '*':  tok = FTS5_STAR;  break;
181928    case '\0': tok = FTS5_EOF;   break;
181929
181930    case '"': {
181931      const char *z2;
181932      tok = FTS5_STRING;
181933
181934      for(z2=&z[1]; 1; z2++){
181935        if( z2[0]=='"' ){
181936          z2++;
181937          if( z2[0]!='"' ) break;
181938        }
181939        if( z2[0]=='\0' ){
181940          sqlite3Fts5ParseError(pParse, "unterminated string");
181941          return FTS5_EOF;
181942        }
181943      }
181944      pToken->n = (z2 - z);
181945      break;
181946    }
181947
181948    default: {
181949      const char *z2;
181950      if( sqlite3Fts5IsBareword(z[0])==0 ){
181951        sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
181952        return FTS5_EOF;
181953      }
181954      tok = FTS5_STRING;
181955      for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
181956      pToken->n = (z2 - z);
181957      if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
181958      if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
181959      if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
181960      break;
181961    }
181962  }
181963
181964  *pz = &pToken->p[pToken->n];
181965  return tok;
181966}
181967
181968static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
181969static void fts5ParseFree(void *p){ sqlite3_free(p); }
181970
181971static int sqlite3Fts5ExprNew(
181972  Fts5Config *pConfig,            /* FTS5 Configuration */
181973  const char *zExpr,              /* Expression text */
181974  Fts5Expr **ppNew,
181975  char **pzErr
181976){
181977  Fts5Parse sParse;
181978  Fts5Token token;
181979  const char *z = zExpr;
181980  int t;                          /* Next token type */
181981  void *pEngine;
181982  Fts5Expr *pNew;
181983
181984  *ppNew = 0;
181985  *pzErr = 0;
181986  memset(&sParse, 0, sizeof(sParse));
181987  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
181988  if( pEngine==0 ){ return SQLITE_NOMEM; }
181989  sParse.pConfig = pConfig;
181990
181991  do {
181992    t = fts5ExprGetToken(&sParse, &z, &token);
181993    sqlite3Fts5Parser(pEngine, t, token, &sParse);
181994  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
181995  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
181996
181997  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
181998  if( sParse.rc==SQLITE_OK ){
181999    *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
182000    if( pNew==0 ){
182001      sParse.rc = SQLITE_NOMEM;
182002      sqlite3Fts5ParseNodeFree(sParse.pExpr);
182003    }else{
182004      if( !sParse.pExpr ){
182005        const int nByte = sizeof(Fts5ExprNode);
182006        pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
182007        if( pNew->pRoot ){
182008          pNew->pRoot->bEof = 1;
182009        }
182010      }else{
182011        pNew->pRoot = sParse.pExpr;
182012      }
182013      pNew->pIndex = 0;
182014      pNew->pConfig = pConfig;
182015      pNew->apExprPhrase = sParse.apPhrase;
182016      pNew->nPhrase = sParse.nPhrase;
182017      sParse.apPhrase = 0;
182018    }
182019  }else{
182020    sqlite3Fts5ParseNodeFree(sParse.pExpr);
182021  }
182022
182023  sqlite3_free(sParse.apPhrase);
182024  *pzErr = sParse.zErr;
182025  return sParse.rc;
182026}
182027
182028/*
182029** Free the expression node object passed as the only argument.
182030*/
182031static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
182032  if( p ){
182033    int i;
182034    for(i=0; i<p->nChild; i++){
182035      sqlite3Fts5ParseNodeFree(p->apChild[i]);
182036    }
182037    sqlite3Fts5ParseNearsetFree(p->pNear);
182038    sqlite3_free(p);
182039  }
182040}
182041
182042/*
182043** Free the expression object passed as the only argument.
182044*/
182045static void sqlite3Fts5ExprFree(Fts5Expr *p){
182046  if( p ){
182047    sqlite3Fts5ParseNodeFree(p->pRoot);
182048    sqlite3_free(p->apExprPhrase);
182049    sqlite3_free(p);
182050  }
182051}
182052
182053/*
182054** Argument pTerm must be a synonym iterator. Return the current rowid
182055** that it points to.
182056*/
182057static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
182058  i64 iRet = 0;
182059  int bRetValid = 0;
182060  Fts5ExprTerm *p;
182061
182062  assert( pTerm->pSynonym );
182063  assert( bDesc==0 || bDesc==1 );
182064  for(p=pTerm; p; p=p->pSynonym){
182065    if( 0==sqlite3Fts5IterEof(p->pIter) ){
182066      i64 iRowid = p->pIter->iRowid;
182067      if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
182068        iRet = iRowid;
182069        bRetValid = 1;
182070      }
182071    }
182072  }
182073
182074  if( pbEof && bRetValid==0 ) *pbEof = 1;
182075  return iRet;
182076}
182077
182078/*
182079** Argument pTerm must be a synonym iterator.
182080*/
182081static int fts5ExprSynonymList(
182082  Fts5ExprTerm *pTerm,
182083  i64 iRowid,
182084  Fts5Buffer *pBuf,               /* Use this buffer for space if required */
182085  u8 **pa, int *pn
182086){
182087  Fts5PoslistReader aStatic[4];
182088  Fts5PoslistReader *aIter = aStatic;
182089  int nIter = 0;
182090  int nAlloc = 4;
182091  int rc = SQLITE_OK;
182092  Fts5ExprTerm *p;
182093
182094  assert( pTerm->pSynonym );
182095  for(p=pTerm; p; p=p->pSynonym){
182096    Fts5IndexIter *pIter = p->pIter;
182097    if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
182098      if( pIter->nData==0 ) continue;
182099      if( nIter==nAlloc ){
182100        int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
182101        Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
182102        if( aNew==0 ){
182103          rc = SQLITE_NOMEM;
182104          goto synonym_poslist_out;
182105        }
182106        memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
182107        nAlloc = nAlloc*2;
182108        if( aIter!=aStatic ) sqlite3_free(aIter);
182109        aIter = aNew;
182110      }
182111      sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
182112      assert( aIter[nIter].bEof==0 );
182113      nIter++;
182114    }
182115  }
182116
182117  if( nIter==1 ){
182118    *pa = (u8*)aIter[0].a;
182119    *pn = aIter[0].n;
182120  }else{
182121    Fts5PoslistWriter writer = {0};
182122    i64 iPrev = -1;
182123    fts5BufferZero(pBuf);
182124    while( 1 ){
182125      int i;
182126      i64 iMin = FTS5_LARGEST_INT64;
182127      for(i=0; i<nIter; i++){
182128        if( aIter[i].bEof==0 ){
182129          if( aIter[i].iPos==iPrev ){
182130            if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
182131          }
182132          if( aIter[i].iPos<iMin ){
182133            iMin = aIter[i].iPos;
182134          }
182135        }
182136      }
182137      if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
182138      rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
182139      iPrev = iMin;
182140    }
182141    if( rc==SQLITE_OK ){
182142      *pa = pBuf->p;
182143      *pn = pBuf->n;
182144    }
182145  }
182146
182147 synonym_poslist_out:
182148  if( aIter!=aStatic ) sqlite3_free(aIter);
182149  return rc;
182150}
182151
182152
182153/*
182154** All individual term iterators in pPhrase are guaranteed to be valid and
182155** pointing to the same rowid when this function is called. This function
182156** checks if the current rowid really is a match, and if so populates
182157** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
182158** is set to true if this is really a match, or false otherwise.
182159**
182160** SQLITE_OK is returned if an error occurs, or an SQLite error code
182161** otherwise. It is not considered an error code if the current rowid is
182162** not a match.
182163*/
182164static int fts5ExprPhraseIsMatch(
182165  Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
182166  Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
182167  int *pbMatch                    /* OUT: Set to true if really a match */
182168){
182169  Fts5PoslistWriter writer = {0};
182170  Fts5PoslistReader aStatic[4];
182171  Fts5PoslistReader *aIter = aStatic;
182172  int i;
182173  int rc = SQLITE_OK;
182174
182175  fts5BufferZero(&pPhrase->poslist);
182176
182177  /* If the aStatic[] array is not large enough, allocate a large array
182178  ** using sqlite3_malloc(). This approach could be improved upon. */
182179  if( pPhrase->nTerm>ArraySize(aStatic) ){
182180    int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
182181    aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
182182    if( !aIter ) return SQLITE_NOMEM;
182183  }
182184  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
182185
182186  /* Initialize a term iterator for each term in the phrase */
182187  for(i=0; i<pPhrase->nTerm; i++){
182188    Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
182189    int n = 0;
182190    int bFlag = 0;
182191    u8 *a = 0;
182192    if( pTerm->pSynonym ){
182193      Fts5Buffer buf = {0, 0, 0};
182194      rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
182195      if( rc ){
182196        sqlite3_free(a);
182197        goto ismatch_out;
182198      }
182199      if( a==buf.p ) bFlag = 1;
182200    }else{
182201      a = (u8*)pTerm->pIter->pData;
182202      n = pTerm->pIter->nData;
182203    }
182204    sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
182205    aIter[i].bFlag = (u8)bFlag;
182206    if( aIter[i].bEof ) goto ismatch_out;
182207  }
182208
182209  while( 1 ){
182210    int bMatch;
182211    i64 iPos = aIter[0].iPos;
182212    do {
182213      bMatch = 1;
182214      for(i=0; i<pPhrase->nTerm; i++){
182215        Fts5PoslistReader *pPos = &aIter[i];
182216        i64 iAdj = iPos + i;
182217        if( pPos->iPos!=iAdj ){
182218          bMatch = 0;
182219          while( pPos->iPos<iAdj ){
182220            if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
182221          }
182222          if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
182223        }
182224      }
182225    }while( bMatch==0 );
182226
182227    /* Append position iPos to the output */
182228    rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
182229    if( rc!=SQLITE_OK ) goto ismatch_out;
182230
182231    for(i=0; i<pPhrase->nTerm; i++){
182232      if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
182233    }
182234  }
182235
182236 ismatch_out:
182237  *pbMatch = (pPhrase->poslist.n>0);
182238  for(i=0; i<pPhrase->nTerm; i++){
182239    if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
182240  }
182241  if( aIter!=aStatic ) sqlite3_free(aIter);
182242  return rc;
182243}
182244
182245typedef struct Fts5LookaheadReader Fts5LookaheadReader;
182246struct Fts5LookaheadReader {
182247  const u8 *a;                    /* Buffer containing position list */
182248  int n;                          /* Size of buffer a[] in bytes */
182249  int i;                          /* Current offset in position list */
182250  i64 iPos;                       /* Current position */
182251  i64 iLookahead;                 /* Next position */
182252};
182253
182254#define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
182255
182256static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
182257  p->iPos = p->iLookahead;
182258  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
182259    p->iLookahead = FTS5_LOOKAHEAD_EOF;
182260  }
182261  return (p->iPos==FTS5_LOOKAHEAD_EOF);
182262}
182263
182264static int fts5LookaheadReaderInit(
182265  const u8 *a, int n,             /* Buffer to read position list from */
182266  Fts5LookaheadReader *p          /* Iterator object to initialize */
182267){
182268  memset(p, 0, sizeof(Fts5LookaheadReader));
182269  p->a = a;
182270  p->n = n;
182271  fts5LookaheadReaderNext(p);
182272  return fts5LookaheadReaderNext(p);
182273}
182274
182275typedef struct Fts5NearTrimmer Fts5NearTrimmer;
182276struct Fts5NearTrimmer {
182277  Fts5LookaheadReader reader;     /* Input iterator */
182278  Fts5PoslistWriter writer;       /* Writer context */
182279  Fts5Buffer *pOut;               /* Output poslist */
182280};
182281
182282/*
182283** The near-set object passed as the first argument contains more than
182284** one phrase. All phrases currently point to the same row. The
182285** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
182286** tests if the current row contains instances of each phrase sufficiently
182287** close together to meet the NEAR constraint. Non-zero is returned if it
182288** does, or zero otherwise.
182289**
182290** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
182291** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
182292** occurs within this function (*pRc) is set accordingly before returning.
182293** The return value is undefined in both these cases.
182294**
182295** If no error occurs and non-zero (a match) is returned, the position-list
182296** of each phrase object is edited to contain only those entries that
182297** meet the constraint before returning.
182298*/
182299static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
182300  Fts5NearTrimmer aStatic[4];
182301  Fts5NearTrimmer *a = aStatic;
182302  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
182303
182304  int i;
182305  int rc = *pRc;
182306  int bMatch;
182307
182308  assert( pNear->nPhrase>1 );
182309
182310  /* If the aStatic[] array is not large enough, allocate a large array
182311  ** using sqlite3_malloc(). This approach could be improved upon. */
182312  if( pNear->nPhrase>ArraySize(aStatic) ){
182313    int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
182314    a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
182315  }else{
182316    memset(aStatic, 0, sizeof(aStatic));
182317  }
182318  if( rc!=SQLITE_OK ){
182319    *pRc = rc;
182320    return 0;
182321  }
182322
182323  /* Initialize a lookahead iterator for each phrase. After passing the
182324  ** buffer and buffer size to the lookaside-reader init function, zero
182325  ** the phrase poslist buffer. The new poslist for the phrase (containing
182326  ** the same entries as the original with some entries removed on account
182327  ** of the NEAR constraint) is written over the original even as it is
182328  ** being read. This is safe as the entries for the new poslist are a
182329  ** subset of the old, so it is not possible for data yet to be read to
182330  ** be overwritten.  */
182331  for(i=0; i<pNear->nPhrase; i++){
182332    Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
182333    fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
182334    pPoslist->n = 0;
182335    a[i].pOut = pPoslist;
182336  }
182337
182338  while( 1 ){
182339    int iAdv;
182340    i64 iMin;
182341    i64 iMax;
182342
182343    /* This block advances the phrase iterators until they point to a set of
182344    ** entries that together comprise a match.  */
182345    iMax = a[0].reader.iPos;
182346    do {
182347      bMatch = 1;
182348      for(i=0; i<pNear->nPhrase; i++){
182349        Fts5LookaheadReader *pPos = &a[i].reader;
182350        iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
182351        if( pPos->iPos<iMin || pPos->iPos>iMax ){
182352          bMatch = 0;
182353          while( pPos->iPos<iMin ){
182354            if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
182355          }
182356          if( pPos->iPos>iMax ) iMax = pPos->iPos;
182357        }
182358      }
182359    }while( bMatch==0 );
182360
182361    /* Add an entry to each output position list */
182362    for(i=0; i<pNear->nPhrase; i++){
182363      i64 iPos = a[i].reader.iPos;
182364      Fts5PoslistWriter *pWriter = &a[i].writer;
182365      if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
182366        sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
182367      }
182368    }
182369
182370    iAdv = 0;
182371    iMin = a[0].reader.iLookahead;
182372    for(i=0; i<pNear->nPhrase; i++){
182373      if( a[i].reader.iLookahead < iMin ){
182374        iMin = a[i].reader.iLookahead;
182375        iAdv = i;
182376      }
182377    }
182378    if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
182379  }
182380
182381  ismatch_out: {
182382    int bRet = a[0].pOut->n>0;
182383    *pRc = rc;
182384    if( a!=aStatic ) sqlite3_free(a);
182385    return bRet;
182386  }
182387}
182388
182389/*
182390** Advance iterator pIter until it points to a value equal to or laster
182391** than the initial value of *piLast. If this means the iterator points
182392** to a value laster than *piLast, update *piLast to the new lastest value.
182393**
182394** If the iterator reaches EOF, set *pbEof to true before returning. If
182395** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
182396** are set, return a non-zero value. Otherwise, return zero.
182397*/
182398static int fts5ExprAdvanceto(
182399  Fts5IndexIter *pIter,           /* Iterator to advance */
182400  int bDesc,                      /* True if iterator is "rowid DESC" */
182401  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
182402  int *pRc,                       /* OUT: Error code */
182403  int *pbEof                      /* OUT: Set to true if EOF */
182404){
182405  i64 iLast = *piLast;
182406  i64 iRowid;
182407
182408  iRowid = pIter->iRowid;
182409  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
182410    int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
182411    if( rc || sqlite3Fts5IterEof(pIter) ){
182412      *pRc = rc;
182413      *pbEof = 1;
182414      return 1;
182415    }
182416    iRowid = pIter->iRowid;
182417    assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
182418  }
182419  *piLast = iRowid;
182420
182421  return 0;
182422}
182423
182424static int fts5ExprSynonymAdvanceto(
182425  Fts5ExprTerm *pTerm,            /* Term iterator to advance */
182426  int bDesc,                      /* True if iterator is "rowid DESC" */
182427  i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
182428  int *pRc                        /* OUT: Error code */
182429){
182430  int rc = SQLITE_OK;
182431  i64 iLast = *piLast;
182432  Fts5ExprTerm *p;
182433  int bEof = 0;
182434
182435  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
182436    if( sqlite3Fts5IterEof(p->pIter)==0 ){
182437      i64 iRowid = p->pIter->iRowid;
182438      if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
182439        rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
182440      }
182441    }
182442  }
182443
182444  if( rc!=SQLITE_OK ){
182445    *pRc = rc;
182446    bEof = 1;
182447  }else{
182448    *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
182449  }
182450  return bEof;
182451}
182452
182453
182454static int fts5ExprNearTest(
182455  int *pRc,
182456  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
182457  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
182458){
182459  Fts5ExprNearset *pNear = pNode->pNear;
182460  int rc = *pRc;
182461
182462  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
182463    Fts5ExprTerm *pTerm;
182464    Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
182465    pPhrase->poslist.n = 0;
182466    for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
182467      Fts5IndexIter *pIter = pTerm->pIter;
182468      if( sqlite3Fts5IterEof(pIter)==0 ){
182469        if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
182470          pPhrase->poslist.n = 1;
182471        }
182472      }
182473    }
182474    return pPhrase->poslist.n;
182475  }else{
182476    int i;
182477
182478    /* Check that each phrase in the nearset matches the current row.
182479    ** Populate the pPhrase->poslist buffers at the same time. If any
182480    ** phrase is not a match, break out of the loop early.  */
182481    for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
182482      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182483      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
182484        int bMatch = 0;
182485        rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
182486        if( bMatch==0 ) break;
182487      }else{
182488        Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
182489        fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
182490      }
182491    }
182492
182493    *pRc = rc;
182494    if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
182495      return 1;
182496    }
182497    return 0;
182498  }
182499}
182500
182501
182502/*
182503** Initialize all term iterators in the pNear object. If any term is found
182504** to match no documents at all, return immediately without initializing any
182505** further iterators.
182506*/
182507static int fts5ExprNearInitAll(
182508  Fts5Expr *pExpr,
182509  Fts5ExprNode *pNode
182510){
182511  Fts5ExprNearset *pNear = pNode->pNear;
182512  int i, j;
182513  int rc = SQLITE_OK;
182514
182515  assert( pNode->bNomatch==0 );
182516  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
182517    Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182518    for(j=0; j<pPhrase->nTerm; j++){
182519      Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
182520      Fts5ExprTerm *p;
182521      int bEof = 1;
182522
182523      for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
182524        if( p->pIter ){
182525          sqlite3Fts5IterClose(p->pIter);
182526          p->pIter = 0;
182527        }
182528        rc = sqlite3Fts5IndexQuery(
182529            pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
182530            (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
182531            (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
182532            pNear->pColset,
182533            &p->pIter
182534        );
182535        assert( rc==SQLITE_OK || p->pIter==0 );
182536        if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
182537          bEof = 0;
182538        }
182539      }
182540
182541      if( bEof ){
182542        pNode->bEof = 1;
182543        return rc;
182544      }
182545    }
182546  }
182547
182548  return rc;
182549}
182550
182551/*
182552** If pExpr is an ASC iterator, this function returns a value with the
182553** same sign as:
182554**
182555**   (iLhs - iRhs)
182556**
182557** Otherwise, if this is a DESC iterator, the opposite is returned:
182558**
182559**   (iRhs - iLhs)
182560*/
182561static int fts5RowidCmp(
182562  Fts5Expr *pExpr,
182563  i64 iLhs,
182564  i64 iRhs
182565){
182566  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
182567  if( pExpr->bDesc==0 ){
182568    if( iLhs<iRhs ) return -1;
182569    return (iLhs > iRhs);
182570  }else{
182571    if( iLhs>iRhs ) return -1;
182572    return (iLhs < iRhs);
182573  }
182574}
182575
182576static void fts5ExprSetEof(Fts5ExprNode *pNode){
182577  int i;
182578  pNode->bEof = 1;
182579  pNode->bNomatch = 0;
182580  for(i=0; i<pNode->nChild; i++){
182581    fts5ExprSetEof(pNode->apChild[i]);
182582  }
182583}
182584
182585static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
182586  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
182587    Fts5ExprNearset *pNear = pNode->pNear;
182588    int i;
182589    for(i=0; i<pNear->nPhrase; i++){
182590      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182591      pPhrase->poslist.n = 0;
182592    }
182593  }else{
182594    int i;
182595    for(i=0; i<pNode->nChild; i++){
182596      fts5ExprNodeZeroPoslist(pNode->apChild[i]);
182597    }
182598  }
182599}
182600
182601
182602
182603/*
182604** Compare the values currently indicated by the two nodes as follows:
182605**
182606**    res = (*p1) - (*p2)
182607**
182608** Nodes that point to values that come later in the iteration order are
182609** considered to be larger. Nodes at EOF are the largest of all.
182610**
182611** This means that if the iteration order is ASC, then numerically larger
182612** rowids are considered larger. Or if it is the default DESC, numerically
182613** smaller rowids are larger.
182614*/
182615static int fts5NodeCompare(
182616  Fts5Expr *pExpr,
182617  Fts5ExprNode *p1,
182618  Fts5ExprNode *p2
182619){
182620  if( p2->bEof ) return -1;
182621  if( p1->bEof ) return +1;
182622  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
182623}
182624
182625/*
182626** All individual term iterators in pNear are guaranteed to be valid when
182627** this function is called. This function checks if all term iterators
182628** point to the same rowid, and if not, advances them until they do.
182629** If an EOF is reached before this happens, *pbEof is set to true before
182630** returning.
182631**
182632** SQLITE_OK is returned if an error occurs, or an SQLite error code
182633** otherwise. It is not considered an error code if an iterator reaches
182634** EOF.
182635*/
182636static int fts5ExprNodeTest_STRING(
182637  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182638  Fts5ExprNode *pNode
182639){
182640  Fts5ExprNearset *pNear = pNode->pNear;
182641  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
182642  int rc = SQLITE_OK;
182643  i64 iLast;                      /* Lastest rowid any iterator points to */
182644  int i, j;                       /* Phrase and token index, respectively */
182645  int bMatch;                     /* True if all terms are at the same rowid */
182646  const int bDesc = pExpr->bDesc;
182647
182648  /* Check that this node should not be FTS5_TERM */
182649  assert( pNear->nPhrase>1
182650       || pNear->apPhrase[0]->nTerm>1
182651       || pNear->apPhrase[0]->aTerm[0].pSynonym
182652  );
182653
182654  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
182655  ** iterator skips through rowids in the default ascending order, this means
182656  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
182657  ** means the minimum rowid.  */
182658  if( pLeft->aTerm[0].pSynonym ){
182659    iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
182660  }else{
182661    iLast = pLeft->aTerm[0].pIter->iRowid;
182662  }
182663
182664  do {
182665    bMatch = 1;
182666    for(i=0; i<pNear->nPhrase; i++){
182667      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182668      for(j=0; j<pPhrase->nTerm; j++){
182669        Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
182670        if( pTerm->pSynonym ){
182671          i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
182672          if( iRowid==iLast ) continue;
182673          bMatch = 0;
182674          if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
182675            pNode->bNomatch = 0;
182676            pNode->bEof = 1;
182677            return rc;
182678          }
182679        }else{
182680          Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
182681          if( pIter->iRowid==iLast ) continue;
182682          bMatch = 0;
182683          if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
182684            return rc;
182685          }
182686        }
182687      }
182688    }
182689  }while( bMatch==0 );
182690
182691  pNode->iRowid = iLast;
182692  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
182693  assert( pNode->bEof==0 || pNode->bNomatch==0 );
182694
182695  return rc;
182696}
182697
182698/*
182699** Advance the first term iterator in the first phrase of pNear. Set output
182700** variable *pbEof to true if it reaches EOF or if an error occurs.
182701**
182702** Return SQLITE_OK if successful, or an SQLite error code if an error
182703** occurs.
182704*/
182705static int fts5ExprNodeNext_STRING(
182706  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182707  Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
182708  int bFromValid,
182709  i64 iFrom
182710){
182711  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
182712  int rc = SQLITE_OK;
182713
182714  pNode->bNomatch = 0;
182715  if( pTerm->pSynonym ){
182716    int bEof = 1;
182717    Fts5ExprTerm *p;
182718
182719    /* Find the firstest rowid any synonym points to. */
182720    i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
182721
182722    /* Advance each iterator that currently points to iRowid. Or, if iFrom
182723    ** is valid - each iterator that points to a rowid before iFrom.  */
182724    for(p=pTerm; p; p=p->pSynonym){
182725      if( sqlite3Fts5IterEof(p->pIter)==0 ){
182726        i64 ii = p->pIter->iRowid;
182727        if( ii==iRowid
182728         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
182729        ){
182730          if( bFromValid ){
182731            rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
182732          }else{
182733            rc = sqlite3Fts5IterNext(p->pIter);
182734          }
182735          if( rc!=SQLITE_OK ) break;
182736          if( sqlite3Fts5IterEof(p->pIter)==0 ){
182737            bEof = 0;
182738          }
182739        }else{
182740          bEof = 0;
182741        }
182742      }
182743    }
182744
182745    /* Set the EOF flag if either all synonym iterators are at EOF or an
182746    ** error has occurred.  */
182747    pNode->bEof = (rc || bEof);
182748  }else{
182749    Fts5IndexIter *pIter = pTerm->pIter;
182750
182751    assert( Fts5NodeIsString(pNode) );
182752    if( bFromValid ){
182753      rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
182754    }else{
182755      rc = sqlite3Fts5IterNext(pIter);
182756    }
182757
182758    pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
182759  }
182760
182761  if( pNode->bEof==0 ){
182762    assert( rc==SQLITE_OK );
182763    rc = fts5ExprNodeTest_STRING(pExpr, pNode);
182764  }
182765
182766  return rc;
182767}
182768
182769
182770static int fts5ExprNodeTest_TERM(
182771  Fts5Expr *pExpr,                /* Expression that pNear is a part of */
182772  Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
182773){
182774  /* As this "NEAR" object is actually a single phrase that consists
182775  ** of a single term only, grab pointers into the poslist managed by the
182776  ** fts5_index.c iterator object. This is much faster than synthesizing
182777  ** a new poslist the way we have to for more complicated phrase or NEAR
182778  ** expressions.  */
182779  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
182780  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
182781
182782  assert( pNode->eType==FTS5_TERM );
182783  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
182784  assert( pPhrase->aTerm[0].pSynonym==0 );
182785
182786  pPhrase->poslist.n = pIter->nData;
182787  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
182788    pPhrase->poslist.p = (u8*)pIter->pData;
182789  }
182790  pNode->iRowid = pIter->iRowid;
182791  pNode->bNomatch = (pPhrase->poslist.n==0);
182792  return SQLITE_OK;
182793}
182794
182795/*
182796** xNext() method for a node of type FTS5_TERM.
182797*/
182798static int fts5ExprNodeNext_TERM(
182799  Fts5Expr *pExpr,
182800  Fts5ExprNode *pNode,
182801  int bFromValid,
182802  i64 iFrom
182803){
182804  int rc;
182805  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
182806
182807  assert( pNode->bEof==0 );
182808  if( bFromValid ){
182809    rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
182810  }else{
182811    rc = sqlite3Fts5IterNext(pIter);
182812  }
182813  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
182814    rc = fts5ExprNodeTest_TERM(pExpr, pNode);
182815  }else{
182816    pNode->bEof = 1;
182817    pNode->bNomatch = 0;
182818  }
182819  return rc;
182820}
182821
182822static void fts5ExprNodeTest_OR(
182823  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
182824  Fts5ExprNode *pNode             /* Expression node to test */
182825){
182826  Fts5ExprNode *pNext = pNode->apChild[0];
182827  int i;
182828
182829  for(i=1; i<pNode->nChild; i++){
182830    Fts5ExprNode *pChild = pNode->apChild[i];
182831    int cmp = fts5NodeCompare(pExpr, pNext, pChild);
182832    if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
182833      pNext = pChild;
182834    }
182835  }
182836  pNode->iRowid = pNext->iRowid;
182837  pNode->bEof = pNext->bEof;
182838  pNode->bNomatch = pNext->bNomatch;
182839}
182840
182841static int fts5ExprNodeNext_OR(
182842  Fts5Expr *pExpr,
182843  Fts5ExprNode *pNode,
182844  int bFromValid,
182845  i64 iFrom
182846){
182847  int i;
182848  i64 iLast = pNode->iRowid;
182849
182850  for(i=0; i<pNode->nChild; i++){
182851    Fts5ExprNode *p1 = pNode->apChild[i];
182852    assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
182853    if( p1->bEof==0 ){
182854      if( (p1->iRowid==iLast)
182855       || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
182856      ){
182857        int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
182858        if( rc!=SQLITE_OK ) return rc;
182859      }
182860    }
182861  }
182862
182863  fts5ExprNodeTest_OR(pExpr, pNode);
182864  return SQLITE_OK;
182865}
182866
182867/*
182868** Argument pNode is an FTS5_AND node.
182869*/
182870static int fts5ExprNodeTest_AND(
182871  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182872  Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
182873){
182874  int iChild;
182875  i64 iLast = pAnd->iRowid;
182876  int rc = SQLITE_OK;
182877  int bMatch;
182878
182879  assert( pAnd->bEof==0 );
182880  do {
182881    pAnd->bNomatch = 0;
182882    bMatch = 1;
182883    for(iChild=0; iChild<pAnd->nChild; iChild++){
182884      Fts5ExprNode *pChild = pAnd->apChild[iChild];
182885      int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
182886      if( cmp>0 ){
182887        /* Advance pChild until it points to iLast or laster */
182888        rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
182889        if( rc!=SQLITE_OK ) return rc;
182890      }
182891
182892      /* If the child node is now at EOF, so is the parent AND node. Otherwise,
182893      ** the child node is guaranteed to have advanced at least as far as
182894      ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
182895      ** new lastest rowid seen so far.  */
182896      assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
182897      if( pChild->bEof ){
182898        fts5ExprSetEof(pAnd);
182899        bMatch = 1;
182900        break;
182901      }else if( iLast!=pChild->iRowid ){
182902        bMatch = 0;
182903        iLast = pChild->iRowid;
182904      }
182905
182906      if( pChild->bNomatch ){
182907        pAnd->bNomatch = 1;
182908      }
182909    }
182910  }while( bMatch==0 );
182911
182912  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
182913    fts5ExprNodeZeroPoslist(pAnd);
182914  }
182915  pAnd->iRowid = iLast;
182916  return SQLITE_OK;
182917}
182918
182919static int fts5ExprNodeNext_AND(
182920  Fts5Expr *pExpr,
182921  Fts5ExprNode *pNode,
182922  int bFromValid,
182923  i64 iFrom
182924){
182925  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
182926  if( rc==SQLITE_OK ){
182927    rc = fts5ExprNodeTest_AND(pExpr, pNode);
182928  }
182929  return rc;
182930}
182931
182932static int fts5ExprNodeTest_NOT(
182933  Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182934  Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
182935){
182936  int rc = SQLITE_OK;
182937  Fts5ExprNode *p1 = pNode->apChild[0];
182938  Fts5ExprNode *p2 = pNode->apChild[1];
182939  assert( pNode->nChild==2 );
182940
182941  while( rc==SQLITE_OK && p1->bEof==0 ){
182942    int cmp = fts5NodeCompare(pExpr, p1, p2);
182943    if( cmp>0 ){
182944      rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
182945      cmp = fts5NodeCompare(pExpr, p1, p2);
182946    }
182947    assert( rc!=SQLITE_OK || cmp<=0 );
182948    if( cmp || p2->bNomatch ) break;
182949    rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
182950  }
182951  pNode->bEof = p1->bEof;
182952  pNode->bNomatch = p1->bNomatch;
182953  pNode->iRowid = p1->iRowid;
182954  if( p1->bEof ){
182955    fts5ExprNodeZeroPoslist(p2);
182956  }
182957  return rc;
182958}
182959
182960static int fts5ExprNodeNext_NOT(
182961  Fts5Expr *pExpr,
182962  Fts5ExprNode *pNode,
182963  int bFromValid,
182964  i64 iFrom
182965){
182966  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
182967  if( rc==SQLITE_OK ){
182968    rc = fts5ExprNodeTest_NOT(pExpr, pNode);
182969  }
182970  return rc;
182971}
182972
182973/*
182974** If pNode currently points to a match, this function returns SQLITE_OK
182975** without modifying it. Otherwise, pNode is advanced until it does point
182976** to a match or EOF is reached.
182977*/
182978static int fts5ExprNodeTest(
182979  Fts5Expr *pExpr,                /* Expression of which pNode is a part */
182980  Fts5ExprNode *pNode             /* Expression node to test */
182981){
182982  int rc = SQLITE_OK;
182983  if( pNode->bEof==0 ){
182984    switch( pNode->eType ){
182985
182986      case FTS5_STRING: {
182987        rc = fts5ExprNodeTest_STRING(pExpr, pNode);
182988        break;
182989      }
182990
182991      case FTS5_TERM: {
182992        rc = fts5ExprNodeTest_TERM(pExpr, pNode);
182993        break;
182994      }
182995
182996      case FTS5_AND: {
182997        rc = fts5ExprNodeTest_AND(pExpr, pNode);
182998        break;
182999      }
183000
183001      case FTS5_OR: {
183002        fts5ExprNodeTest_OR(pExpr, pNode);
183003        break;
183004      }
183005
183006      default: assert( pNode->eType==FTS5_NOT ); {
183007        rc = fts5ExprNodeTest_NOT(pExpr, pNode);
183008        break;
183009      }
183010    }
183011  }
183012  return rc;
183013}
183014
183015
183016/*
183017** Set node pNode, which is part of expression pExpr, to point to the first
183018** match. If there are no matches, set the Node.bEof flag to indicate EOF.
183019**
183020** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
183021** It is not an error if there are no matches.
183022*/
183023static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
183024  int rc = SQLITE_OK;
183025  pNode->bEof = 0;
183026  pNode->bNomatch = 0;
183027
183028  if( Fts5NodeIsString(pNode) ){
183029    /* Initialize all term iterators in the NEAR object. */
183030    rc = fts5ExprNearInitAll(pExpr, pNode);
183031  }else if( pNode->xNext==0 ){
183032    pNode->bEof = 1;
183033  }else{
183034    int i;
183035    int nEof = 0;
183036    for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
183037      Fts5ExprNode *pChild = pNode->apChild[i];
183038      rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
183039      assert( pChild->bEof==0 || pChild->bEof==1 );
183040      nEof += pChild->bEof;
183041    }
183042    pNode->iRowid = pNode->apChild[0]->iRowid;
183043
183044    switch( pNode->eType ){
183045      case FTS5_AND:
183046        if( nEof>0 ) fts5ExprSetEof(pNode);
183047        break;
183048
183049      case FTS5_OR:
183050        if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
183051        break;
183052
183053      default:
183054        assert( pNode->eType==FTS5_NOT );
183055        pNode->bEof = pNode->apChild[0]->bEof;
183056        break;
183057    }
183058  }
183059
183060  if( rc==SQLITE_OK ){
183061    rc = fts5ExprNodeTest(pExpr, pNode);
183062  }
183063  return rc;
183064}
183065
183066
183067/*
183068** Begin iterating through the set of documents in index pIdx matched by
183069** the MATCH expression passed as the first argument. If the "bDesc"
183070** parameter is passed a non-zero value, iteration is in descending rowid
183071** order. Or, if it is zero, in ascending order.
183072**
183073** If iterating in ascending rowid order (bDesc==0), the first document
183074** visited is that with the smallest rowid that is larger than or equal
183075** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
183076** then the first document visited must have a rowid smaller than or
183077** equal to iFirst.
183078**
183079** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
183080** is not considered an error if the query does not match any documents.
183081*/
183082static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
183083  Fts5ExprNode *pRoot = p->pRoot;
183084  int rc;                         /* Return code */
183085
183086  p->pIndex = pIdx;
183087  p->bDesc = bDesc;
183088  rc = fts5ExprNodeFirst(p, pRoot);
183089
183090  /* If not at EOF but the current rowid occurs earlier than iFirst in
183091  ** the iteration order, move to document iFirst or later. */
183092  if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
183093    rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
183094  }
183095
183096  /* If the iterator is not at a real match, skip forward until it is. */
183097  while( pRoot->bNomatch ){
183098    assert( pRoot->bEof==0 && rc==SQLITE_OK );
183099    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
183100  }
183101  return rc;
183102}
183103
183104/*
183105** Move to the next document
183106**
183107** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
183108** is not considered an error if the query does not match any documents.
183109*/
183110static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
183111  int rc;
183112  Fts5ExprNode *pRoot = p->pRoot;
183113  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
183114  do {
183115    rc = fts5ExprNodeNext(p, pRoot, 0, 0);
183116    assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
183117  }while( pRoot->bNomatch );
183118  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
183119    pRoot->bEof = 1;
183120  }
183121  return rc;
183122}
183123
183124static int sqlite3Fts5ExprEof(Fts5Expr *p){
183125  return p->pRoot->bEof;
183126}
183127
183128static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
183129  return p->pRoot->iRowid;
183130}
183131
183132static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
183133  int rc = SQLITE_OK;
183134  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
183135  return rc;
183136}
183137
183138/*
183139** Free the phrase object passed as the only argument.
183140*/
183141static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
183142  if( pPhrase ){
183143    int i;
183144    for(i=0; i<pPhrase->nTerm; i++){
183145      Fts5ExprTerm *pSyn;
183146      Fts5ExprTerm *pNext;
183147      Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
183148      sqlite3_free(pTerm->zTerm);
183149      sqlite3Fts5IterClose(pTerm->pIter);
183150      for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
183151        pNext = pSyn->pSynonym;
183152        sqlite3Fts5IterClose(pSyn->pIter);
183153        fts5BufferFree((Fts5Buffer*)&pSyn[1]);
183154        sqlite3_free(pSyn);
183155      }
183156    }
183157    if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
183158    sqlite3_free(pPhrase);
183159  }
183160}
183161
183162/*
183163** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
183164** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
183165** appended to it and the results returned.
183166**
183167** If an OOM error occurs, both the pNear and pPhrase objects are freed and
183168** NULL returned.
183169*/
183170static Fts5ExprNearset *sqlite3Fts5ParseNearset(
183171  Fts5Parse *pParse,              /* Parse context */
183172  Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
183173  Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
183174){
183175  const int SZALLOC = 8;
183176  Fts5ExprNearset *pRet = 0;
183177
183178  if( pParse->rc==SQLITE_OK ){
183179    if( pPhrase==0 ){
183180      return pNear;
183181    }
183182    if( pNear==0 ){
183183      int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
183184      pRet = sqlite3_malloc(nByte);
183185      if( pRet==0 ){
183186        pParse->rc = SQLITE_NOMEM;
183187      }else{
183188        memset(pRet, 0, nByte);
183189      }
183190    }else if( (pNear->nPhrase % SZALLOC)==0 ){
183191      int nNew = pNear->nPhrase + SZALLOC;
183192      int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
183193
183194      pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
183195      if( pRet==0 ){
183196        pParse->rc = SQLITE_NOMEM;
183197      }
183198    }else{
183199      pRet = pNear;
183200    }
183201  }
183202
183203  if( pRet==0 ){
183204    assert( pParse->rc!=SQLITE_OK );
183205    sqlite3Fts5ParseNearsetFree(pNear);
183206    sqlite3Fts5ParsePhraseFree(pPhrase);
183207  }else{
183208    if( pRet->nPhrase>0 ){
183209      Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
183210      assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
183211      if( pPhrase->nTerm==0 ){
183212        fts5ExprPhraseFree(pPhrase);
183213        pRet->nPhrase--;
183214        pParse->nPhrase--;
183215        pPhrase = pLast;
183216      }else if( pLast->nTerm==0 ){
183217        fts5ExprPhraseFree(pLast);
183218        pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
183219        pParse->nPhrase--;
183220        pRet->nPhrase--;
183221      }
183222    }
183223    pRet->apPhrase[pRet->nPhrase++] = pPhrase;
183224  }
183225  return pRet;
183226}
183227
183228typedef struct TokenCtx TokenCtx;
183229struct TokenCtx {
183230  Fts5ExprPhrase *pPhrase;
183231  int rc;
183232};
183233
183234/*
183235** Callback for tokenizing terms used by ParseTerm().
183236*/
183237static int fts5ParseTokenize(
183238  void *pContext,                 /* Pointer to Fts5InsertCtx object */
183239  int tflags,                     /* Mask of FTS5_TOKEN_* flags */
183240  const char *pToken,             /* Buffer containing token */
183241  int nToken,                     /* Size of token in bytes */
183242  int iUnused1,                   /* Start offset of token */
183243  int iUnused2                    /* End offset of token */
183244){
183245  int rc = SQLITE_OK;
183246  const int SZALLOC = 8;
183247  TokenCtx *pCtx = (TokenCtx*)pContext;
183248  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
183249
183250  UNUSED_PARAM2(iUnused1, iUnused2);
183251
183252  /* If an error has already occurred, this is a no-op */
183253  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
183254  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
183255
183256  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
183257    Fts5ExprTerm *pSyn;
183258    int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
183259    pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
183260    if( pSyn==0 ){
183261      rc = SQLITE_NOMEM;
183262    }else{
183263      memset(pSyn, 0, nByte);
183264      pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
183265      memcpy(pSyn->zTerm, pToken, nToken);
183266      pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
183267      pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
183268    }
183269  }else{
183270    Fts5ExprTerm *pTerm;
183271    if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
183272      Fts5ExprPhrase *pNew;
183273      int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
183274
183275      pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
183276          sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
183277      );
183278      if( pNew==0 ){
183279        rc = SQLITE_NOMEM;
183280      }else{
183281        if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
183282        pCtx->pPhrase = pPhrase = pNew;
183283        pNew->nTerm = nNew - SZALLOC;
183284      }
183285    }
183286
183287    if( rc==SQLITE_OK ){
183288      pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
183289      memset(pTerm, 0, sizeof(Fts5ExprTerm));
183290      pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
183291    }
183292  }
183293
183294  pCtx->rc = rc;
183295  return rc;
183296}
183297
183298
183299/*
183300** Free the phrase object passed as the only argument.
183301*/
183302static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
183303  fts5ExprPhraseFree(pPhrase);
183304}
183305
183306/*
183307** Free the phrase object passed as the second argument.
183308*/
183309static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
183310  if( pNear ){
183311    int i;
183312    for(i=0; i<pNear->nPhrase; i++){
183313      fts5ExprPhraseFree(pNear->apPhrase[i]);
183314    }
183315    sqlite3_free(pNear->pColset);
183316    sqlite3_free(pNear);
183317  }
183318}
183319
183320static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
183321  assert( pParse->pExpr==0 );
183322  pParse->pExpr = p;
183323}
183324
183325/*
183326** This function is called by the parser to process a string token. The
183327** string may or may not be quoted. In any case it is tokenized and a
183328** phrase object consisting of all tokens returned.
183329*/
183330static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
183331  Fts5Parse *pParse,              /* Parse context */
183332  Fts5ExprPhrase *pAppend,        /* Phrase to append to */
183333  Fts5Token *pToken,              /* String to tokenize */
183334  int bPrefix                     /* True if there is a trailing "*" */
183335){
183336  Fts5Config *pConfig = pParse->pConfig;
183337  TokenCtx sCtx;                  /* Context object passed to callback */
183338  int rc;                         /* Tokenize return code */
183339  char *z = 0;
183340
183341  memset(&sCtx, 0, sizeof(TokenCtx));
183342  sCtx.pPhrase = pAppend;
183343
183344  rc = fts5ParseStringFromToken(pToken, &z);
183345  if( rc==SQLITE_OK ){
183346    int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
183347    int n;
183348    sqlite3Fts5Dequote(z);
183349    n = (int)strlen(z);
183350    rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
183351  }
183352  sqlite3_free(z);
183353  if( rc || (rc = sCtx.rc) ){
183354    pParse->rc = rc;
183355    fts5ExprPhraseFree(sCtx.pPhrase);
183356    sCtx.pPhrase = 0;
183357  }else{
183358
183359    if( pAppend==0 ){
183360      if( (pParse->nPhrase % 8)==0 ){
183361        int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
183362        Fts5ExprPhrase **apNew;
183363        apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
183364        if( apNew==0 ){
183365          pParse->rc = SQLITE_NOMEM;
183366          fts5ExprPhraseFree(sCtx.pPhrase);
183367          return 0;
183368        }
183369        pParse->apPhrase = apNew;
183370      }
183371      pParse->nPhrase++;
183372    }
183373
183374    if( sCtx.pPhrase==0 ){
183375      /* This happens when parsing a token or quoted phrase that contains
183376      ** no token characters at all. (e.g ... MATCH '""'). */
183377      sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
183378    }else if( sCtx.pPhrase->nTerm ){
183379      sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
183380    }
183381    pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
183382  }
183383
183384  return sCtx.pPhrase;
183385}
183386
183387/*
183388** Create a new FTS5 expression by cloning phrase iPhrase of the
183389** expression passed as the second argument.
183390*/
183391static int sqlite3Fts5ExprClonePhrase(
183392  Fts5Expr *pExpr,
183393  int iPhrase,
183394  Fts5Expr **ppNew
183395){
183396  int rc = SQLITE_OK;             /* Return code */
183397  Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
183398  int i;                          /* Used to iterate through phrase terms */
183399  Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
183400  TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
183401
183402  pOrig = pExpr->apExprPhrase[iPhrase];
183403  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
183404  if( rc==SQLITE_OK ){
183405    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
183406        sizeof(Fts5ExprPhrase*));
183407  }
183408  if( rc==SQLITE_OK ){
183409    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
183410        sizeof(Fts5ExprNode));
183411  }
183412  if( rc==SQLITE_OK ){
183413    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
183414        sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
183415  }
183416  if( rc==SQLITE_OK ){
183417    Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
183418    if( pColsetOrig ){
183419      int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
183420      Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
183421      if( pColset ){
183422        memcpy(pColset, pColsetOrig, nByte);
183423      }
183424      pNew->pRoot->pNear->pColset = pColset;
183425    }
183426  }
183427
183428  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
183429    int tflags = 0;
183430    Fts5ExprTerm *p;
183431    for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
183432      const char *zTerm = p->zTerm;
183433      rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
183434          0, 0);
183435      tflags = FTS5_TOKEN_COLOCATED;
183436    }
183437    if( rc==SQLITE_OK ){
183438      sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
183439    }
183440  }
183441
183442  if( rc==SQLITE_OK ){
183443    /* All the allocations succeeded. Put the expression object together. */
183444    pNew->pIndex = pExpr->pIndex;
183445    pNew->pConfig = pExpr->pConfig;
183446    pNew->nPhrase = 1;
183447    pNew->apExprPhrase[0] = sCtx.pPhrase;
183448    pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
183449    pNew->pRoot->pNear->nPhrase = 1;
183450    sCtx.pPhrase->pNode = pNew->pRoot;
183451
183452    if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
183453      pNew->pRoot->eType = FTS5_TERM;
183454      pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
183455    }else{
183456      pNew->pRoot->eType = FTS5_STRING;
183457      pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
183458    }
183459  }else{
183460    sqlite3Fts5ExprFree(pNew);
183461    fts5ExprPhraseFree(sCtx.pPhrase);
183462    pNew = 0;
183463  }
183464
183465  *ppNew = pNew;
183466  return rc;
183467}
183468
183469
183470/*
183471** Token pTok has appeared in a MATCH expression where the NEAR operator
183472** is expected. If token pTok does not contain "NEAR", store an error
183473** in the pParse object.
183474*/
183475static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
183476  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
183477    sqlite3Fts5ParseError(
183478        pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
183479    );
183480  }
183481}
183482
183483static void sqlite3Fts5ParseSetDistance(
183484  Fts5Parse *pParse,
183485  Fts5ExprNearset *pNear,
183486  Fts5Token *p
183487){
183488  if( pNear ){
183489    int nNear = 0;
183490    int i;
183491    if( p->n ){
183492      for(i=0; i<p->n; i++){
183493        char c = (char)p->p[i];
183494        if( c<'0' || c>'9' ){
183495          sqlite3Fts5ParseError(
183496              pParse, "expected integer, got \"%.*s\"", p->n, p->p
183497              );
183498          return;
183499        }
183500        nNear = nNear * 10 + (p->p[i] - '0');
183501      }
183502    }else{
183503      nNear = FTS5_DEFAULT_NEARDIST;
183504    }
183505    pNear->nNear = nNear;
183506  }
183507}
183508
183509/*
183510** The second argument passed to this function may be NULL, or it may be
183511** an existing Fts5Colset object. This function returns a pointer to
183512** a new colset object containing the contents of (p) with new value column
183513** number iCol appended.
183514**
183515** If an OOM error occurs, store an error code in pParse and return NULL.
183516** The old colset object (if any) is not freed in this case.
183517*/
183518static Fts5Colset *fts5ParseColset(
183519  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
183520  Fts5Colset *p,                  /* Existing colset object */
183521  int iCol                        /* New column to add to colset object */
183522){
183523  int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
183524  Fts5Colset *pNew;               /* New colset object to return */
183525
183526  assert( pParse->rc==SQLITE_OK );
183527  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
183528
183529  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
183530  if( pNew==0 ){
183531    pParse->rc = SQLITE_NOMEM;
183532  }else{
183533    int *aiCol = pNew->aiCol;
183534    int i, j;
183535    for(i=0; i<nCol; i++){
183536      if( aiCol[i]==iCol ) return pNew;
183537      if( aiCol[i]>iCol ) break;
183538    }
183539    for(j=nCol; j>i; j--){
183540      aiCol[j] = aiCol[j-1];
183541    }
183542    aiCol[i] = iCol;
183543    pNew->nCol = nCol+1;
183544
183545#ifndef NDEBUG
183546    /* Check that the array is in order and contains no duplicate entries. */
183547    for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
183548#endif
183549  }
183550
183551  return pNew;
183552}
183553
183554static Fts5Colset *sqlite3Fts5ParseColset(
183555  Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
183556  Fts5Colset *pColset,            /* Existing colset object */
183557  Fts5Token *p
183558){
183559  Fts5Colset *pRet = 0;
183560  int iCol;
183561  char *z;                        /* Dequoted copy of token p */
183562
183563  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
183564  if( pParse->rc==SQLITE_OK ){
183565    Fts5Config *pConfig = pParse->pConfig;
183566    sqlite3Fts5Dequote(z);
183567    for(iCol=0; iCol<pConfig->nCol; iCol++){
183568      if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
183569    }
183570    if( iCol==pConfig->nCol ){
183571      sqlite3Fts5ParseError(pParse, "no such column: %s", z);
183572    }else{
183573      pRet = fts5ParseColset(pParse, pColset, iCol);
183574    }
183575    sqlite3_free(z);
183576  }
183577
183578  if( pRet==0 ){
183579    assert( pParse->rc!=SQLITE_OK );
183580    sqlite3_free(pColset);
183581  }
183582
183583  return pRet;
183584}
183585
183586static void sqlite3Fts5ParseSetColset(
183587  Fts5Parse *pParse,
183588  Fts5ExprNearset *pNear,
183589  Fts5Colset *pColset
183590){
183591  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
183592    pParse->rc = SQLITE_ERROR;
183593    pParse->zErr = sqlite3_mprintf(
183594      "fts5: column queries are not supported (detail=none)"
183595    );
183596    sqlite3_free(pColset);
183597    return;
183598  }
183599
183600  if( pNear ){
183601    pNear->pColset = pColset;
183602  }else{
183603    sqlite3_free(pColset);
183604  }
183605}
183606
183607static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
183608  switch( pNode->eType ){
183609    case FTS5_STRING: {
183610      Fts5ExprNearset *pNear = pNode->pNear;
183611      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
183612       && pNear->apPhrase[0]->aTerm[0].pSynonym==0
183613      ){
183614        pNode->eType = FTS5_TERM;
183615        pNode->xNext = fts5ExprNodeNext_TERM;
183616      }else{
183617        pNode->xNext = fts5ExprNodeNext_STRING;
183618      }
183619      break;
183620    };
183621
183622    case FTS5_OR: {
183623      pNode->xNext = fts5ExprNodeNext_OR;
183624      break;
183625    };
183626
183627    case FTS5_AND: {
183628      pNode->xNext = fts5ExprNodeNext_AND;
183629      break;
183630    };
183631
183632    default: assert( pNode->eType==FTS5_NOT ); {
183633      pNode->xNext = fts5ExprNodeNext_NOT;
183634      break;
183635    };
183636  }
183637}
183638
183639static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
183640  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
183641    int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
183642    memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
183643    p->nChild += pSub->nChild;
183644    sqlite3_free(pSub);
183645  }else{
183646    p->apChild[p->nChild++] = pSub;
183647  }
183648}
183649
183650/*
183651** Allocate and return a new expression object. If anything goes wrong (i.e.
183652** OOM error), leave an error code in pParse and return NULL.
183653*/
183654static Fts5ExprNode *sqlite3Fts5ParseNode(
183655  Fts5Parse *pParse,              /* Parse context */
183656  int eType,                      /* FTS5_STRING, AND, OR or NOT */
183657  Fts5ExprNode *pLeft,            /* Left hand child expression */
183658  Fts5ExprNode *pRight,           /* Right hand child expression */
183659  Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
183660){
183661  Fts5ExprNode *pRet = 0;
183662
183663  if( pParse->rc==SQLITE_OK ){
183664    int nChild = 0;               /* Number of children of returned node */
183665    int nByte;                    /* Bytes of space to allocate for this node */
183666
183667    assert( (eType!=FTS5_STRING && !pNear)
183668         || (eType==FTS5_STRING && !pLeft && !pRight)
183669    );
183670    if( eType==FTS5_STRING && pNear==0 ) return 0;
183671    if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
183672    if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
183673
183674    if( eType==FTS5_NOT ){
183675      nChild = 2;
183676    }else if( eType==FTS5_AND || eType==FTS5_OR ){
183677      nChild = 2;
183678      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
183679      if( pRight->eType==eType ) nChild += pRight->nChild-1;
183680    }
183681
183682    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
183683    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
183684
183685    if( pRet ){
183686      pRet->eType = eType;
183687      pRet->pNear = pNear;
183688      fts5ExprAssignXNext(pRet);
183689      if( eType==FTS5_STRING ){
183690        int iPhrase;
183691        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
183692          pNear->apPhrase[iPhrase]->pNode = pRet;
183693          if( pNear->apPhrase[iPhrase]->nTerm==0 ){
183694            pRet->xNext = 0;
183695            pRet->eType = FTS5_EOF;
183696          }
183697        }
183698
183699        if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
183700         && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
183701        ){
183702          assert( pParse->rc==SQLITE_OK );
183703          pParse->rc = SQLITE_ERROR;
183704          assert( pParse->zErr==0 );
183705          pParse->zErr = sqlite3_mprintf(
183706              "fts5: %s queries are not supported (detail!=full)",
183707              pNear->nPhrase==1 ? "phrase": "NEAR"
183708          );
183709          sqlite3_free(pRet);
183710          pRet = 0;
183711        }
183712
183713      }else{
183714        fts5ExprAddChildren(pRet, pLeft);
183715        fts5ExprAddChildren(pRet, pRight);
183716      }
183717    }
183718  }
183719
183720  if( pRet==0 ){
183721    assert( pParse->rc!=SQLITE_OK );
183722    sqlite3Fts5ParseNodeFree(pLeft);
183723    sqlite3Fts5ParseNodeFree(pRight);
183724    sqlite3Fts5ParseNearsetFree(pNear);
183725  }
183726  return pRet;
183727}
183728
183729static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
183730  Fts5Parse *pParse,              /* Parse context */
183731  Fts5ExprNode *pLeft,            /* Left hand child expression */
183732  Fts5ExprNode *pRight            /* Right hand child expression */
183733){
183734  Fts5ExprNode *pRet = 0;
183735  Fts5ExprNode *pPrev;
183736
183737  if( pParse->rc ){
183738    sqlite3Fts5ParseNodeFree(pLeft);
183739    sqlite3Fts5ParseNodeFree(pRight);
183740  }else{
183741
183742    assert( pLeft->eType==FTS5_STRING
183743        || pLeft->eType==FTS5_TERM
183744        || pLeft->eType==FTS5_EOF
183745        || pLeft->eType==FTS5_AND
183746    );
183747    assert( pRight->eType==FTS5_STRING
183748        || pRight->eType==FTS5_TERM
183749        || pRight->eType==FTS5_EOF
183750    );
183751
183752    if( pLeft->eType==FTS5_AND ){
183753      pPrev = pLeft->apChild[pLeft->nChild-1];
183754    }else{
183755      pPrev = pLeft;
183756    }
183757    assert( pPrev->eType==FTS5_STRING
183758        || pPrev->eType==FTS5_TERM
183759        || pPrev->eType==FTS5_EOF
183760        );
183761
183762    if( pRight->eType==FTS5_EOF ){
183763      assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
183764      sqlite3Fts5ParseNodeFree(pRight);
183765      pRet = pLeft;
183766      pParse->nPhrase--;
183767    }
183768    else if( pPrev->eType==FTS5_EOF ){
183769      Fts5ExprPhrase **ap;
183770
183771      if( pPrev==pLeft ){
183772        pRet = pRight;
183773      }else{
183774        pLeft->apChild[pLeft->nChild-1] = pRight;
183775        pRet = pLeft;
183776      }
183777
183778      ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
183779      assert( ap[0]==pPrev->pNear->apPhrase[0] );
183780      memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
183781      pParse->nPhrase--;
183782
183783      sqlite3Fts5ParseNodeFree(pPrev);
183784    }
183785    else{
183786      pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
183787    }
183788  }
183789
183790  return pRet;
183791}
183792
183793static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
183794  int nByte = 0;
183795  Fts5ExprTerm *p;
183796  char *zQuoted;
183797
183798  /* Determine the maximum amount of space required. */
183799  for(p=pTerm; p; p=p->pSynonym){
183800    nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
183801  }
183802  zQuoted = sqlite3_malloc(nByte);
183803
183804  if( zQuoted ){
183805    int i = 0;
183806    for(p=pTerm; p; p=p->pSynonym){
183807      char *zIn = p->zTerm;
183808      zQuoted[i++] = '"';
183809      while( *zIn ){
183810        if( *zIn=='"' ) zQuoted[i++] = '"';
183811        zQuoted[i++] = *zIn++;
183812      }
183813      zQuoted[i++] = '"';
183814      if( p->pSynonym ) zQuoted[i++] = '|';
183815    }
183816    if( pTerm->bPrefix ){
183817      zQuoted[i++] = ' ';
183818      zQuoted[i++] = '*';
183819    }
183820    zQuoted[i++] = '\0';
183821  }
183822  return zQuoted;
183823}
183824
183825static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
183826  char *zNew;
183827  va_list ap;
183828  va_start(ap, zFmt);
183829  zNew = sqlite3_vmprintf(zFmt, ap);
183830  va_end(ap);
183831  if( zApp && zNew ){
183832    char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
183833    sqlite3_free(zNew);
183834    zNew = zNew2;
183835  }
183836  sqlite3_free(zApp);
183837  return zNew;
183838}
183839
183840/*
183841** Compose a tcl-readable representation of expression pExpr. Return a
183842** pointer to a buffer containing that representation. It is the
183843** responsibility of the caller to at some point free the buffer using
183844** sqlite3_free().
183845*/
183846static char *fts5ExprPrintTcl(
183847  Fts5Config *pConfig,
183848  const char *zNearsetCmd,
183849  Fts5ExprNode *pExpr
183850){
183851  char *zRet = 0;
183852  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
183853    Fts5ExprNearset *pNear = pExpr->pNear;
183854    int i;
183855    int iTerm;
183856
183857    zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
183858    if( zRet==0 ) return 0;
183859    if( pNear->pColset ){
183860      int *aiCol = pNear->pColset->aiCol;
183861      int nCol = pNear->pColset->nCol;
183862      if( nCol==1 ){
183863        zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
183864      }else{
183865        zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
183866        for(i=1; i<pNear->pColset->nCol; i++){
183867          zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
183868        }
183869        zRet = fts5PrintfAppend(zRet, "} ");
183870      }
183871      if( zRet==0 ) return 0;
183872    }
183873
183874    if( pNear->nPhrase>1 ){
183875      zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
183876      if( zRet==0 ) return 0;
183877    }
183878
183879    zRet = fts5PrintfAppend(zRet, "--");
183880    if( zRet==0 ) return 0;
183881
183882    for(i=0; i<pNear->nPhrase; i++){
183883      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
183884
183885      zRet = fts5PrintfAppend(zRet, " {");
183886      for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
183887        char *zTerm = pPhrase->aTerm[iTerm].zTerm;
183888        zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
183889        if( pPhrase->aTerm[iTerm].bPrefix ){
183890          zRet = fts5PrintfAppend(zRet, "*");
183891        }
183892      }
183893
183894      if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
183895      if( zRet==0 ) return 0;
183896    }
183897
183898  }else{
183899    char const *zOp = 0;
183900    int i;
183901    switch( pExpr->eType ){
183902      case FTS5_AND: zOp = "AND"; break;
183903      case FTS5_NOT: zOp = "NOT"; break;
183904      default:
183905        assert( pExpr->eType==FTS5_OR );
183906        zOp = "OR";
183907        break;
183908    }
183909
183910    zRet = sqlite3_mprintf("%s", zOp);
183911    for(i=0; zRet && i<pExpr->nChild; i++){
183912      char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
183913      if( !z ){
183914        sqlite3_free(zRet);
183915        zRet = 0;
183916      }else{
183917        zRet = fts5PrintfAppend(zRet, " [%z]", z);
183918      }
183919    }
183920  }
183921
183922  return zRet;
183923}
183924
183925static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
183926  char *zRet = 0;
183927  if( pExpr->eType==0 ){
183928    return sqlite3_mprintf("\"\"");
183929  }else
183930  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
183931    Fts5ExprNearset *pNear = pExpr->pNear;
183932    int i;
183933    int iTerm;
183934
183935    if( pNear->pColset ){
183936      int iCol = pNear->pColset->aiCol[0];
183937      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
183938      if( zRet==0 ) return 0;
183939    }
183940
183941    if( pNear->nPhrase>1 ){
183942      zRet = fts5PrintfAppend(zRet, "NEAR(");
183943      if( zRet==0 ) return 0;
183944    }
183945
183946    for(i=0; i<pNear->nPhrase; i++){
183947      Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
183948      if( i!=0 ){
183949        zRet = fts5PrintfAppend(zRet, " ");
183950        if( zRet==0 ) return 0;
183951      }
183952      for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
183953        char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
183954        if( zTerm ){
183955          zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
183956          sqlite3_free(zTerm);
183957        }
183958        if( zTerm==0 || zRet==0 ){
183959          sqlite3_free(zRet);
183960          return 0;
183961        }
183962      }
183963    }
183964
183965    if( pNear->nPhrase>1 ){
183966      zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
183967      if( zRet==0 ) return 0;
183968    }
183969
183970  }else{
183971    char const *zOp = 0;
183972    int i;
183973
183974    switch( pExpr->eType ){
183975      case FTS5_AND: zOp = " AND "; break;
183976      case FTS5_NOT: zOp = " NOT "; break;
183977      default:
183978        assert( pExpr->eType==FTS5_OR );
183979        zOp = " OR ";
183980        break;
183981    }
183982
183983    for(i=0; i<pExpr->nChild; i++){
183984      char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
183985      if( z==0 ){
183986        sqlite3_free(zRet);
183987        zRet = 0;
183988      }else{
183989        int e = pExpr->apChild[i]->eType;
183990        int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
183991        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
183992            (i==0 ? "" : zOp),
183993            (b?"(":""), z, (b?")":"")
183994        );
183995      }
183996      if( zRet==0 ) break;
183997    }
183998  }
183999
184000  return zRet;
184001}
184002
184003/*
184004** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
184005** and fts5_expr_tcl() (bTcl!=0).
184006*/
184007static void fts5ExprFunction(
184008  sqlite3_context *pCtx,          /* Function call context */
184009  int nArg,                       /* Number of args */
184010  sqlite3_value **apVal,          /* Function arguments */
184011  int bTcl
184012){
184013  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
184014  sqlite3 *db = sqlite3_context_db_handle(pCtx);
184015  const char *zExpr = 0;
184016  char *zErr = 0;
184017  Fts5Expr *pExpr = 0;
184018  int rc;
184019  int i;
184020
184021  const char **azConfig;          /* Array of arguments for Fts5Config */
184022  const char *zNearsetCmd = "nearset";
184023  int nConfig;                    /* Size of azConfig[] */
184024  Fts5Config *pConfig = 0;
184025  int iArg = 1;
184026
184027  if( nArg<1 ){
184028    zErr = sqlite3_mprintf("wrong number of arguments to function %s",
184029        bTcl ? "fts5_expr_tcl" : "fts5_expr"
184030    );
184031    sqlite3_result_error(pCtx, zErr, -1);
184032    sqlite3_free(zErr);
184033    return;
184034  }
184035
184036  if( bTcl && nArg>1 ){
184037    zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
184038    iArg = 2;
184039  }
184040
184041  nConfig = 3 + (nArg-iArg);
184042  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
184043  if( azConfig==0 ){
184044    sqlite3_result_error_nomem(pCtx);
184045    return;
184046  }
184047  azConfig[0] = 0;
184048  azConfig[1] = "main";
184049  azConfig[2] = "tbl";
184050  for(i=3; iArg<nArg; iArg++){
184051    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
184052  }
184053
184054  zExpr = (const char*)sqlite3_value_text(apVal[0]);
184055
184056  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
184057  if( rc==SQLITE_OK ){
184058    rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
184059  }
184060  if( rc==SQLITE_OK ){
184061    char *zText;
184062    if( pExpr->pRoot->xNext==0 ){
184063      zText = sqlite3_mprintf("");
184064    }else if( bTcl ){
184065      zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
184066    }else{
184067      zText = fts5ExprPrint(pConfig, pExpr->pRoot);
184068    }
184069    if( zText==0 ){
184070      rc = SQLITE_NOMEM;
184071    }else{
184072      sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
184073      sqlite3_free(zText);
184074    }
184075  }
184076
184077  if( rc!=SQLITE_OK ){
184078    if( zErr ){
184079      sqlite3_result_error(pCtx, zErr, -1);
184080      sqlite3_free(zErr);
184081    }else{
184082      sqlite3_result_error_code(pCtx, rc);
184083    }
184084  }
184085  sqlite3_free((void *)azConfig);
184086  sqlite3Fts5ConfigFree(pConfig);
184087  sqlite3Fts5ExprFree(pExpr);
184088}
184089
184090static void fts5ExprFunctionHr(
184091  sqlite3_context *pCtx,          /* Function call context */
184092  int nArg,                       /* Number of args */
184093  sqlite3_value **apVal           /* Function arguments */
184094){
184095  fts5ExprFunction(pCtx, nArg, apVal, 0);
184096}
184097static void fts5ExprFunctionTcl(
184098  sqlite3_context *pCtx,          /* Function call context */
184099  int nArg,                       /* Number of args */
184100  sqlite3_value **apVal           /* Function arguments */
184101){
184102  fts5ExprFunction(pCtx, nArg, apVal, 1);
184103}
184104
184105/*
184106** The implementation of an SQLite user-defined-function that accepts a
184107** single integer as an argument. If the integer is an alpha-numeric
184108** unicode code point, 1 is returned. Otherwise 0.
184109*/
184110static void fts5ExprIsAlnum(
184111  sqlite3_context *pCtx,          /* Function call context */
184112  int nArg,                       /* Number of args */
184113  sqlite3_value **apVal           /* Function arguments */
184114){
184115  int iCode;
184116  if( nArg!=1 ){
184117    sqlite3_result_error(pCtx,
184118        "wrong number of arguments to function fts5_isalnum", -1
184119    );
184120    return;
184121  }
184122  iCode = sqlite3_value_int(apVal[0]);
184123  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
184124}
184125
184126static void fts5ExprFold(
184127  sqlite3_context *pCtx,          /* Function call context */
184128  int nArg,                       /* Number of args */
184129  sqlite3_value **apVal           /* Function arguments */
184130){
184131  if( nArg!=1 && nArg!=2 ){
184132    sqlite3_result_error(pCtx,
184133        "wrong number of arguments to function fts5_fold", -1
184134    );
184135  }else{
184136    int iCode;
184137    int bRemoveDiacritics = 0;
184138    iCode = sqlite3_value_int(apVal[0]);
184139    if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
184140    sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
184141  }
184142}
184143
184144/*
184145** This is called during initialization to register the fts5_expr() scalar
184146** UDF with the SQLite handle passed as the only argument.
184147*/
184148static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
184149  struct Fts5ExprFunc {
184150    const char *z;
184151    void (*x)(sqlite3_context*,int,sqlite3_value**);
184152  } aFunc[] = {
184153    { "fts5_expr",     fts5ExprFunctionHr },
184154    { "fts5_expr_tcl", fts5ExprFunctionTcl },
184155    { "fts5_isalnum",  fts5ExprIsAlnum },
184156    { "fts5_fold",     fts5ExprFold },
184157  };
184158  int i;
184159  int rc = SQLITE_OK;
184160  void *pCtx = (void*)pGlobal;
184161
184162  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
184163    struct Fts5ExprFunc *p = &aFunc[i];
184164    rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
184165  }
184166
184167  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
184168#ifndef NDEBUG
184169  (void)sqlite3Fts5ParserTrace;
184170#endif
184171
184172  return rc;
184173}
184174
184175/*
184176** Return the number of phrases in expression pExpr.
184177*/
184178static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
184179  return (pExpr ? pExpr->nPhrase : 0);
184180}
184181
184182/*
184183** Return the number of terms in the iPhrase'th phrase in pExpr.
184184*/
184185static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
184186  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
184187  return pExpr->apExprPhrase[iPhrase]->nTerm;
184188}
184189
184190/*
184191** This function is used to access the current position list for phrase
184192** iPhrase.
184193*/
184194static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
184195  int nRet;
184196  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
184197  Fts5ExprNode *pNode = pPhrase->pNode;
184198  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
184199    *pa = pPhrase->poslist.p;
184200    nRet = pPhrase->poslist.n;
184201  }else{
184202    *pa = 0;
184203    nRet = 0;
184204  }
184205  return nRet;
184206}
184207
184208struct Fts5PoslistPopulator {
184209  Fts5PoslistWriter writer;
184210  int bOk;                        /* True if ok to populate */
184211  int bMiss;
184212};
184213
184214static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
184215  Fts5PoslistPopulator *pRet;
184216  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
184217  if( pRet ){
184218    int i;
184219    memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
184220    for(i=0; i<pExpr->nPhrase; i++){
184221      Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
184222      Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
184223      assert( pExpr->apExprPhrase[i]->nTerm==1 );
184224      if( bLive &&
184225          (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
184226      ){
184227        pRet[i].bMiss = 1;
184228      }else{
184229        pBuf->n = 0;
184230      }
184231    }
184232  }
184233  return pRet;
184234}
184235
184236struct Fts5ExprCtx {
184237  Fts5Expr *pExpr;
184238  Fts5PoslistPopulator *aPopulator;
184239  i64 iOff;
184240};
184241typedef struct Fts5ExprCtx Fts5ExprCtx;
184242
184243/*
184244** TODO: Make this more efficient!
184245*/
184246static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
184247  int i;
184248  for(i=0; i<pColset->nCol; i++){
184249    if( pColset->aiCol[i]==iCol ) return 1;
184250  }
184251  return 0;
184252}
184253
184254static int fts5ExprPopulatePoslistsCb(
184255  void *pCtx,                /* Copy of 2nd argument to xTokenize() */
184256  int tflags,                /* Mask of FTS5_TOKEN_* flags */
184257  const char *pToken,        /* Pointer to buffer containing token */
184258  int nToken,                /* Size of token in bytes */
184259  int iUnused1,              /* Byte offset of token within input text */
184260  int iUnused2               /* Byte offset of end of token within input text */
184261){
184262  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
184263  Fts5Expr *pExpr = p->pExpr;
184264  int i;
184265
184266  UNUSED_PARAM2(iUnused1, iUnused2);
184267
184268  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
184269  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
184270  for(i=0; i<pExpr->nPhrase; i++){
184271    Fts5ExprTerm *pTerm;
184272    if( p->aPopulator[i].bOk==0 ) continue;
184273    for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
184274      int nTerm = (int)strlen(pTerm->zTerm);
184275      if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
184276       && memcmp(pTerm->zTerm, pToken, nTerm)==0
184277      ){
184278        int rc = sqlite3Fts5PoslistWriterAppend(
184279            &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
184280        );
184281        if( rc ) return rc;
184282        break;
184283      }
184284    }
184285  }
184286  return SQLITE_OK;
184287}
184288
184289static int sqlite3Fts5ExprPopulatePoslists(
184290  Fts5Config *pConfig,
184291  Fts5Expr *pExpr,
184292  Fts5PoslistPopulator *aPopulator,
184293  int iCol,
184294  const char *z, int n
184295){
184296  int i;
184297  Fts5ExprCtx sCtx;
184298  sCtx.pExpr = pExpr;
184299  sCtx.aPopulator = aPopulator;
184300  sCtx.iOff = (((i64)iCol) << 32) - 1;
184301
184302  for(i=0; i<pExpr->nPhrase; i++){
184303    Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
184304    Fts5Colset *pColset = pNode->pNear->pColset;
184305    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
184306     || aPopulator[i].bMiss
184307    ){
184308      aPopulator[i].bOk = 0;
184309    }else{
184310      aPopulator[i].bOk = 1;
184311    }
184312  }
184313
184314  return sqlite3Fts5Tokenize(pConfig,
184315      FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
184316  );
184317}
184318
184319static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
184320  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
184321    pNode->pNear->apPhrase[0]->poslist.n = 0;
184322  }else{
184323    int i;
184324    for(i=0; i<pNode->nChild; i++){
184325      fts5ExprClearPoslists(pNode->apChild[i]);
184326    }
184327  }
184328}
184329
184330static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
184331  pNode->iRowid = iRowid;
184332  pNode->bEof = 0;
184333  switch( pNode->eType ){
184334    case FTS5_TERM:
184335    case FTS5_STRING:
184336      return (pNode->pNear->apPhrase[0]->poslist.n>0);
184337
184338    case FTS5_AND: {
184339      int i;
184340      for(i=0; i<pNode->nChild; i++){
184341        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
184342          fts5ExprClearPoslists(pNode);
184343          return 0;
184344        }
184345      }
184346      break;
184347    }
184348
184349    case FTS5_OR: {
184350      int i;
184351      int bRet = 0;
184352      for(i=0; i<pNode->nChild; i++){
184353        if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
184354          bRet = 1;
184355        }
184356      }
184357      return bRet;
184358    }
184359
184360    default: {
184361      assert( pNode->eType==FTS5_NOT );
184362      if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
184363          || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
184364        ){
184365        fts5ExprClearPoslists(pNode);
184366        return 0;
184367      }
184368      break;
184369    }
184370  }
184371  return 1;
184372}
184373
184374static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
184375  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
184376}
184377
184378/*
184379** This function is only called for detail=columns tables.
184380*/
184381static int sqlite3Fts5ExprPhraseCollist(
184382  Fts5Expr *pExpr,
184383  int iPhrase,
184384  const u8 **ppCollist,
184385  int *pnCollist
184386){
184387  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
184388  Fts5ExprNode *pNode = pPhrase->pNode;
184389  int rc = SQLITE_OK;
184390
184391  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
184392  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
184393
184394  if( pNode->bEof==0
184395   && pNode->iRowid==pExpr->pRoot->iRowid
184396   && pPhrase->poslist.n>0
184397  ){
184398    Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
184399    if( pTerm->pSynonym ){
184400      Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
184401      rc = fts5ExprSynonymList(
184402          pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
184403      );
184404    }else{
184405      *ppCollist = pPhrase->aTerm[0].pIter->pData;
184406      *pnCollist = pPhrase->aTerm[0].pIter->nData;
184407    }
184408  }else{
184409    *ppCollist = 0;
184410    *pnCollist = 0;
184411  }
184412
184413  return rc;
184414}
184415
184416
184417/*
184418** 2014 August 11
184419**
184420** The author disclaims copyright to this source code.  In place of
184421** a legal notice, here is a blessing:
184422**
184423**    May you do good and not evil.
184424**    May you find forgiveness for yourself and forgive others.
184425**    May you share freely, never taking more than you give.
184426**
184427******************************************************************************
184428**
184429*/
184430
184431
184432
184433/* #include "fts5Int.h" */
184434
184435typedef struct Fts5HashEntry Fts5HashEntry;
184436
184437/*
184438** This file contains the implementation of an in-memory hash table used
184439** to accumuluate "term -> doclist" content before it is flused to a level-0
184440** segment.
184441*/
184442
184443
184444struct Fts5Hash {
184445  int eDetail;                    /* Copy of Fts5Config.eDetail */
184446  int *pnByte;                    /* Pointer to bytes counter */
184447  int nEntry;                     /* Number of entries currently in hash */
184448  int nSlot;                      /* Size of aSlot[] array */
184449  Fts5HashEntry *pScan;           /* Current ordered scan item */
184450  Fts5HashEntry **aSlot;          /* Array of hash slots */
184451};
184452
184453/*
184454** Each entry in the hash table is represented by an object of the
184455** following type. Each object, its key (zKey[]) and its current data
184456** are stored in a single memory allocation. The position list data
184457** immediately follows the key data in memory.
184458**
184459** The data that follows the key is in a similar, but not identical format
184460** to the doclist data stored in the database. It is:
184461**
184462**   * Rowid, as a varint
184463**   * Position list, without 0x00 terminator.
184464**   * Size of previous position list and rowid, as a 4 byte
184465**     big-endian integer.
184466**
184467** iRowidOff:
184468**   Offset of last rowid written to data area. Relative to first byte of
184469**   structure.
184470**
184471** nData:
184472**   Bytes of data written since iRowidOff.
184473*/
184474struct Fts5HashEntry {
184475  Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
184476  Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
184477
184478  int nAlloc;                     /* Total size of allocation */
184479  int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
184480  int nData;                      /* Total bytes of data (incl. structure) */
184481  int nKey;                       /* Length of zKey[] in bytes */
184482  u8 bDel;                        /* Set delete-flag @ iSzPoslist */
184483  u8 bContent;                    /* Set content-flag (detail=none mode) */
184484  i16 iCol;                       /* Column of last value written */
184485  int iPos;                       /* Position of last value written */
184486  i64 iRowid;                     /* Rowid of last value written */
184487  char zKey[8];                   /* Nul-terminated entry key */
184488};
184489
184490/*
184491** Size of Fts5HashEntry without the zKey[] array.
184492*/
184493#define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
184494
184495
184496
184497/*
184498** Allocate a new hash table.
184499*/
184500static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
184501  int rc = SQLITE_OK;
184502  Fts5Hash *pNew;
184503
184504  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
184505  if( pNew==0 ){
184506    rc = SQLITE_NOMEM;
184507  }else{
184508    int nByte;
184509    memset(pNew, 0, sizeof(Fts5Hash));
184510    pNew->pnByte = pnByte;
184511    pNew->eDetail = pConfig->eDetail;
184512
184513    pNew->nSlot = 1024;
184514    nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
184515    pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
184516    if( pNew->aSlot==0 ){
184517      sqlite3_free(pNew);
184518      *ppNew = 0;
184519      rc = SQLITE_NOMEM;
184520    }else{
184521      memset(pNew->aSlot, 0, nByte);
184522    }
184523  }
184524  return rc;
184525}
184526
184527/*
184528** Free a hash table object.
184529*/
184530static void sqlite3Fts5HashFree(Fts5Hash *pHash){
184531  if( pHash ){
184532    sqlite3Fts5HashClear(pHash);
184533    sqlite3_free(pHash->aSlot);
184534    sqlite3_free(pHash);
184535  }
184536}
184537
184538/*
184539** Empty (but do not delete) a hash table.
184540*/
184541static void sqlite3Fts5HashClear(Fts5Hash *pHash){
184542  int i;
184543  for(i=0; i<pHash->nSlot; i++){
184544    Fts5HashEntry *pNext;
184545    Fts5HashEntry *pSlot;
184546    for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
184547      pNext = pSlot->pHashNext;
184548      sqlite3_free(pSlot);
184549    }
184550  }
184551  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
184552  pHash->nEntry = 0;
184553}
184554
184555static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
184556  int i;
184557  unsigned int h = 13;
184558  for(i=n-1; i>=0; i--){
184559    h = (h << 3) ^ h ^ p[i];
184560  }
184561  return (h % nSlot);
184562}
184563
184564static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
184565  int i;
184566  unsigned int h = 13;
184567  for(i=n-1; i>=0; i--){
184568    h = (h << 3) ^ h ^ p[i];
184569  }
184570  h = (h << 3) ^ h ^ b;
184571  return (h % nSlot);
184572}
184573
184574/*
184575** Resize the hash table by doubling the number of slots.
184576*/
184577static int fts5HashResize(Fts5Hash *pHash){
184578  int nNew = pHash->nSlot*2;
184579  int i;
184580  Fts5HashEntry **apNew;
184581  Fts5HashEntry **apOld = pHash->aSlot;
184582
184583  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
184584  if( !apNew ) return SQLITE_NOMEM;
184585  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
184586
184587  for(i=0; i<pHash->nSlot; i++){
184588    while( apOld[i] ){
184589      int iHash;
184590      Fts5HashEntry *p = apOld[i];
184591      apOld[i] = p->pHashNext;
184592      iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
184593      p->pHashNext = apNew[iHash];
184594      apNew[iHash] = p;
184595    }
184596  }
184597
184598  sqlite3_free(apOld);
184599  pHash->nSlot = nNew;
184600  pHash->aSlot = apNew;
184601  return SQLITE_OK;
184602}
184603
184604static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
184605  if( p->iSzPoslist ){
184606    u8 *pPtr = (u8*)p;
184607    if( pHash->eDetail==FTS5_DETAIL_NONE ){
184608      assert( p->nData==p->iSzPoslist );
184609      if( p->bDel ){
184610        pPtr[p->nData++] = 0x00;
184611        if( p->bContent ){
184612          pPtr[p->nData++] = 0x00;
184613        }
184614      }
184615    }else{
184616      int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
184617      int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
184618
184619      assert( p->bDel==0 || p->bDel==1 );
184620      if( nPos<=127 ){
184621        pPtr[p->iSzPoslist] = (u8)nPos;
184622      }else{
184623        int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
184624        memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
184625        sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
184626        p->nData += (nByte-1);
184627      }
184628    }
184629
184630    p->iSzPoslist = 0;
184631    p->bDel = 0;
184632    p->bContent = 0;
184633  }
184634}
184635
184636/*
184637** Add an entry to the in-memory hash table. The key is the concatenation
184638** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
184639**
184640**     (bByte || pToken) -> (iRowid,iCol,iPos)
184641**
184642** Or, if iCol is negative, then the value is a delete marker.
184643*/
184644static int sqlite3Fts5HashWrite(
184645  Fts5Hash *pHash,
184646  i64 iRowid,                     /* Rowid for this entry */
184647  int iCol,                       /* Column token appears in (-ve -> delete) */
184648  int iPos,                       /* Position of token within column */
184649  char bByte,                     /* First byte of token */
184650  const char *pToken, int nToken  /* Token to add or remove to or from index */
184651){
184652  unsigned int iHash;
184653  Fts5HashEntry *p;
184654  u8 *pPtr;
184655  int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
184656  int bNew;                       /* If non-delete entry should be written */
184657
184658  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
184659
184660  /* Attempt to locate an existing hash entry */
184661  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
184662  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
184663    if( p->zKey[0]==bByte
184664     && p->nKey==nToken
184665     && memcmp(&p->zKey[1], pToken, nToken)==0
184666    ){
184667      break;
184668    }
184669  }
184670
184671  /* If an existing hash entry cannot be found, create a new one. */
184672  if( p==0 ){
184673    /* Figure out how much space to allocate */
184674    int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
184675    if( nByte<128 ) nByte = 128;
184676
184677    /* Grow the Fts5Hash.aSlot[] array if necessary. */
184678    if( (pHash->nEntry*2)>=pHash->nSlot ){
184679      int rc = fts5HashResize(pHash);
184680      if( rc!=SQLITE_OK ) return rc;
184681      iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
184682    }
184683
184684    /* Allocate new Fts5HashEntry and add it to the hash table. */
184685    p = (Fts5HashEntry*)sqlite3_malloc(nByte);
184686    if( !p ) return SQLITE_NOMEM;
184687    memset(p, 0, FTS5_HASHENTRYSIZE);
184688    p->nAlloc = nByte;
184689    p->zKey[0] = bByte;
184690    memcpy(&p->zKey[1], pToken, nToken);
184691    assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
184692    p->nKey = nToken;
184693    p->zKey[nToken+1] = '\0';
184694    p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
184695    p->pHashNext = pHash->aSlot[iHash];
184696    pHash->aSlot[iHash] = p;
184697    pHash->nEntry++;
184698
184699    /* Add the first rowid field to the hash-entry */
184700    p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
184701    p->iRowid = iRowid;
184702
184703    p->iSzPoslist = p->nData;
184704    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
184705      p->nData += 1;
184706      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
184707    }
184708
184709    nIncr += p->nData;
184710  }else{
184711
184712    /* Appending to an existing hash-entry. Check that there is enough
184713    ** space to append the largest possible new entry. Worst case scenario
184714    ** is:
184715    **
184716    **     + 9 bytes for a new rowid,
184717    **     + 4 byte reserved for the "poslist size" varint.
184718    **     + 1 byte for a "new column" byte,
184719    **     + 3 bytes for a new column number (16-bit max) as a varint,
184720    **     + 5 bytes for the new position offset (32-bit max).
184721    */
184722    if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
184723      int nNew = p->nAlloc * 2;
184724      Fts5HashEntry *pNew;
184725      Fts5HashEntry **pp;
184726      pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
184727      if( pNew==0 ) return SQLITE_NOMEM;
184728      pNew->nAlloc = nNew;
184729      for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
184730      *pp = pNew;
184731      p = pNew;
184732    }
184733    nIncr -= p->nData;
184734  }
184735  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
184736
184737  pPtr = (u8*)p;
184738
184739  /* If this is a new rowid, append the 4-byte size field for the previous
184740  ** entry, and the new rowid for this entry.  */
184741  if( iRowid!=p->iRowid ){
184742    fts5HashAddPoslistSize(pHash, p);
184743    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
184744    p->iRowid = iRowid;
184745    bNew = 1;
184746    p->iSzPoslist = p->nData;
184747    if( pHash->eDetail!=FTS5_DETAIL_NONE ){
184748      p->nData += 1;
184749      p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
184750      p->iPos = 0;
184751    }
184752  }
184753
184754  if( iCol>=0 ){
184755    if( pHash->eDetail==FTS5_DETAIL_NONE ){
184756      p->bContent = 1;
184757    }else{
184758      /* Append a new column value, if necessary */
184759      assert( iCol>=p->iCol );
184760      if( iCol!=p->iCol ){
184761        if( pHash->eDetail==FTS5_DETAIL_FULL ){
184762          pPtr[p->nData++] = 0x01;
184763          p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
184764          p->iCol = (i16)iCol;
184765          p->iPos = 0;
184766        }else{
184767          bNew = 1;
184768          p->iCol = (i16)(iPos = iCol);
184769        }
184770      }
184771
184772      /* Append the new position offset, if necessary */
184773      if( bNew ){
184774        p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
184775        p->iPos = iPos;
184776      }
184777    }
184778  }else{
184779    /* This is a delete. Set the delete flag. */
184780    p->bDel = 1;
184781  }
184782
184783  nIncr += p->nData;
184784  *pHash->pnByte += nIncr;
184785  return SQLITE_OK;
184786}
184787
184788
184789/*
184790** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
184791** each sorted in key order. This function merges the two lists into a
184792** single list and returns a pointer to its first element.
184793*/
184794static Fts5HashEntry *fts5HashEntryMerge(
184795  Fts5HashEntry *pLeft,
184796  Fts5HashEntry *pRight
184797){
184798  Fts5HashEntry *p1 = pLeft;
184799  Fts5HashEntry *p2 = pRight;
184800  Fts5HashEntry *pRet = 0;
184801  Fts5HashEntry **ppOut = &pRet;
184802
184803  while( p1 || p2 ){
184804    if( p1==0 ){
184805      *ppOut = p2;
184806      p2 = 0;
184807    }else if( p2==0 ){
184808      *ppOut = p1;
184809      p1 = 0;
184810    }else{
184811      int i = 0;
184812      while( p1->zKey[i]==p2->zKey[i] ) i++;
184813
184814      if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
184815        /* p2 is smaller */
184816        *ppOut = p2;
184817        ppOut = &p2->pScanNext;
184818        p2 = p2->pScanNext;
184819      }else{
184820        /* p1 is smaller */
184821        *ppOut = p1;
184822        ppOut = &p1->pScanNext;
184823        p1 = p1->pScanNext;
184824      }
184825      *ppOut = 0;
184826    }
184827  }
184828
184829  return pRet;
184830}
184831
184832/*
184833** Extract all tokens from hash table iHash and link them into a list
184834** in sorted order. The hash table is cleared before returning. It is
184835** the responsibility of the caller to free the elements of the returned
184836** list.
184837*/
184838static int fts5HashEntrySort(
184839  Fts5Hash *pHash,
184840  const char *pTerm, int nTerm,   /* Query prefix, if any */
184841  Fts5HashEntry **ppSorted
184842){
184843  const int nMergeSlot = 32;
184844  Fts5HashEntry **ap;
184845  Fts5HashEntry *pList;
184846  int iSlot;
184847  int i;
184848
184849  *ppSorted = 0;
184850  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
184851  if( !ap ) return SQLITE_NOMEM;
184852  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
184853
184854  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
184855    Fts5HashEntry *pIter;
184856    for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
184857      if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
184858        Fts5HashEntry *pEntry = pIter;
184859        pEntry->pScanNext = 0;
184860        for(i=0; ap[i]; i++){
184861          pEntry = fts5HashEntryMerge(pEntry, ap[i]);
184862          ap[i] = 0;
184863        }
184864        ap[i] = pEntry;
184865      }
184866    }
184867  }
184868
184869  pList = 0;
184870  for(i=0; i<nMergeSlot; i++){
184871    pList = fts5HashEntryMerge(pList, ap[i]);
184872  }
184873
184874  pHash->nEntry = 0;
184875  sqlite3_free(ap);
184876  *ppSorted = pList;
184877  return SQLITE_OK;
184878}
184879
184880/*
184881** Query the hash table for a doclist associated with term pTerm/nTerm.
184882*/
184883static int sqlite3Fts5HashQuery(
184884  Fts5Hash *pHash,                /* Hash table to query */
184885  const char *pTerm, int nTerm,   /* Query term */
184886  const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
184887  int *pnDoclist                  /* OUT: Size of doclist in bytes */
184888){
184889  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
184890  Fts5HashEntry *p;
184891
184892  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
184893    if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
184894  }
184895
184896  if( p ){
184897    fts5HashAddPoslistSize(pHash, p);
184898    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
184899    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
184900  }else{
184901    *ppDoclist = 0;
184902    *pnDoclist = 0;
184903  }
184904
184905  return SQLITE_OK;
184906}
184907
184908static int sqlite3Fts5HashScanInit(
184909  Fts5Hash *p,                    /* Hash table to query */
184910  const char *pTerm, int nTerm    /* Query prefix */
184911){
184912  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
184913}
184914
184915static void sqlite3Fts5HashScanNext(Fts5Hash *p){
184916  assert( !sqlite3Fts5HashScanEof(p) );
184917  p->pScan = p->pScan->pScanNext;
184918}
184919
184920static int sqlite3Fts5HashScanEof(Fts5Hash *p){
184921  return (p->pScan==0);
184922}
184923
184924static void sqlite3Fts5HashScanEntry(
184925  Fts5Hash *pHash,
184926  const char **pzTerm,            /* OUT: term (nul-terminated) */
184927  const u8 **ppDoclist,           /* OUT: pointer to doclist */
184928  int *pnDoclist                  /* OUT: size of doclist in bytes */
184929){
184930  Fts5HashEntry *p;
184931  if( (p = pHash->pScan) ){
184932    int nTerm = (int)strlen(p->zKey);
184933    fts5HashAddPoslistSize(pHash, p);
184934    *pzTerm = p->zKey;
184935    *ppDoclist = (const u8*)&p->zKey[nTerm+1];
184936    *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
184937  }else{
184938    *pzTerm = 0;
184939    *ppDoclist = 0;
184940    *pnDoclist = 0;
184941  }
184942}
184943
184944
184945/*
184946** 2014 May 31
184947**
184948** The author disclaims copyright to this source code.  In place of
184949** a legal notice, here is a blessing:
184950**
184951**    May you do good and not evil.
184952**    May you find forgiveness for yourself and forgive others.
184953**    May you share freely, never taking more than you give.
184954**
184955******************************************************************************
184956**
184957** Low level access to the FTS index stored in the database file. The
184958** routines in this file file implement all read and write access to the
184959** %_data table. Other parts of the system access this functionality via
184960** the interface defined in fts5Int.h.
184961*/
184962
184963
184964/* #include "fts5Int.h" */
184965
184966/*
184967** Overview:
184968**
184969** The %_data table contains all the FTS indexes for an FTS5 virtual table.
184970** As well as the main term index, there may be up to 31 prefix indexes.
184971** The format is similar to FTS3/4, except that:
184972**
184973**   * all segment b-tree leaf data is stored in fixed size page records
184974**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
184975**     taken to ensure it is possible to iterate in either direction through
184976**     the entries in a doclist, or to seek to a specific entry within a
184977**     doclist, without loading it into memory.
184978**
184979**   * large doclists that span many pages have associated "doclist index"
184980**     records that contain a copy of the first rowid on each page spanned by
184981**     the doclist. This is used to speed up seek operations, and merges of
184982**     large doclists with very small doclists.
184983**
184984**   * extra fields in the "structure record" record the state of ongoing
184985**     incremental merge operations.
184986**
184987*/
184988
184989
184990#define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
184991#define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
184992
184993#define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
184994
184995#define FTS5_MAIN_PREFIX '0'
184996
184997#if FTS5_MAX_PREFIX_INDEXES > 31
184998# error "FTS5_MAX_PREFIX_INDEXES is too large"
184999#endif
185000
185001/*
185002** Details:
185003**
185004** The %_data table managed by this module,
185005**
185006**     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
185007**
185008** , contains the following 5 types of records. See the comments surrounding
185009** the FTS5_*_ROWID macros below for a description of how %_data rowids are
185010** assigned to each fo them.
185011**
185012** 1. Structure Records:
185013**
185014**   The set of segments that make up an index - the index structure - are
185015**   recorded in a single record within the %_data table. The record consists
185016**   of a single 32-bit configuration cookie value followed by a list of
185017**   SQLite varints. If the FTS table features more than one index (because
185018**   there are one or more prefix indexes), it is guaranteed that all share
185019**   the same cookie value.
185020**
185021**   Immediately following the configuration cookie, the record begins with
185022**   three varints:
185023**
185024**     + number of levels,
185025**     + total number of segments on all levels,
185026**     + value of write counter.
185027**
185028**   Then, for each level from 0 to nMax:
185029**
185030**     + number of input segments in ongoing merge.
185031**     + total number of segments in level.
185032**     + for each segment from oldest to newest:
185033**         + segment id (always > 0)
185034**         + first leaf page number (often 1, always greater than 0)
185035**         + final leaf page number
185036**
185037** 2. The Averages Record:
185038**
185039**   A single record within the %_data table. The data is a list of varints.
185040**   The first value is the number of rows in the index. Then, for each column
185041**   from left to right, the total number of tokens in the column for all
185042**   rows of the table.
185043**
185044** 3. Segment leaves:
185045**
185046**   TERM/DOCLIST FORMAT:
185047**
185048**     Most of each segment leaf is taken up by term/doclist data. The
185049**     general format of term/doclist, starting with the first term
185050**     on the leaf page, is:
185051**
185052**         varint : size of first term
185053**         blob:    first term data
185054**         doclist: first doclist
185055**         zero-or-more {
185056**           varint:  number of bytes in common with previous term
185057**           varint:  number of bytes of new term data (nNew)
185058**           blob:    nNew bytes of new term data
185059**           doclist: next doclist
185060**         }
185061**
185062**     doclist format:
185063**
185064**         varint:  first rowid
185065**         poslist: first poslist
185066**         zero-or-more {
185067**           varint:  rowid delta (always > 0)
185068**           poslist: next poslist
185069**         }
185070**
185071**     poslist format:
185072**
185073**         varint: size of poslist in bytes multiplied by 2, not including
185074**                 this field. Plus 1 if this entry carries the "delete" flag.
185075**         collist: collist for column 0
185076**         zero-or-more {
185077**           0x01 byte
185078**           varint: column number (I)
185079**           collist: collist for column I
185080**         }
185081**
185082**     collist format:
185083**
185084**         varint: first offset + 2
185085**         zero-or-more {
185086**           varint: offset delta + 2
185087**         }
185088**
185089**   PAGE FORMAT
185090**
185091**     Each leaf page begins with a 4-byte header containing 2 16-bit
185092**     unsigned integer fields in big-endian format. They are:
185093**
185094**       * The byte offset of the first rowid on the page, if it exists
185095**         and occurs before the first term (otherwise 0).
185096**
185097**       * The byte offset of the start of the page footer. If the page
185098**         footer is 0 bytes in size, then this field is the same as the
185099**         size of the leaf page in bytes.
185100**
185101**     The page footer consists of a single varint for each term located
185102**     on the page. Each varint is the byte offset of the current term
185103**     within the page, delta-compressed against the previous value. In
185104**     other words, the first varint in the footer is the byte offset of
185105**     the first term, the second is the byte offset of the second less that
185106**     of the first, and so on.
185107**
185108**     The term/doclist format described above is accurate if the entire
185109**     term/doclist data fits on a single leaf page. If this is not the case,
185110**     the format is changed in two ways:
185111**
185112**       + if the first rowid on a page occurs before the first term, it
185113**         is stored as a literal value:
185114**
185115**             varint:  first rowid
185116**
185117**       + the first term on each page is stored in the same way as the
185118**         very first term of the segment:
185119**
185120**             varint : size of first term
185121**             blob:    first term data
185122**
185123** 5. Segment doclist indexes:
185124**
185125**   Doclist indexes are themselves b-trees, however they usually consist of
185126**   a single leaf record only. The format of each doclist index leaf page
185127**   is:
185128**
185129**     * Flags byte. Bits are:
185130**         0x01: Clear if leaf is also the root page, otherwise set.
185131**
185132**     * Page number of fts index leaf page. As a varint.
185133**
185134**     * First rowid on page indicated by previous field. As a varint.
185135**
185136**     * A list of varints, one for each subsequent termless page. A
185137**       positive delta if the termless page contains at least one rowid,
185138**       or an 0x00 byte otherwise.
185139**
185140**   Internal doclist index nodes are:
185141**
185142**     * Flags byte. Bits are:
185143**         0x01: Clear for root page, otherwise set.
185144**
185145**     * Page number of first child page. As a varint.
185146**
185147**     * Copy of first rowid on page indicated by previous field. As a varint.
185148**
185149**     * A list of delta-encoded varints - the first rowid on each subsequent
185150**       child page.
185151**
185152*/
185153
185154/*
185155** Rowids for the averages and structure records in the %_data table.
185156*/
185157#define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
185158#define FTS5_STRUCTURE_ROWID   10    /* The structure record */
185159
185160/*
185161** Macros determining the rowids used by segment leaves and dlidx leaves
185162** and nodes. All nodes and leaves are stored in the %_data table with large
185163** positive rowids.
185164**
185165** Each segment has a unique non-zero 16-bit id.
185166**
185167** The rowid for each segment leaf is found by passing the segment id and
185168** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
185169** sequentially starting from 1.
185170*/
185171#define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
185172#define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
185173#define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
185174#define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
185175
185176#define fts5_dri(segid, dlidx, height, pgno) (                                 \
185177 ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
185178 ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
185179 ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
185180 ((i64)(pgno))                                                                 \
185181)
185182
185183#define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
185184#define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
185185
185186/*
185187** Maximum segments permitted in a single index
185188*/
185189#define FTS5_MAX_SEGMENT 2000
185190
185191#ifdef SQLITE_DEBUG
185192static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
185193#endif
185194
185195
185196/*
185197** Each time a blob is read from the %_data table, it is padded with this
185198** many zero bytes. This makes it easier to decode the various record formats
185199** without overreading if the records are corrupt.
185200*/
185201#define FTS5_DATA_ZERO_PADDING 8
185202#define FTS5_DATA_PADDING 20
185203
185204typedef struct Fts5Data Fts5Data;
185205typedef struct Fts5DlidxIter Fts5DlidxIter;
185206typedef struct Fts5DlidxLvl Fts5DlidxLvl;
185207typedef struct Fts5DlidxWriter Fts5DlidxWriter;
185208typedef struct Fts5Iter Fts5Iter;
185209typedef struct Fts5PageWriter Fts5PageWriter;
185210typedef struct Fts5SegIter Fts5SegIter;
185211typedef struct Fts5DoclistIter Fts5DoclistIter;
185212typedef struct Fts5SegWriter Fts5SegWriter;
185213typedef struct Fts5Structure Fts5Structure;
185214typedef struct Fts5StructureLevel Fts5StructureLevel;
185215typedef struct Fts5StructureSegment Fts5StructureSegment;
185216
185217struct Fts5Data {
185218  u8 *p;                          /* Pointer to buffer containing record */
185219  int nn;                         /* Size of record in bytes */
185220  int szLeaf;                     /* Size of leaf without page-index */
185221};
185222
185223/*
185224** One object per %_data table.
185225*/
185226struct Fts5Index {
185227  Fts5Config *pConfig;            /* Virtual table configuration */
185228  char *zDataTbl;                 /* Name of %_data table */
185229  int nWorkUnit;                  /* Leaf pages in a "unit" of work */
185230
185231  /*
185232  ** Variables related to the accumulation of tokens and doclists within the
185233  ** in-memory hash tables before they are flushed to disk.
185234  */
185235  Fts5Hash *pHash;                /* Hash table for in-memory data */
185236  int nPendingData;               /* Current bytes of pending data */
185237  i64 iWriteRowid;                /* Rowid for current doc being written */
185238  int bDelete;                    /* Current write is a delete */
185239
185240  /* Error state. */
185241  int rc;                         /* Current error code */
185242
185243  /* State used by the fts5DataXXX() functions. */
185244  sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
185245  sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
185246  sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
185247  sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
185248  sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
185249  sqlite3_stmt *pIdxSelect;
185250  int nRead;                      /* Total number of blocks read */
185251
185252  sqlite3_stmt *pDataVersion;
185253  i64 iStructVersion;             /* data_version when pStruct read */
185254  Fts5Structure *pStruct;         /* Current db structure (or NULL) */
185255};
185256
185257struct Fts5DoclistIter {
185258  u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
185259
185260  /* Output variables. aPoslist==0 at EOF */
185261  i64 iRowid;
185262  u8 *aPoslist;
185263  int nPoslist;
185264  int nSize;
185265};
185266
185267/*
185268** The contents of the "structure" record for each index are represented
185269** using an Fts5Structure record in memory. Which uses instances of the
185270** other Fts5StructureXXX types as components.
185271*/
185272struct Fts5StructureSegment {
185273  int iSegid;                     /* Segment id */
185274  int pgnoFirst;                  /* First leaf page number in segment */
185275  int pgnoLast;                   /* Last leaf page number in segment */
185276};
185277struct Fts5StructureLevel {
185278  int nMerge;                     /* Number of segments in incr-merge */
185279  int nSeg;                       /* Total number of segments on level */
185280  Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
185281};
185282struct Fts5Structure {
185283  int nRef;                       /* Object reference count */
185284  u64 nWriteCounter;              /* Total leaves written to level 0 */
185285  int nSegment;                   /* Total segments in this structure */
185286  int nLevel;                     /* Number of levels in this index */
185287  Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
185288};
185289
185290/*
185291** An object of type Fts5SegWriter is used to write to segments.
185292*/
185293struct Fts5PageWriter {
185294  int pgno;                       /* Page number for this page */
185295  int iPrevPgidx;                 /* Previous value written into pgidx */
185296  Fts5Buffer buf;                 /* Buffer containing leaf data */
185297  Fts5Buffer pgidx;               /* Buffer containing page-index */
185298  Fts5Buffer term;                /* Buffer containing previous term on page */
185299};
185300struct Fts5DlidxWriter {
185301  int pgno;                       /* Page number for this page */
185302  int bPrevValid;                 /* True if iPrev is valid */
185303  i64 iPrev;                      /* Previous rowid value written to page */
185304  Fts5Buffer buf;                 /* Buffer containing page data */
185305};
185306struct Fts5SegWriter {
185307  int iSegid;                     /* Segid to write to */
185308  Fts5PageWriter writer;          /* PageWriter object */
185309  i64 iPrevRowid;                 /* Previous rowid written to current leaf */
185310  u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
185311  u8 bFirstRowidInPage;           /* True if next rowid is first in page */
185312  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
185313  u8 bFirstTermInPage;            /* True if next term will be first in leaf */
185314  int nLeafWritten;               /* Number of leaf pages written */
185315  int nEmpty;                     /* Number of contiguous term-less nodes */
185316
185317  int nDlidx;                     /* Allocated size of aDlidx[] array */
185318  Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
185319
185320  /* Values to insert into the %_idx table */
185321  Fts5Buffer btterm;              /* Next term to insert into %_idx table */
185322  int iBtPage;                    /* Page number corresponding to btterm */
185323};
185324
185325typedef struct Fts5CResult Fts5CResult;
185326struct Fts5CResult {
185327  u16 iFirst;                     /* aSeg[] index of firstest iterator */
185328  u8 bTermEq;                     /* True if the terms are equal */
185329};
185330
185331/*
185332** Object for iterating through a single segment, visiting each term/rowid
185333** pair in the segment.
185334**
185335** pSeg:
185336**   The segment to iterate through.
185337**
185338** iLeafPgno:
185339**   Current leaf page number within segment.
185340**
185341** iLeafOffset:
185342**   Byte offset within the current leaf that is the first byte of the
185343**   position list data (one byte passed the position-list size field).
185344**   rowid field of the current entry. Usually this is the size field of the
185345**   position list data. The exception is if the rowid for the current entry
185346**   is the last thing on the leaf page.
185347**
185348** pLeaf:
185349**   Buffer containing current leaf page data. Set to NULL at EOF.
185350**
185351** iTermLeafPgno, iTermLeafOffset:
185352**   Leaf page number containing the last term read from the segment. And
185353**   the offset immediately following the term data.
185354**
185355** flags:
185356**   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
185357**
185358**   FTS5_SEGITER_ONETERM:
185359**     If set, set the iterator to point to EOF after the current doclist
185360**     has been exhausted. Do not proceed to the next term in the segment.
185361**
185362**   FTS5_SEGITER_REVERSE:
185363**     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
185364**     it is set, iterate through rowid in descending order instead of the
185365**     default ascending order.
185366**
185367** iRowidOffset/nRowidOffset/aRowidOffset:
185368**     These are used if the FTS5_SEGITER_REVERSE flag is set.
185369**
185370**     For each rowid on the page corresponding to the current term, the
185371**     corresponding aRowidOffset[] entry is set to the byte offset of the
185372**     start of the "position-list-size" field within the page.
185373**
185374** iTermIdx:
185375**     Index of current term on iTermLeafPgno.
185376*/
185377struct Fts5SegIter {
185378  Fts5StructureSegment *pSeg;     /* Segment to iterate through */
185379  int flags;                      /* Mask of configuration flags */
185380  int iLeafPgno;                  /* Current leaf page number */
185381  Fts5Data *pLeaf;                /* Current leaf data */
185382  Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
185383  int iLeafOffset;                /* Byte offset within current leaf */
185384
185385  /* Next method */
185386  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
185387
185388  /* The page and offset from which the current term was read. The offset
185389  ** is the offset of the first rowid in the current doclist.  */
185390  int iTermLeafPgno;
185391  int iTermLeafOffset;
185392
185393  int iPgidxOff;                  /* Next offset in pgidx */
185394  int iEndofDoclist;
185395
185396  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
185397  int iRowidOffset;               /* Current entry in aRowidOffset[] */
185398  int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
185399  int *aRowidOffset;              /* Array of offset to rowid fields */
185400
185401  Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
185402
185403  /* Variables populated based on current entry. */
185404  Fts5Buffer term;                /* Current term */
185405  i64 iRowid;                     /* Current rowid */
185406  int nPos;                       /* Number of bytes in current position list */
185407  u8 bDel;                        /* True if the delete flag is set */
185408};
185409
185410/*
185411** Argument is a pointer to an Fts5Data structure that contains a
185412** leaf page.
185413*/
185414#define ASSERT_SZLEAF_OK(x) assert( \
185415    (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
185416)
185417
185418#define FTS5_SEGITER_ONETERM 0x01
185419#define FTS5_SEGITER_REVERSE 0x02
185420
185421/*
185422** Argument is a pointer to an Fts5Data structure that contains a leaf
185423** page. This macro evaluates to true if the leaf contains no terms, or
185424** false if it contains at least one term.
185425*/
185426#define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
185427
185428#define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
185429
185430#define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
185431
185432/*
185433** Object for iterating through the merged results of one or more segments,
185434** visiting each term/rowid pair in the merged data.
185435**
185436** nSeg is always a power of two greater than or equal to the number of
185437** segments that this object is merging data from. Both the aSeg[] and
185438** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
185439** with zeroed objects - these are handled as if they were iterators opened
185440** on empty segments.
185441**
185442** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
185443** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
185444** comparison in this context is the index of the iterator that currently
185445** points to the smaller term/rowid combination. Iterators at EOF are
185446** considered to be greater than all other iterators.
185447**
185448** aFirst[1] contains the index in aSeg[] of the iterator that points to
185449** the smallest key overall. aFirst[0] is unused.
185450**
185451** poslist:
185452**   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
185453**   There is no way to tell if this is populated or not.
185454*/
185455struct Fts5Iter {
185456  Fts5IndexIter base;             /* Base class containing output vars */
185457
185458  Fts5Index *pIndex;              /* Index that owns this iterator */
185459  Fts5Structure *pStruct;         /* Database structure for this iterator */
185460  Fts5Buffer poslist;             /* Buffer containing current poslist */
185461  Fts5Colset *pColset;            /* Restrict matches to these columns */
185462
185463  /* Invoked to set output variables. */
185464  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
185465
185466  int nSeg;                       /* Size of aSeg[] array */
185467  int bRev;                       /* True to iterate in reverse order */
185468  u8 bSkipEmpty;                  /* True to skip deleted entries */
185469
185470  i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
185471  Fts5CResult *aFirst;            /* Current merge state (see above) */
185472  Fts5SegIter aSeg[1];            /* Array of segment iterators */
185473};
185474
185475
185476/*
185477** An instance of the following type is used to iterate through the contents
185478** of a doclist-index record.
185479**
185480** pData:
185481**   Record containing the doclist-index data.
185482**
185483** bEof:
185484**   Set to true once iterator has reached EOF.
185485**
185486** iOff:
185487**   Set to the current offset within record pData.
185488*/
185489struct Fts5DlidxLvl {
185490  Fts5Data *pData;              /* Data for current page of this level */
185491  int iOff;                     /* Current offset into pData */
185492  int bEof;                     /* At EOF already */
185493  int iFirstOff;                /* Used by reverse iterators */
185494
185495  /* Output variables */
185496  int iLeafPgno;                /* Page number of current leaf page */
185497  i64 iRowid;                   /* First rowid on leaf iLeafPgno */
185498};
185499struct Fts5DlidxIter {
185500  int nLvl;
185501  int iSegid;
185502  Fts5DlidxLvl aLvl[1];
185503};
185504
185505static void fts5PutU16(u8 *aOut, u16 iVal){
185506  aOut[0] = (iVal>>8);
185507  aOut[1] = (iVal&0xFF);
185508}
185509
185510static u16 fts5GetU16(const u8 *aIn){
185511  return ((u16)aIn[0] << 8) + aIn[1];
185512}
185513
185514/*
185515** Allocate and return a buffer at least nByte bytes in size.
185516**
185517** If an OOM error is encountered, return NULL and set the error code in
185518** the Fts5Index handle passed as the first argument.
185519*/
185520static void *fts5IdxMalloc(Fts5Index *p, int nByte){
185521  return sqlite3Fts5MallocZero(&p->rc, nByte);
185522}
185523
185524/*
185525** Compare the contents of the pLeft buffer with the pRight/nRight blob.
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*/
185532#ifdef SQLITE_DEBUG
185533static int fts5BufferCompareBlob(
185534  Fts5Buffer *pLeft,              /* Left hand side of comparison */
185535  const u8 *pRight, int nRight    /* Right hand side of comparison */
185536){
185537  int nCmp = MIN(pLeft->n, nRight);
185538  int res = memcmp(pLeft->p, pRight, nCmp);
185539  return (res==0 ? (pLeft->n - nRight) : res);
185540}
185541#endif
185542
185543/*
185544** Compare the contents of the two buffers using memcmp(). If one buffer
185545** is a prefix of the other, it is considered the lesser.
185546**
185547** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
185548** +ve if pRight is smaller than pLeft. In other words:
185549**
185550**     res = *pLeft - *pRight
185551*/
185552static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
185553  int nCmp = MIN(pLeft->n, pRight->n);
185554  int res = memcmp(pLeft->p, pRight->p, nCmp);
185555  return (res==0 ? (pLeft->n - pRight->n) : res);
185556}
185557
185558static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
185559  int ret;
185560  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
185561  return ret;
185562}
185563
185564/*
185565** Close the read-only blob handle, if it is open.
185566*/
185567static void fts5CloseReader(Fts5Index *p){
185568  if( p->pReader ){
185569    sqlite3_blob *pReader = p->pReader;
185570    p->pReader = 0;
185571    sqlite3_blob_close(pReader);
185572  }
185573}
185574
185575
185576/*
185577** Retrieve a record from the %_data table.
185578**
185579** If an error occurs, NULL is returned and an error left in the
185580** Fts5Index object.
185581*/
185582static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
185583  Fts5Data *pRet = 0;
185584  if( p->rc==SQLITE_OK ){
185585    int rc = SQLITE_OK;
185586
185587    if( p->pReader ){
185588      /* This call may return SQLITE_ABORT if there has been a savepoint
185589      ** rollback since it was last used. In this case a new blob handle
185590      ** is required.  */
185591      sqlite3_blob *pBlob = p->pReader;
185592      p->pReader = 0;
185593      rc = sqlite3_blob_reopen(pBlob, iRowid);
185594      assert( p->pReader==0 );
185595      p->pReader = pBlob;
185596      if( rc!=SQLITE_OK ){
185597        fts5CloseReader(p);
185598      }
185599      if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
185600    }
185601
185602    /* If the blob handle is not open at this point, open it and seek
185603    ** to the requested entry.  */
185604    if( p->pReader==0 && rc==SQLITE_OK ){
185605      Fts5Config *pConfig = p->pConfig;
185606      rc = sqlite3_blob_open(pConfig->db,
185607          pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
185608      );
185609    }
185610
185611    /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
185612    ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
185613    ** All the reasons those functions might return SQLITE_ERROR - missing
185614    ** table, missing row, non-blob/text in block column - indicate
185615    ** backing store corruption.  */
185616    if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
185617
185618    if( rc==SQLITE_OK ){
185619      u8 *aOut = 0;               /* Read blob data into this buffer */
185620      int nByte = sqlite3_blob_bytes(p->pReader);
185621      int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
185622      pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
185623      if( pRet ){
185624        pRet->nn = nByte;
185625        aOut = pRet->p = (u8*)&pRet[1];
185626      }else{
185627        rc = SQLITE_NOMEM;
185628      }
185629
185630      if( rc==SQLITE_OK ){
185631        rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
185632      }
185633      if( rc!=SQLITE_OK ){
185634        sqlite3_free(pRet);
185635        pRet = 0;
185636      }else{
185637        /* TODO1: Fix this */
185638        pRet->szLeaf = fts5GetU16(&pRet->p[2]);
185639      }
185640    }
185641    p->rc = rc;
185642    p->nRead++;
185643  }
185644
185645  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
185646  return pRet;
185647}
185648
185649
185650/*
185651** Release a reference to data record returned by an earlier call to
185652** fts5DataRead().
185653*/
185654static void fts5DataRelease(Fts5Data *pData){
185655  sqlite3_free(pData);
185656}
185657
185658static int fts5IndexPrepareStmt(
185659  Fts5Index *p,
185660  sqlite3_stmt **ppStmt,
185661  char *zSql
185662){
185663  if( p->rc==SQLITE_OK ){
185664    if( zSql ){
185665      p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
185666    }else{
185667      p->rc = SQLITE_NOMEM;
185668    }
185669  }
185670  sqlite3_free(zSql);
185671  return p->rc;
185672}
185673
185674
185675/*
185676** INSERT OR REPLACE a record into the %_data table.
185677*/
185678static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
185679  if( p->rc!=SQLITE_OK ) return;
185680
185681  if( p->pWriter==0 ){
185682    Fts5Config *pConfig = p->pConfig;
185683    fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
185684          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
185685          pConfig->zDb, pConfig->zName
185686    ));
185687    if( p->rc ) return;
185688  }
185689
185690  sqlite3_bind_int64(p->pWriter, 1, iRowid);
185691  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
185692  sqlite3_step(p->pWriter);
185693  p->rc = sqlite3_reset(p->pWriter);
185694}
185695
185696/*
185697** Execute the following SQL:
185698**
185699**     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
185700*/
185701static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
185702  if( p->rc!=SQLITE_OK ) return;
185703
185704  if( p->pDeleter==0 ){
185705    int rc;
185706    Fts5Config *pConfig = p->pConfig;
185707    char *zSql = sqlite3_mprintf(
185708        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
185709          pConfig->zDb, pConfig->zName
185710    );
185711    if( zSql==0 ){
185712      rc = SQLITE_NOMEM;
185713    }else{
185714      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
185715      sqlite3_free(zSql);
185716    }
185717    if( rc!=SQLITE_OK ){
185718      p->rc = rc;
185719      return;
185720    }
185721  }
185722
185723  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
185724  sqlite3_bind_int64(p->pDeleter, 2, iLast);
185725  sqlite3_step(p->pDeleter);
185726  p->rc = sqlite3_reset(p->pDeleter);
185727}
185728
185729/*
185730** Remove all records associated with segment iSegid.
185731*/
185732static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
185733  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
185734  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
185735  fts5DataDelete(p, iFirst, iLast);
185736  if( p->pIdxDeleter==0 ){
185737    Fts5Config *pConfig = p->pConfig;
185738    fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
185739          "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
185740          pConfig->zDb, pConfig->zName
185741    ));
185742  }
185743  if( p->rc==SQLITE_OK ){
185744    sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
185745    sqlite3_step(p->pIdxDeleter);
185746    p->rc = sqlite3_reset(p->pIdxDeleter);
185747  }
185748}
185749
185750/*
185751** Release a reference to an Fts5Structure object returned by an earlier
185752** call to fts5StructureRead() or fts5StructureDecode().
185753*/
185754static void fts5StructureRelease(Fts5Structure *pStruct){
185755  if( pStruct && 0>=(--pStruct->nRef) ){
185756    int i;
185757    assert( pStruct->nRef==0 );
185758    for(i=0; i<pStruct->nLevel; i++){
185759      sqlite3_free(pStruct->aLevel[i].aSeg);
185760    }
185761    sqlite3_free(pStruct);
185762  }
185763}
185764
185765static void fts5StructureRef(Fts5Structure *pStruct){
185766  pStruct->nRef++;
185767}
185768
185769/*
185770** Deserialize and return the structure record currently stored in serialized
185771** form within buffer pData/nData.
185772**
185773** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
185774** are over-allocated by one slot. This allows the structure contents
185775** to be more easily edited.
185776**
185777** If an error occurs, *ppOut is set to NULL and an SQLite error code
185778** returned. Otherwise, *ppOut is set to point to the new object and
185779** SQLITE_OK returned.
185780*/
185781static int fts5StructureDecode(
185782  const u8 *pData,                /* Buffer containing serialized structure */
185783  int nData,                      /* Size of buffer pData in bytes */
185784  int *piCookie,                  /* Configuration cookie value */
185785  Fts5Structure **ppOut           /* OUT: Deserialized object */
185786){
185787  int rc = SQLITE_OK;
185788  int i = 0;
185789  int iLvl;
185790  int nLevel = 0;
185791  int nSegment = 0;
185792  int nByte;                      /* Bytes of space to allocate at pRet */
185793  Fts5Structure *pRet = 0;        /* Structure object to return */
185794
185795  /* Grab the cookie value */
185796  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
185797  i = 4;
185798
185799  /* Read the total number of levels and segments from the start of the
185800  ** structure record.  */
185801  i += fts5GetVarint32(&pData[i], nLevel);
185802  i += fts5GetVarint32(&pData[i], nSegment);
185803  nByte = (
185804      sizeof(Fts5Structure) +                    /* Main structure */
185805      sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
185806  );
185807  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
185808
185809  if( pRet ){
185810    pRet->nRef = 1;
185811    pRet->nLevel = nLevel;
185812    pRet->nSegment = nSegment;
185813    i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
185814
185815    for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
185816      Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
185817      int nTotal = 0;
185818      int iSeg;
185819
185820      if( i>=nData ){
185821        rc = FTS5_CORRUPT;
185822      }else{
185823        i += fts5GetVarint32(&pData[i], pLvl->nMerge);
185824        i += fts5GetVarint32(&pData[i], nTotal);
185825        assert( nTotal>=pLvl->nMerge );
185826        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
185827            nTotal * sizeof(Fts5StructureSegment)
185828        );
185829      }
185830
185831      if( rc==SQLITE_OK ){
185832        pLvl->nSeg = nTotal;
185833        for(iSeg=0; iSeg<nTotal; iSeg++){
185834          if( i>=nData ){
185835            rc = FTS5_CORRUPT;
185836            break;
185837          }
185838          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
185839          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
185840          i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
185841        }
185842      }
185843    }
185844    if( rc!=SQLITE_OK ){
185845      fts5StructureRelease(pRet);
185846      pRet = 0;
185847    }
185848  }
185849
185850  *ppOut = pRet;
185851  return rc;
185852}
185853
185854/*
185855**
185856*/
185857static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
185858  if( *pRc==SQLITE_OK ){
185859    Fts5Structure *pStruct = *ppStruct;
185860    int nLevel = pStruct->nLevel;
185861    int nByte = (
185862        sizeof(Fts5Structure) +                  /* Main structure */
185863        sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
185864    );
185865
185866    pStruct = sqlite3_realloc(pStruct, nByte);
185867    if( pStruct ){
185868      memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
185869      pStruct->nLevel++;
185870      *ppStruct = pStruct;
185871    }else{
185872      *pRc = SQLITE_NOMEM;
185873    }
185874  }
185875}
185876
185877/*
185878** Extend level iLvl so that there is room for at least nExtra more
185879** segments.
185880*/
185881static void fts5StructureExtendLevel(
185882  int *pRc,
185883  Fts5Structure *pStruct,
185884  int iLvl,
185885  int nExtra,
185886  int bInsert
185887){
185888  if( *pRc==SQLITE_OK ){
185889    Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
185890    Fts5StructureSegment *aNew;
185891    int nByte;
185892
185893    nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
185894    aNew = sqlite3_realloc(pLvl->aSeg, nByte);
185895    if( aNew ){
185896      if( bInsert==0 ){
185897        memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
185898      }else{
185899        int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
185900        memmove(&aNew[nExtra], aNew, nMove);
185901        memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
185902      }
185903      pLvl->aSeg = aNew;
185904    }else{
185905      *pRc = SQLITE_NOMEM;
185906    }
185907  }
185908}
185909
185910static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
185911  Fts5Structure *pRet = 0;
185912  Fts5Config *pConfig = p->pConfig;
185913  int iCookie;                    /* Configuration cookie */
185914  Fts5Data *pData;
185915
185916  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
185917  if( p->rc==SQLITE_OK ){
185918    /* TODO: Do we need this if the leaf-index is appended? Probably... */
185919    memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
185920    p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
185921    if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
185922      p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
185923    }
185924    fts5DataRelease(pData);
185925    if( p->rc!=SQLITE_OK ){
185926      fts5StructureRelease(pRet);
185927      pRet = 0;
185928    }
185929  }
185930
185931  return pRet;
185932}
185933
185934static i64 fts5IndexDataVersion(Fts5Index *p){
185935  i64 iVersion = 0;
185936
185937  if( p->rc==SQLITE_OK ){
185938    if( p->pDataVersion==0 ){
185939      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
185940          sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
185941          );
185942      if( p->rc ) return 0;
185943    }
185944
185945    if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
185946      iVersion = sqlite3_column_int64(p->pDataVersion, 0);
185947    }
185948    p->rc = sqlite3_reset(p->pDataVersion);
185949  }
185950
185951  return iVersion;
185952}
185953
185954/*
185955** Read, deserialize and return the structure record.
185956**
185957** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
185958** are over-allocated as described for function fts5StructureDecode()
185959** above.
185960**
185961** If an error occurs, NULL is returned and an error code left in the
185962** Fts5Index handle. If an error has already occurred when this function
185963** is called, it is a no-op.
185964*/
185965static Fts5Structure *fts5StructureRead(Fts5Index *p){
185966
185967  if( p->pStruct==0 ){
185968    p->iStructVersion = fts5IndexDataVersion(p);
185969    if( p->rc==SQLITE_OK ){
185970      p->pStruct = fts5StructureReadUncached(p);
185971    }
185972  }
185973
185974#if 0
185975  else{
185976    Fts5Structure *pTest = fts5StructureReadUncached(p);
185977    if( pTest ){
185978      int i, j;
185979      assert_nc( p->pStruct->nSegment==pTest->nSegment );
185980      assert_nc( p->pStruct->nLevel==pTest->nLevel );
185981      for(i=0; i<pTest->nLevel; i++){
185982        assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
185983        assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
185984        for(j=0; j<pTest->aLevel[i].nSeg; j++){
185985          Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
185986          Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
185987          assert_nc( p1->iSegid==p2->iSegid );
185988          assert_nc( p1->pgnoFirst==p2->pgnoFirst );
185989          assert_nc( p1->pgnoLast==p2->pgnoLast );
185990        }
185991      }
185992      fts5StructureRelease(pTest);
185993    }
185994  }
185995#endif
185996
185997  if( p->rc!=SQLITE_OK ) return 0;
185998  assert( p->iStructVersion!=0 );
185999  assert( p->pStruct!=0 );
186000  fts5StructureRef(p->pStruct);
186001  return p->pStruct;
186002}
186003
186004static void fts5StructureInvalidate(Fts5Index *p){
186005  if( p->pStruct ){
186006    fts5StructureRelease(p->pStruct);
186007    p->pStruct = 0;
186008  }
186009}
186010
186011/*
186012** Return the total number of segments in index structure pStruct. This
186013** function is only ever used as part of assert() conditions.
186014*/
186015#ifdef SQLITE_DEBUG
186016static int fts5StructureCountSegments(Fts5Structure *pStruct){
186017  int nSegment = 0;               /* Total number of segments */
186018  if( pStruct ){
186019    int iLvl;                     /* Used to iterate through levels */
186020    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
186021      nSegment += pStruct->aLevel[iLvl].nSeg;
186022    }
186023  }
186024
186025  return nSegment;
186026}
186027#endif
186028
186029#define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
186030  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
186031  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
186032  (pBuf)->n += nBlob;                                      \
186033}
186034
186035#define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
186036  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
186037  assert( (pBuf)->nSpace>=(pBuf)->n );                          \
186038}
186039
186040
186041/*
186042** Serialize and store the "structure" record.
186043**
186044** If an error occurs, leave an error code in the Fts5Index object. If an
186045** error has already occurred, this function is a no-op.
186046*/
186047static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
186048  if( p->rc==SQLITE_OK ){
186049    Fts5Buffer buf;               /* Buffer to serialize record into */
186050    int iLvl;                     /* Used to iterate through levels */
186051    int iCookie;                  /* Cookie value to store */
186052
186053    assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
186054    memset(&buf, 0, sizeof(Fts5Buffer));
186055
186056    /* Append the current configuration cookie */
186057    iCookie = p->pConfig->iCookie;
186058    if( iCookie<0 ) iCookie = 0;
186059
186060    if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
186061      sqlite3Fts5Put32(buf.p, iCookie);
186062      buf.n = 4;
186063      fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
186064      fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
186065      fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
186066    }
186067
186068    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
186069      int iSeg;                     /* Used to iterate through segments */
186070      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
186071      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
186072      fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
186073      assert( pLvl->nMerge<=pLvl->nSeg );
186074
186075      for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
186076        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
186077        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
186078        fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
186079      }
186080    }
186081
186082    fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
186083    fts5BufferFree(&buf);
186084  }
186085}
186086
186087#if 0
186088static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
186089static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
186090  int rc = SQLITE_OK;
186091  Fts5Buffer buf;
186092  memset(&buf, 0, sizeof(buf));
186093  fts5DebugStructure(&rc, &buf, pStruct);
186094  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
186095  fflush(stdout);
186096  fts5BufferFree(&buf);
186097}
186098#else
186099# define fts5PrintStructure(x,y)
186100#endif
186101
186102static int fts5SegmentSize(Fts5StructureSegment *pSeg){
186103  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
186104}
186105
186106/*
186107** Return a copy of index structure pStruct. Except, promote as many
186108** segments as possible to level iPromote. If an OOM occurs, NULL is
186109** returned.
186110*/
186111static void fts5StructurePromoteTo(
186112  Fts5Index *p,
186113  int iPromote,
186114  int szPromote,
186115  Fts5Structure *pStruct
186116){
186117  int il, is;
186118  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
186119
186120  if( pOut->nMerge==0 ){
186121    for(il=iPromote+1; il<pStruct->nLevel; il++){
186122      Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
186123      if( pLvl->nMerge ) return;
186124      for(is=pLvl->nSeg-1; is>=0; is--){
186125        int sz = fts5SegmentSize(&pLvl->aSeg[is]);
186126        if( sz>szPromote ) return;
186127        fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
186128        if( p->rc ) return;
186129        memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
186130        pOut->nSeg++;
186131        pLvl->nSeg--;
186132      }
186133    }
186134  }
186135}
186136
186137/*
186138** A new segment has just been written to level iLvl of index structure
186139** pStruct. This function determines if any segments should be promoted
186140** as a result. Segments are promoted in two scenarios:
186141**
186142**   a) If the segment just written is smaller than one or more segments
186143**      within the previous populated level, it is promoted to the previous
186144**      populated level.
186145**
186146**   b) If the segment just written is larger than the newest segment on
186147**      the next populated level, then that segment, and any other adjacent
186148**      segments that are also smaller than the one just written, are
186149**      promoted.
186150**
186151** If one or more segments are promoted, the structure object is updated
186152** to reflect this.
186153*/
186154static void fts5StructurePromote(
186155  Fts5Index *p,                   /* FTS5 backend object */
186156  int iLvl,                       /* Index level just updated */
186157  Fts5Structure *pStruct          /* Index structure */
186158){
186159  if( p->rc==SQLITE_OK ){
186160    int iTst;
186161    int iPromote = -1;
186162    int szPromote = 0;            /* Promote anything this size or smaller */
186163    Fts5StructureSegment *pSeg;   /* Segment just written */
186164    int szSeg;                    /* Size of segment just written */
186165    int nSeg = pStruct->aLevel[iLvl].nSeg;
186166
186167    if( nSeg==0 ) return;
186168    pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
186169    szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
186170
186171    /* Check for condition (a) */
186172    for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
186173    if( iTst>=0 ){
186174      int i;
186175      int szMax = 0;
186176      Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
186177      assert( pTst->nMerge==0 );
186178      for(i=0; i<pTst->nSeg; i++){
186179        int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
186180        if( sz>szMax ) szMax = sz;
186181      }
186182      if( szMax>=szSeg ){
186183        /* Condition (a) is true. Promote the newest segment on level
186184        ** iLvl to level iTst.  */
186185        iPromote = iTst;
186186        szPromote = szMax;
186187      }
186188    }
186189
186190    /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
186191    ** is a no-op if it is not.  */
186192    if( iPromote<0 ){
186193      iPromote = iLvl;
186194      szPromote = szSeg;
186195    }
186196    fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
186197  }
186198}
186199
186200
186201/*
186202** Advance the iterator passed as the only argument. If the end of the
186203** doclist-index page is reached, return non-zero.
186204*/
186205static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
186206  Fts5Data *pData = pLvl->pData;
186207
186208  if( pLvl->iOff==0 ){
186209    assert( pLvl->bEof==0 );
186210    pLvl->iOff = 1;
186211    pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
186212    pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
186213    pLvl->iFirstOff = pLvl->iOff;
186214  }else{
186215    int iOff;
186216    for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
186217      if( pData->p[iOff] ) break;
186218    }
186219
186220    if( iOff<pData->nn ){
186221      i64 iVal;
186222      pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
186223      iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
186224      pLvl->iRowid += iVal;
186225      pLvl->iOff = iOff;
186226    }else{
186227      pLvl->bEof = 1;
186228    }
186229  }
186230
186231  return pLvl->bEof;
186232}
186233
186234/*
186235** Advance the iterator passed as the only argument.
186236*/
186237static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
186238  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
186239
186240  assert( iLvl<pIter->nLvl );
186241  if( fts5DlidxLvlNext(pLvl) ){
186242    if( (iLvl+1) < pIter->nLvl ){
186243      fts5DlidxIterNextR(p, pIter, iLvl+1);
186244      if( pLvl[1].bEof==0 ){
186245        fts5DataRelease(pLvl->pData);
186246        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186247        pLvl->pData = fts5DataRead(p,
186248            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
186249        );
186250        if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
186251      }
186252    }
186253  }
186254
186255  return pIter->aLvl[0].bEof;
186256}
186257static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
186258  return fts5DlidxIterNextR(p, pIter, 0);
186259}
186260
186261/*
186262** The iterator passed as the first argument has the following fields set
186263** as follows. This function sets up the rest of the iterator so that it
186264** points to the first rowid in the doclist-index.
186265**
186266**   pData:
186267**     pointer to doclist-index record,
186268**
186269** When this function is called pIter->iLeafPgno is the page number the
186270** doclist is associated with (the one featuring the term).
186271*/
186272static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
186273  int i;
186274  for(i=0; i<pIter->nLvl; i++){
186275    fts5DlidxLvlNext(&pIter->aLvl[i]);
186276  }
186277  return pIter->aLvl[0].bEof;
186278}
186279
186280
186281static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
186282  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
186283}
186284
186285static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
186286  int i;
186287
186288  /* Advance each level to the last entry on the last page */
186289  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
186290    Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
186291    while( fts5DlidxLvlNext(pLvl)==0 );
186292    pLvl->bEof = 0;
186293
186294    if( i>0 ){
186295      Fts5DlidxLvl *pChild = &pLvl[-1];
186296      fts5DataRelease(pChild->pData);
186297      memset(pChild, 0, sizeof(Fts5DlidxLvl));
186298      pChild->pData = fts5DataRead(p,
186299          FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
186300      );
186301    }
186302  }
186303}
186304
186305/*
186306** Move the iterator passed as the only argument to the previous entry.
186307*/
186308static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
186309  int iOff = pLvl->iOff;
186310
186311  assert( pLvl->bEof==0 );
186312  if( iOff<=pLvl->iFirstOff ){
186313    pLvl->bEof = 1;
186314  }else{
186315    u8 *a = pLvl->pData->p;
186316    i64 iVal;
186317    int iLimit;
186318    int ii;
186319    int nZero = 0;
186320
186321    /* Currently iOff points to the first byte of a varint. This block
186322    ** decrements iOff until it points to the first byte of the previous
186323    ** varint. Taking care not to read any memory locations that occur
186324    ** before the buffer in memory.  */
186325    iLimit = (iOff>9 ? iOff-9 : 0);
186326    for(iOff--; iOff>iLimit; iOff--){
186327      if( (a[iOff-1] & 0x80)==0 ) break;
186328    }
186329
186330    fts5GetVarint(&a[iOff], (u64*)&iVal);
186331    pLvl->iRowid -= iVal;
186332    pLvl->iLeafPgno--;
186333
186334    /* Skip backwards past any 0x00 varints. */
186335    for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
186336      nZero++;
186337    }
186338    if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
186339      /* The byte immediately before the last 0x00 byte has the 0x80 bit
186340      ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
186341      ** bytes before a[ii]. */
186342      int bZero = 0;              /* True if last 0x00 counts */
186343      if( (ii-8)>=pLvl->iFirstOff ){
186344        int j;
186345        for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
186346        bZero = (j>8);
186347      }
186348      if( bZero==0 ) nZero--;
186349    }
186350    pLvl->iLeafPgno -= nZero;
186351    pLvl->iOff = iOff - nZero;
186352  }
186353
186354  return pLvl->bEof;
186355}
186356
186357static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
186358  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
186359
186360  assert( iLvl<pIter->nLvl );
186361  if( fts5DlidxLvlPrev(pLvl) ){
186362    if( (iLvl+1) < pIter->nLvl ){
186363      fts5DlidxIterPrevR(p, pIter, iLvl+1);
186364      if( pLvl[1].bEof==0 ){
186365        fts5DataRelease(pLvl->pData);
186366        memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186367        pLvl->pData = fts5DataRead(p,
186368            FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
186369        );
186370        if( pLvl->pData ){
186371          while( fts5DlidxLvlNext(pLvl)==0 );
186372          pLvl->bEof = 0;
186373        }
186374      }
186375    }
186376  }
186377
186378  return pIter->aLvl[0].bEof;
186379}
186380static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
186381  return fts5DlidxIterPrevR(p, pIter, 0);
186382}
186383
186384/*
186385** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
186386*/
186387static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
186388  if( pIter ){
186389    int i;
186390    for(i=0; i<pIter->nLvl; i++){
186391      fts5DataRelease(pIter->aLvl[i].pData);
186392    }
186393    sqlite3_free(pIter);
186394  }
186395}
186396
186397static Fts5DlidxIter *fts5DlidxIterInit(
186398  Fts5Index *p,                   /* Fts5 Backend to iterate within */
186399  int bRev,                       /* True for ORDER BY ASC */
186400  int iSegid,                     /* Segment id */
186401  int iLeafPg                     /* Leaf page number to load dlidx for */
186402){
186403  Fts5DlidxIter *pIter = 0;
186404  int i;
186405  int bDone = 0;
186406
186407  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
186408    int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
186409    Fts5DlidxIter *pNew;
186410
186411    pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
186412    if( pNew==0 ){
186413      p->rc = SQLITE_NOMEM;
186414    }else{
186415      i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
186416      Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
186417      pIter = pNew;
186418      memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186419      pLvl->pData = fts5DataRead(p, iRowid);
186420      if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
186421        bDone = 1;
186422      }
186423      pIter->nLvl = i+1;
186424    }
186425  }
186426
186427  if( p->rc==SQLITE_OK ){
186428    pIter->iSegid = iSegid;
186429    if( bRev==0 ){
186430      fts5DlidxIterFirst(pIter);
186431    }else{
186432      fts5DlidxIterLast(p, pIter);
186433    }
186434  }
186435
186436  if( p->rc!=SQLITE_OK ){
186437    fts5DlidxIterFree(pIter);
186438    pIter = 0;
186439  }
186440
186441  return pIter;
186442}
186443
186444static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
186445  return pIter->aLvl[0].iRowid;
186446}
186447static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
186448  return pIter->aLvl[0].iLeafPgno;
186449}
186450
186451/*
186452** Load the next leaf page into the segment iterator.
186453*/
186454static void fts5SegIterNextPage(
186455  Fts5Index *p,                   /* FTS5 backend object */
186456  Fts5SegIter *pIter              /* Iterator to advance to next page */
186457){
186458  Fts5Data *pLeaf;
186459  Fts5StructureSegment *pSeg = pIter->pSeg;
186460  fts5DataRelease(pIter->pLeaf);
186461  pIter->iLeafPgno++;
186462  if( pIter->pNextLeaf ){
186463    pIter->pLeaf = pIter->pNextLeaf;
186464    pIter->pNextLeaf = 0;
186465  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
186466    pIter->pLeaf = fts5DataRead(p,
186467        FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
186468    );
186469  }else{
186470    pIter->pLeaf = 0;
186471  }
186472  pLeaf = pIter->pLeaf;
186473
186474  if( pLeaf ){
186475    pIter->iPgidxOff = pLeaf->szLeaf;
186476    if( fts5LeafIsTermless(pLeaf) ){
186477      pIter->iEndofDoclist = pLeaf->nn+1;
186478    }else{
186479      pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
186480          pIter->iEndofDoclist
186481      );
186482    }
186483  }
186484}
186485
186486/*
186487** Argument p points to a buffer containing a varint to be interpreted as a
186488** position list size field. Read the varint and return the number of bytes
186489** read. Before returning, set *pnSz to the number of bytes in the position
186490** list, and *pbDel to true if the delete flag is set, or false otherwise.
186491*/
186492static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
186493  int nSz;
186494  int n = 0;
186495  fts5FastGetVarint32(p, n, nSz);
186496  assert_nc( nSz>=0 );
186497  *pnSz = nSz/2;
186498  *pbDel = nSz & 0x0001;
186499  return n;
186500}
186501
186502/*
186503** Fts5SegIter.iLeafOffset currently points to the first byte of a
186504** position-list size field. Read the value of the field and store it
186505** in the following variables:
186506**
186507**   Fts5SegIter.nPos
186508**   Fts5SegIter.bDel
186509**
186510** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
186511** position list content (if any).
186512*/
186513static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
186514  if( p->rc==SQLITE_OK ){
186515    int iOff = pIter->iLeafOffset;  /* Offset to read at */
186516    ASSERT_SZLEAF_OK(pIter->pLeaf);
186517    if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
186518      int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
186519      pIter->bDel = 0;
186520      pIter->nPos = 1;
186521      if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
186522        pIter->bDel = 1;
186523        iOff++;
186524        if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
186525          pIter->nPos = 1;
186526          iOff++;
186527        }else{
186528          pIter->nPos = 0;
186529        }
186530      }
186531    }else{
186532      int nSz;
186533      fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
186534      pIter->bDel = (nSz & 0x0001);
186535      pIter->nPos = nSz>>1;
186536      assert_nc( pIter->nPos>=0 );
186537    }
186538    pIter->iLeafOffset = iOff;
186539  }
186540}
186541
186542static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
186543  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
186544  int iOff = pIter->iLeafOffset;
186545
186546  ASSERT_SZLEAF_OK(pIter->pLeaf);
186547  if( iOff>=pIter->pLeaf->szLeaf ){
186548    fts5SegIterNextPage(p, pIter);
186549    if( pIter->pLeaf==0 ){
186550      if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
186551      return;
186552    }
186553    iOff = 4;
186554    a = pIter->pLeaf->p;
186555  }
186556  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
186557  pIter->iLeafOffset = iOff;
186558}
186559
186560/*
186561** Fts5SegIter.iLeafOffset currently points to the first byte of the
186562** "nSuffix" field of a term. Function parameter nKeep contains the value
186563** of the "nPrefix" field (if there was one - it is passed 0 if this is
186564** the first term in the segment).
186565**
186566** This function populates:
186567**
186568**   Fts5SegIter.term
186569**   Fts5SegIter.rowid
186570**
186571** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
186572** the first position list. The position list belonging to document
186573** (Fts5SegIter.iRowid).
186574*/
186575static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
186576  u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
186577  int iOff = pIter->iLeafOffset;  /* Offset to read at */
186578  int nNew;                       /* Bytes of new data */
186579
186580  iOff += fts5GetVarint32(&a[iOff], nNew);
186581  if( iOff+nNew>pIter->pLeaf->nn ){
186582    p->rc = FTS5_CORRUPT;
186583    return;
186584  }
186585  pIter->term.n = nKeep;
186586  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
186587  iOff += nNew;
186588  pIter->iTermLeafOffset = iOff;
186589  pIter->iTermLeafPgno = pIter->iLeafPgno;
186590  pIter->iLeafOffset = iOff;
186591
186592  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
186593    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186594  }else{
186595    int nExtra;
186596    pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
186597    pIter->iEndofDoclist += nExtra;
186598  }
186599
186600  fts5SegIterLoadRowid(p, pIter);
186601}
186602
186603static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
186604static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
186605static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
186606
186607static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
186608  if( pIter->flags & FTS5_SEGITER_REVERSE ){
186609    pIter->xNext = fts5SegIterNext_Reverse;
186610  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
186611    pIter->xNext = fts5SegIterNext_None;
186612  }else{
186613    pIter->xNext = fts5SegIterNext;
186614  }
186615}
186616
186617/*
186618** Initialize the iterator object pIter to iterate through the entries in
186619** segment pSeg. The iterator is left pointing to the first entry when
186620** this function returns.
186621**
186622** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
186623** an error has already occurred when this function is called, it is a no-op.
186624*/
186625static void fts5SegIterInit(
186626  Fts5Index *p,                   /* FTS index object */
186627  Fts5StructureSegment *pSeg,     /* Description of segment */
186628  Fts5SegIter *pIter              /* Object to populate */
186629){
186630  if( pSeg->pgnoFirst==0 ){
186631    /* This happens if the segment is being used as an input to an incremental
186632    ** merge and all data has already been "trimmed". See function
186633    ** fts5TrimSegments() for details. In this case leave the iterator empty.
186634    ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
186635    ** at EOF already. */
186636    assert( pIter->pLeaf==0 );
186637    return;
186638  }
186639
186640  if( p->rc==SQLITE_OK ){
186641    memset(pIter, 0, sizeof(*pIter));
186642    fts5SegIterSetNext(p, pIter);
186643    pIter->pSeg = pSeg;
186644    pIter->iLeafPgno = pSeg->pgnoFirst-1;
186645    fts5SegIterNextPage(p, pIter);
186646  }
186647
186648  if( p->rc==SQLITE_OK ){
186649    pIter->iLeafOffset = 4;
186650    assert_nc( pIter->pLeaf->nn>4 );
186651    assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
186652    pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
186653    fts5SegIterLoadTerm(p, pIter, 0);
186654    fts5SegIterLoadNPos(p, pIter);
186655  }
186656}
186657
186658/*
186659** This function is only ever called on iterators created by calls to
186660** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
186661**
186662** The iterator is in an unusual state when this function is called: the
186663** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
186664** the position-list size field for the first relevant rowid on the page.
186665** Fts5SegIter.rowid is set, but nPos and bDel are not.
186666**
186667** This function advances the iterator so that it points to the last
186668** relevant rowid on the page and, if necessary, initializes the
186669** aRowidOffset[] and iRowidOffset variables. At this point the iterator
186670** is in its regular state - Fts5SegIter.iLeafOffset points to the first
186671** byte of the position list content associated with said rowid.
186672*/
186673static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
186674  int eDetail = p->pConfig->eDetail;
186675  int n = pIter->pLeaf->szLeaf;
186676  int i = pIter->iLeafOffset;
186677  u8 *a = pIter->pLeaf->p;
186678  int iRowidOffset = 0;
186679
186680  if( n>pIter->iEndofDoclist ){
186681    n = pIter->iEndofDoclist;
186682  }
186683
186684  ASSERT_SZLEAF_OK(pIter->pLeaf);
186685  while( 1 ){
186686    i64 iDelta = 0;
186687
186688    if( eDetail==FTS5_DETAIL_NONE ){
186689      /* todo */
186690      if( i<n && a[i]==0 ){
186691        i++;
186692        if( i<n && a[i]==0 ) i++;
186693      }
186694    }else{
186695      int nPos;
186696      int bDummy;
186697      i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
186698      i += nPos;
186699    }
186700    if( i>=n ) break;
186701    i += fts5GetVarint(&a[i], (u64*)&iDelta);
186702    pIter->iRowid += iDelta;
186703
186704    /* If necessary, grow the pIter->aRowidOffset[] array. */
186705    if( iRowidOffset>=pIter->nRowidOffset ){
186706      int nNew = pIter->nRowidOffset + 8;
186707      int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
186708      if( aNew==0 ){
186709        p->rc = SQLITE_NOMEM;
186710        break;
186711      }
186712      pIter->aRowidOffset = aNew;
186713      pIter->nRowidOffset = nNew;
186714    }
186715
186716    pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
186717    pIter->iLeafOffset = i;
186718  }
186719  pIter->iRowidOffset = iRowidOffset;
186720  fts5SegIterLoadNPos(p, pIter);
186721}
186722
186723/*
186724**
186725*/
186726static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
186727  assert( pIter->flags & FTS5_SEGITER_REVERSE );
186728  assert( pIter->flags & FTS5_SEGITER_ONETERM );
186729
186730  fts5DataRelease(pIter->pLeaf);
186731  pIter->pLeaf = 0;
186732  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
186733    Fts5Data *pNew;
186734    pIter->iLeafPgno--;
186735    pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
186736          pIter->pSeg->iSegid, pIter->iLeafPgno
186737    ));
186738    if( pNew ){
186739      /* iTermLeafOffset may be equal to szLeaf if the term is the last
186740      ** thing on the page - i.e. the first rowid is on the following page.
186741      ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
186742      if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
186743        assert( pIter->pLeaf==0 );
186744        if( pIter->iTermLeafOffset<pNew->szLeaf ){
186745          pIter->pLeaf = pNew;
186746          pIter->iLeafOffset = pIter->iTermLeafOffset;
186747        }
186748      }else{
186749        int iRowidOff;
186750        iRowidOff = fts5LeafFirstRowidOff(pNew);
186751        if( iRowidOff ){
186752          pIter->pLeaf = pNew;
186753          pIter->iLeafOffset = iRowidOff;
186754        }
186755      }
186756
186757      if( pIter->pLeaf ){
186758        u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
186759        pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
186760        break;
186761      }else{
186762        fts5DataRelease(pNew);
186763      }
186764    }
186765  }
186766
186767  if( pIter->pLeaf ){
186768    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186769    fts5SegIterReverseInitPage(p, pIter);
186770  }
186771}
186772
186773/*
186774** Return true if the iterator passed as the second argument currently
186775** points to a delete marker. A delete marker is an entry with a 0 byte
186776** position-list.
186777*/
186778static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
186779  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
186780  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
186781}
186782
186783/*
186784** Advance iterator pIter to the next entry.
186785**
186786** This version of fts5SegIterNext() is only used by reverse iterators.
186787*/
186788static void fts5SegIterNext_Reverse(
186789  Fts5Index *p,                   /* FTS5 backend object */
186790  Fts5SegIter *pIter,             /* Iterator to advance */
186791  int *pbUnused                   /* Unused */
186792){
186793  assert( pIter->flags & FTS5_SEGITER_REVERSE );
186794  assert( pIter->pNextLeaf==0 );
186795  UNUSED_PARAM(pbUnused);
186796
186797  if( pIter->iRowidOffset>0 ){
186798    u8 *a = pIter->pLeaf->p;
186799    int iOff;
186800    i64 iDelta;
186801
186802    pIter->iRowidOffset--;
186803    pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
186804    fts5SegIterLoadNPos(p, pIter);
186805    iOff = pIter->iLeafOffset;
186806    if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
186807      iOff += pIter->nPos;
186808    }
186809    fts5GetVarint(&a[iOff], (u64*)&iDelta);
186810    pIter->iRowid -= iDelta;
186811  }else{
186812    fts5SegIterReverseNewPage(p, pIter);
186813  }
186814}
186815
186816/*
186817** Advance iterator pIter to the next entry.
186818**
186819** This version of fts5SegIterNext() is only used if detail=none and the
186820** iterator is not a reverse direction iterator.
186821*/
186822static void fts5SegIterNext_None(
186823  Fts5Index *p,                   /* FTS5 backend object */
186824  Fts5SegIter *pIter,             /* Iterator to advance */
186825  int *pbNewTerm                  /* OUT: Set for new term */
186826){
186827  int iOff;
186828
186829  assert( p->rc==SQLITE_OK );
186830  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
186831  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
186832
186833  ASSERT_SZLEAF_OK(pIter->pLeaf);
186834  iOff = pIter->iLeafOffset;
186835
186836  /* Next entry is on the next page */
186837  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
186838    fts5SegIterNextPage(p, pIter);
186839    if( p->rc || pIter->pLeaf==0 ) return;
186840    pIter->iRowid = 0;
186841    iOff = 4;
186842  }
186843
186844  if( iOff<pIter->iEndofDoclist ){
186845    /* Next entry is on the current page */
186846    i64 iDelta;
186847    iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
186848    pIter->iLeafOffset = iOff;
186849    pIter->iRowid += iDelta;
186850  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
186851    if( pIter->pSeg ){
186852      int nKeep = 0;
186853      if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
186854        iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
186855      }
186856      pIter->iLeafOffset = iOff;
186857      fts5SegIterLoadTerm(p, pIter, nKeep);
186858    }else{
186859      const u8 *pList = 0;
186860      const char *zTerm = 0;
186861      int nList;
186862      sqlite3Fts5HashScanNext(p->pHash);
186863      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
186864      if( pList==0 ) goto next_none_eof;
186865      pIter->pLeaf->p = (u8*)pList;
186866      pIter->pLeaf->nn = nList;
186867      pIter->pLeaf->szLeaf = nList;
186868      pIter->iEndofDoclist = nList;
186869      sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
186870      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
186871    }
186872
186873    if( pbNewTerm ) *pbNewTerm = 1;
186874  }else{
186875    goto next_none_eof;
186876  }
186877
186878  fts5SegIterLoadNPos(p, pIter);
186879
186880  return;
186881 next_none_eof:
186882  fts5DataRelease(pIter->pLeaf);
186883  pIter->pLeaf = 0;
186884}
186885
186886
186887/*
186888** Advance iterator pIter to the next entry.
186889**
186890** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
186891** is not considered an error if the iterator reaches EOF. If an error has
186892** already occurred when this function is called, it is a no-op.
186893*/
186894static void fts5SegIterNext(
186895  Fts5Index *p,                   /* FTS5 backend object */
186896  Fts5SegIter *pIter,             /* Iterator to advance */
186897  int *pbNewTerm                  /* OUT: Set for new term */
186898){
186899  Fts5Data *pLeaf = pIter->pLeaf;
186900  int iOff;
186901  int bNewTerm = 0;
186902  int nKeep = 0;
186903  u8 *a;
186904  int n;
186905
186906  assert( pbNewTerm==0 || *pbNewTerm==0 );
186907  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
186908
186909  /* Search for the end of the position list within the current page. */
186910  a = pLeaf->p;
186911  n = pLeaf->szLeaf;
186912
186913  ASSERT_SZLEAF_OK(pLeaf);
186914  iOff = pIter->iLeafOffset + pIter->nPos;
186915
186916  if( iOff<n ){
186917    /* The next entry is on the current page. */
186918    assert_nc( iOff<=pIter->iEndofDoclist );
186919    if( iOff>=pIter->iEndofDoclist ){
186920      bNewTerm = 1;
186921      if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
186922        iOff += fts5GetVarint32(&a[iOff], nKeep);
186923      }
186924    }else{
186925      u64 iDelta;
186926      iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
186927      pIter->iRowid += iDelta;
186928      assert_nc( iDelta>0 );
186929    }
186930    pIter->iLeafOffset = iOff;
186931
186932  }else if( pIter->pSeg==0 ){
186933    const u8 *pList = 0;
186934    const char *zTerm = 0;
186935    int nList = 0;
186936    assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
186937    if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
186938      sqlite3Fts5HashScanNext(p->pHash);
186939      sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
186940    }
186941    if( pList==0 ){
186942      fts5DataRelease(pIter->pLeaf);
186943      pIter->pLeaf = 0;
186944    }else{
186945      pIter->pLeaf->p = (u8*)pList;
186946      pIter->pLeaf->nn = nList;
186947      pIter->pLeaf->szLeaf = nList;
186948      pIter->iEndofDoclist = nList+1;
186949      sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
186950          (u8*)zTerm);
186951      pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
186952      *pbNewTerm = 1;
186953    }
186954  }else{
186955    iOff = 0;
186956    /* Next entry is not on the current page */
186957    while( iOff==0 ){
186958      fts5SegIterNextPage(p, pIter);
186959      pLeaf = pIter->pLeaf;
186960      if( pLeaf==0 ) break;
186961      ASSERT_SZLEAF_OK(pLeaf);
186962      if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
186963        iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
186964        pIter->iLeafOffset = iOff;
186965
186966        if( pLeaf->nn>pLeaf->szLeaf ){
186967          pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
186968              &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
186969              );
186970        }
186971
186972      }
186973      else if( pLeaf->nn>pLeaf->szLeaf ){
186974        pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
186975            &pLeaf->p[pLeaf->szLeaf], iOff
186976            );
186977        pIter->iLeafOffset = iOff;
186978        pIter->iEndofDoclist = iOff;
186979        bNewTerm = 1;
186980      }
186981      assert_nc( iOff<pLeaf->szLeaf );
186982      if( iOff>pLeaf->szLeaf ){
186983        p->rc = FTS5_CORRUPT;
186984        return;
186985      }
186986    }
186987  }
186988
186989  /* Check if the iterator is now at EOF. If so, return early. */
186990  if( pIter->pLeaf ){
186991    if( bNewTerm ){
186992      if( pIter->flags & FTS5_SEGITER_ONETERM ){
186993        fts5DataRelease(pIter->pLeaf);
186994        pIter->pLeaf = 0;
186995      }else{
186996        fts5SegIterLoadTerm(p, pIter, nKeep);
186997        fts5SegIterLoadNPos(p, pIter);
186998        if( pbNewTerm ) *pbNewTerm = 1;
186999      }
187000    }else{
187001      /* The following could be done by calling fts5SegIterLoadNPos(). But
187002      ** this block is particularly performance critical, so equivalent
187003      ** code is inlined.
187004      **
187005      ** Later: Switched back to fts5SegIterLoadNPos() because it supports
187006      ** detail=none mode. Not ideal.
187007      */
187008      int nSz;
187009      assert( p->rc==SQLITE_OK );
187010      fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
187011      pIter->bDel = (nSz & 0x0001);
187012      pIter->nPos = nSz>>1;
187013      assert_nc( pIter->nPos>=0 );
187014    }
187015  }
187016}
187017
187018#define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
187019
187020#define fts5IndexSkipVarint(a, iOff) {            \
187021  int iEnd = iOff+9;                              \
187022  while( (a[iOff++] & 0x80) && iOff<iEnd );       \
187023}
187024
187025/*
187026** Iterator pIter currently points to the first rowid in a doclist. This
187027** function sets the iterator up so that iterates in reverse order through
187028** the doclist.
187029*/
187030static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
187031  Fts5DlidxIter *pDlidx = pIter->pDlidx;
187032  Fts5Data *pLast = 0;
187033  int pgnoLast = 0;
187034
187035  if( pDlidx ){
187036    int iSegid = pIter->pSeg->iSegid;
187037    pgnoLast = fts5DlidxIterPgno(pDlidx);
187038    pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
187039  }else{
187040    Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
187041
187042    /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
187043    ** position-list content for the current rowid. Back it up so that it
187044    ** points to the start of the position-list size field. */
187045    int iPoslist;
187046    if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
187047      iPoslist = pIter->iTermLeafOffset;
187048    }else{
187049      iPoslist = 4;
187050    }
187051    fts5IndexSkipVarint(pLeaf->p, iPoslist);
187052    pIter->iLeafOffset = iPoslist;
187053
187054    /* If this condition is true then the largest rowid for the current
187055    ** term may not be stored on the current page. So search forward to
187056    ** see where said rowid really is.  */
187057    if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
187058      int pgno;
187059      Fts5StructureSegment *pSeg = pIter->pSeg;
187060
187061      /* The last rowid in the doclist may not be on the current page. Search
187062      ** forward to find the page containing the last rowid.  */
187063      for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
187064        i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
187065        Fts5Data *pNew = fts5DataRead(p, iAbs);
187066        if( pNew ){
187067          int iRowid, bTermless;
187068          iRowid = fts5LeafFirstRowidOff(pNew);
187069          bTermless = fts5LeafIsTermless(pNew);
187070          if( iRowid ){
187071            SWAPVAL(Fts5Data*, pNew, pLast);
187072            pgnoLast = pgno;
187073          }
187074          fts5DataRelease(pNew);
187075          if( bTermless==0 ) break;
187076        }
187077      }
187078    }
187079  }
187080
187081  /* If pLast is NULL at this point, then the last rowid for this doclist
187082  ** lies on the page currently indicated by the iterator. In this case
187083  ** pIter->iLeafOffset is already set to point to the position-list size
187084  ** field associated with the first relevant rowid on the page.
187085  **
187086  ** Or, if pLast is non-NULL, then it is the page that contains the last
187087  ** rowid. In this case configure the iterator so that it points to the
187088  ** first rowid on this page.
187089  */
187090  if( pLast ){
187091    int iOff;
187092    fts5DataRelease(pIter->pLeaf);
187093    pIter->pLeaf = pLast;
187094    pIter->iLeafPgno = pgnoLast;
187095    iOff = fts5LeafFirstRowidOff(pLast);
187096    iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
187097    pIter->iLeafOffset = iOff;
187098
187099    if( fts5LeafIsTermless(pLast) ){
187100      pIter->iEndofDoclist = pLast->nn+1;
187101    }else{
187102      pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
187103    }
187104
187105  }
187106
187107  fts5SegIterReverseInitPage(p, pIter);
187108}
187109
187110/*
187111** Iterator pIter currently points to the first rowid of a doclist.
187112** There is a doclist-index associated with the final term on the current
187113** page. If the current term is the last term on the page, load the
187114** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
187115*/
187116static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
187117  int iSeg = pIter->pSeg->iSegid;
187118  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
187119  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
187120
187121  assert( pIter->flags & FTS5_SEGITER_ONETERM );
187122  assert( pIter->pDlidx==0 );
187123
187124  /* Check if the current doclist ends on this page. If it does, return
187125  ** early without loading the doclist-index (as it belongs to a different
187126  ** term. */
187127  if( pIter->iTermLeafPgno==pIter->iLeafPgno
187128   && pIter->iEndofDoclist<pLeaf->szLeaf
187129  ){
187130    return;
187131  }
187132
187133  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
187134}
187135
187136/*
187137** The iterator object passed as the second argument currently contains
187138** no valid values except for the Fts5SegIter.pLeaf member variable. This
187139** function searches the leaf page for a term matching (pTerm/nTerm).
187140**
187141** If the specified term is found on the page, then the iterator is left
187142** pointing to it. If argument bGe is zero and the term is not found,
187143** the iterator is left pointing at EOF.
187144**
187145** If bGe is non-zero and the specified term is not found, then the
187146** iterator is left pointing to the smallest term in the segment that
187147** is larger than the specified term, even if this term is not on the
187148** current page.
187149*/
187150static void fts5LeafSeek(
187151  Fts5Index *p,                   /* Leave any error code here */
187152  int bGe,                        /* True for a >= search */
187153  Fts5SegIter *pIter,             /* Iterator to seek */
187154  const u8 *pTerm, int nTerm      /* Term to search for */
187155){
187156  int iOff;
187157  const u8 *a = pIter->pLeaf->p;
187158  int szLeaf = pIter->pLeaf->szLeaf;
187159  int n = pIter->pLeaf->nn;
187160
187161  int nMatch = 0;
187162  int nKeep = 0;
187163  int nNew = 0;
187164  int iTermOff;
187165  int iPgidx;                     /* Current offset in pgidx */
187166  int bEndOfPage = 0;
187167
187168  assert( p->rc==SQLITE_OK );
187169
187170  iPgidx = szLeaf;
187171  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
187172  iOff = iTermOff;
187173  if( iOff>n ){
187174    p->rc = FTS5_CORRUPT;
187175    return;
187176  }
187177
187178  while( 1 ){
187179
187180    /* Figure out how many new bytes are in this term */
187181    fts5FastGetVarint32(a, iOff, nNew);
187182    if( nKeep<nMatch ){
187183      goto search_failed;
187184    }
187185
187186    assert( nKeep>=nMatch );
187187    if( nKeep==nMatch ){
187188      int nCmp;
187189      int i;
187190      nCmp = MIN(nNew, nTerm-nMatch);
187191      for(i=0; i<nCmp; i++){
187192        if( a[iOff+i]!=pTerm[nMatch+i] ) break;
187193      }
187194      nMatch += i;
187195
187196      if( nTerm==nMatch ){
187197        if( i==nNew ){
187198          goto search_success;
187199        }else{
187200          goto search_failed;
187201        }
187202      }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
187203        goto search_failed;
187204      }
187205    }
187206
187207    if( iPgidx>=n ){
187208      bEndOfPage = 1;
187209      break;
187210    }
187211
187212    iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
187213    iTermOff += nKeep;
187214    iOff = iTermOff;
187215
187216    /* Read the nKeep field of the next term. */
187217    fts5FastGetVarint32(a, iOff, nKeep);
187218  }
187219
187220 search_failed:
187221  if( bGe==0 ){
187222    fts5DataRelease(pIter->pLeaf);
187223    pIter->pLeaf = 0;
187224    return;
187225  }else if( bEndOfPage ){
187226    do {
187227      fts5SegIterNextPage(p, pIter);
187228      if( pIter->pLeaf==0 ) return;
187229      a = pIter->pLeaf->p;
187230      if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
187231        iPgidx = pIter->pLeaf->szLeaf;
187232        iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
187233        if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
187234          p->rc = FTS5_CORRUPT;
187235        }else{
187236          nKeep = 0;
187237          iTermOff = iOff;
187238          n = pIter->pLeaf->nn;
187239          iOff += fts5GetVarint32(&a[iOff], nNew);
187240          break;
187241        }
187242      }
187243    }while( 1 );
187244  }
187245
187246 search_success:
187247
187248  pIter->iLeafOffset = iOff + nNew;
187249  pIter->iTermLeafOffset = pIter->iLeafOffset;
187250  pIter->iTermLeafPgno = pIter->iLeafPgno;
187251
187252  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
187253  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
187254
187255  if( iPgidx>=n ){
187256    pIter->iEndofDoclist = pIter->pLeaf->nn+1;
187257  }else{
187258    int nExtra;
187259    iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
187260    pIter->iEndofDoclist = iTermOff + nExtra;
187261  }
187262  pIter->iPgidxOff = iPgidx;
187263
187264  fts5SegIterLoadRowid(p, pIter);
187265  fts5SegIterLoadNPos(p, pIter);
187266}
187267
187268static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
187269  if( p->pIdxSelect==0 ){
187270    Fts5Config *pConfig = p->pConfig;
187271    fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
187272          "SELECT pgno FROM '%q'.'%q_idx' WHERE "
187273          "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
187274          pConfig->zDb, pConfig->zName
187275    ));
187276  }
187277  return p->pIdxSelect;
187278}
187279
187280/*
187281** Initialize the object pIter to point to term pTerm/nTerm within segment
187282** pSeg. If there is no such term in the index, the iterator is set to EOF.
187283**
187284** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
187285** an error has already occurred when this function is called, it is a no-op.
187286*/
187287static void fts5SegIterSeekInit(
187288  Fts5Index *p,                   /* FTS5 backend */
187289  const u8 *pTerm, int nTerm,     /* Term to seek to */
187290  int flags,                      /* Mask of FTS5INDEX_XXX flags */
187291  Fts5StructureSegment *pSeg,     /* Description of segment */
187292  Fts5SegIter *pIter              /* Object to populate */
187293){
187294  int iPg = 1;
187295  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
187296  int bDlidx = 0;                 /* True if there is a doclist-index */
187297  sqlite3_stmt *pIdxSelect = 0;
187298
187299  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
187300  assert( pTerm && nTerm );
187301  memset(pIter, 0, sizeof(*pIter));
187302  pIter->pSeg = pSeg;
187303
187304  /* This block sets stack variable iPg to the leaf page number that may
187305  ** contain term (pTerm/nTerm), if it is present in the segment. */
187306  pIdxSelect = fts5IdxSelectStmt(p);
187307  if( p->rc ) return;
187308  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
187309  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
187310  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
187311    i64 val = sqlite3_column_int(pIdxSelect, 0);
187312    iPg = (int)(val>>1);
187313    bDlidx = (val & 0x0001);
187314  }
187315  p->rc = sqlite3_reset(pIdxSelect);
187316
187317  if( iPg<pSeg->pgnoFirst ){
187318    iPg = pSeg->pgnoFirst;
187319    bDlidx = 0;
187320  }
187321
187322  pIter->iLeafPgno = iPg - 1;
187323  fts5SegIterNextPage(p, pIter);
187324
187325  if( pIter->pLeaf ){
187326    fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
187327  }
187328
187329  if( p->rc==SQLITE_OK && bGe==0 ){
187330    pIter->flags |= FTS5_SEGITER_ONETERM;
187331    if( pIter->pLeaf ){
187332      if( flags & FTS5INDEX_QUERY_DESC ){
187333        pIter->flags |= FTS5_SEGITER_REVERSE;
187334      }
187335      if( bDlidx ){
187336        fts5SegIterLoadDlidx(p, pIter);
187337      }
187338      if( flags & FTS5INDEX_QUERY_DESC ){
187339        fts5SegIterReverse(p, pIter);
187340      }
187341    }
187342  }
187343
187344  fts5SegIterSetNext(p, pIter);
187345
187346  /* Either:
187347  **
187348  **   1) an error has occurred, or
187349  **   2) the iterator points to EOF, or
187350  **   3) the iterator points to an entry with term (pTerm/nTerm), or
187351  **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
187352  **      to an entry with a term greater than or equal to (pTerm/nTerm).
187353  */
187354  assert( p->rc!=SQLITE_OK                                          /* 1 */
187355   || pIter->pLeaf==0                                               /* 2 */
187356   || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
187357   || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
187358  );
187359}
187360
187361/*
187362** Initialize the object pIter to point to term pTerm/nTerm within the
187363** in-memory hash table. If there is no such term in the hash-table, the
187364** iterator is set to EOF.
187365**
187366** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
187367** an error has already occurred when this function is called, it is a no-op.
187368*/
187369static void fts5SegIterHashInit(
187370  Fts5Index *p,                   /* FTS5 backend */
187371  const u8 *pTerm, int nTerm,     /* Term to seek to */
187372  int flags,                      /* Mask of FTS5INDEX_XXX flags */
187373  Fts5SegIter *pIter              /* Object to populate */
187374){
187375  const u8 *pList = 0;
187376  int nList = 0;
187377  const u8 *z = 0;
187378  int n = 0;
187379
187380  assert( p->pHash );
187381  assert( p->rc==SQLITE_OK );
187382
187383  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
187384    p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
187385    sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
187386    n = (z ? (int)strlen((const char*)z) : 0);
187387  }else{
187388    pIter->flags |= FTS5_SEGITER_ONETERM;
187389    sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
187390    z = pTerm;
187391    n = nTerm;
187392  }
187393
187394  if( pList ){
187395    Fts5Data *pLeaf;
187396    sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
187397    pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
187398    if( pLeaf==0 ) return;
187399    pLeaf->p = (u8*)pList;
187400    pLeaf->nn = pLeaf->szLeaf = nList;
187401    pIter->pLeaf = pLeaf;
187402    pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
187403    pIter->iEndofDoclist = pLeaf->nn;
187404
187405    if( flags & FTS5INDEX_QUERY_DESC ){
187406      pIter->flags |= FTS5_SEGITER_REVERSE;
187407      fts5SegIterReverseInitPage(p, pIter);
187408    }else{
187409      fts5SegIterLoadNPos(p, pIter);
187410    }
187411  }
187412
187413  fts5SegIterSetNext(p, pIter);
187414}
187415
187416/*
187417** Zero the iterator passed as the only argument.
187418*/
187419static void fts5SegIterClear(Fts5SegIter *pIter){
187420  fts5BufferFree(&pIter->term);
187421  fts5DataRelease(pIter->pLeaf);
187422  fts5DataRelease(pIter->pNextLeaf);
187423  fts5DlidxIterFree(pIter->pDlidx);
187424  sqlite3_free(pIter->aRowidOffset);
187425  memset(pIter, 0, sizeof(Fts5SegIter));
187426}
187427
187428#ifdef SQLITE_DEBUG
187429
187430/*
187431** This function is used as part of the big assert() procedure implemented by
187432** fts5AssertMultiIterSetup(). It ensures that the result currently stored
187433** in *pRes is the correct result of comparing the current positions of the
187434** two iterators.
187435*/
187436static void fts5AssertComparisonResult(
187437  Fts5Iter *pIter,
187438  Fts5SegIter *p1,
187439  Fts5SegIter *p2,
187440  Fts5CResult *pRes
187441){
187442  int i1 = p1 - pIter->aSeg;
187443  int i2 = p2 - pIter->aSeg;
187444
187445  if( p1->pLeaf || p2->pLeaf ){
187446    if( p1->pLeaf==0 ){
187447      assert( pRes->iFirst==i2 );
187448    }else if( p2->pLeaf==0 ){
187449      assert( pRes->iFirst==i1 );
187450    }else{
187451      int nMin = MIN(p1->term.n, p2->term.n);
187452      int res = memcmp(p1->term.p, p2->term.p, nMin);
187453      if( res==0 ) res = p1->term.n - p2->term.n;
187454
187455      if( res==0 ){
187456        assert( pRes->bTermEq==1 );
187457        assert( p1->iRowid!=p2->iRowid );
187458        res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
187459      }else{
187460        assert( pRes->bTermEq==0 );
187461      }
187462
187463      if( res<0 ){
187464        assert( pRes->iFirst==i1 );
187465      }else{
187466        assert( pRes->iFirst==i2 );
187467      }
187468    }
187469  }
187470}
187471
187472/*
187473** This function is a no-op unless SQLITE_DEBUG is defined when this module
187474** is compiled. In that case, this function is essentially an assert()
187475** statement used to verify that the contents of the pIter->aFirst[] array
187476** are correct.
187477*/
187478static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
187479  if( p->rc==SQLITE_OK ){
187480    Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187481    int i;
187482
187483    assert( (pFirst->pLeaf==0)==pIter->base.bEof );
187484
187485    /* Check that pIter->iSwitchRowid is set correctly. */
187486    for(i=0; i<pIter->nSeg; i++){
187487      Fts5SegIter *p1 = &pIter->aSeg[i];
187488      assert( p1==pFirst
187489           || p1->pLeaf==0
187490           || fts5BufferCompare(&pFirst->term, &p1->term)
187491           || p1->iRowid==pIter->iSwitchRowid
187492           || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
187493      );
187494    }
187495
187496    for(i=0; i<pIter->nSeg; i+=2){
187497      Fts5SegIter *p1 = &pIter->aSeg[i];
187498      Fts5SegIter *p2 = &pIter->aSeg[i+1];
187499      Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
187500      fts5AssertComparisonResult(pIter, p1, p2, pRes);
187501    }
187502
187503    for(i=1; i<(pIter->nSeg / 2); i+=2){
187504      Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
187505      Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
187506      Fts5CResult *pRes = &pIter->aFirst[i];
187507      fts5AssertComparisonResult(pIter, p1, p2, pRes);
187508    }
187509  }
187510}
187511#else
187512# define fts5AssertMultiIterSetup(x,y)
187513#endif
187514
187515/*
187516** Do the comparison necessary to populate pIter->aFirst[iOut].
187517**
187518** If the returned value is non-zero, then it is the index of an entry
187519** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
187520** to a key that is a duplicate of another, higher priority,
187521** segment-iterator in the pSeg->aSeg[] array.
187522*/
187523static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
187524  int i1;                         /* Index of left-hand Fts5SegIter */
187525  int i2;                         /* Index of right-hand Fts5SegIter */
187526  int iRes;
187527  Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
187528  Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
187529  Fts5CResult *pRes = &pIter->aFirst[iOut];
187530
187531  assert( iOut<pIter->nSeg && iOut>0 );
187532  assert( pIter->bRev==0 || pIter->bRev==1 );
187533
187534  if( iOut>=(pIter->nSeg/2) ){
187535    i1 = (iOut - pIter->nSeg/2) * 2;
187536    i2 = i1 + 1;
187537  }else{
187538    i1 = pIter->aFirst[iOut*2].iFirst;
187539    i2 = pIter->aFirst[iOut*2+1].iFirst;
187540  }
187541  p1 = &pIter->aSeg[i1];
187542  p2 = &pIter->aSeg[i2];
187543
187544  pRes->bTermEq = 0;
187545  if( p1->pLeaf==0 ){           /* If p1 is at EOF */
187546    iRes = i2;
187547  }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
187548    iRes = i1;
187549  }else{
187550    int res = fts5BufferCompare(&p1->term, &p2->term);
187551    if( res==0 ){
187552      assert( i2>i1 );
187553      assert( i2!=0 );
187554      pRes->bTermEq = 1;
187555      if( p1->iRowid==p2->iRowid ){
187556        p1->bDel = p2->bDel;
187557        return i2;
187558      }
187559      res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
187560    }
187561    assert( res!=0 );
187562    if( res<0 ){
187563      iRes = i1;
187564    }else{
187565      iRes = i2;
187566    }
187567  }
187568
187569  pRes->iFirst = (u16)iRes;
187570  return 0;
187571}
187572
187573/*
187574** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
187575** It is an error if leaf iLeafPgno does not exist or contains no rowids.
187576*/
187577static void fts5SegIterGotoPage(
187578  Fts5Index *p,                   /* FTS5 backend object */
187579  Fts5SegIter *pIter,             /* Iterator to advance */
187580  int iLeafPgno
187581){
187582  assert( iLeafPgno>pIter->iLeafPgno );
187583
187584  if( iLeafPgno>pIter->pSeg->pgnoLast ){
187585    p->rc = FTS5_CORRUPT;
187586  }else{
187587    fts5DataRelease(pIter->pNextLeaf);
187588    pIter->pNextLeaf = 0;
187589    pIter->iLeafPgno = iLeafPgno-1;
187590    fts5SegIterNextPage(p, pIter);
187591    assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
187592
187593    if( p->rc==SQLITE_OK ){
187594      int iOff;
187595      u8 *a = pIter->pLeaf->p;
187596      int n = pIter->pLeaf->szLeaf;
187597
187598      iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
187599      if( iOff<4 || iOff>=n ){
187600        p->rc = FTS5_CORRUPT;
187601      }else{
187602        iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
187603        pIter->iLeafOffset = iOff;
187604        fts5SegIterLoadNPos(p, pIter);
187605      }
187606    }
187607  }
187608}
187609
187610/*
187611** Advance the iterator passed as the second argument until it is at or
187612** past rowid iFrom. Regardless of the value of iFrom, the iterator is
187613** always advanced at least once.
187614*/
187615static void fts5SegIterNextFrom(
187616  Fts5Index *p,                   /* FTS5 backend object */
187617  Fts5SegIter *pIter,             /* Iterator to advance */
187618  i64 iMatch                      /* Advance iterator at least this far */
187619){
187620  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
187621  Fts5DlidxIter *pDlidx = pIter->pDlidx;
187622  int iLeafPgno = pIter->iLeafPgno;
187623  int bMove = 1;
187624
187625  assert( pIter->flags & FTS5_SEGITER_ONETERM );
187626  assert( pIter->pDlidx );
187627  assert( pIter->pLeaf );
187628
187629  if( bRev==0 ){
187630    while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
187631      iLeafPgno = fts5DlidxIterPgno(pDlidx);
187632      fts5DlidxIterNext(p, pDlidx);
187633    }
187634    assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
187635    if( iLeafPgno>pIter->iLeafPgno ){
187636      fts5SegIterGotoPage(p, pIter, iLeafPgno);
187637      bMove = 0;
187638    }
187639  }else{
187640    assert( pIter->pNextLeaf==0 );
187641    assert( iMatch<pIter->iRowid );
187642    while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
187643      fts5DlidxIterPrev(p, pDlidx);
187644    }
187645    iLeafPgno = fts5DlidxIterPgno(pDlidx);
187646
187647    assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
187648
187649    if( iLeafPgno<pIter->iLeafPgno ){
187650      pIter->iLeafPgno = iLeafPgno+1;
187651      fts5SegIterReverseNewPage(p, pIter);
187652      bMove = 0;
187653    }
187654  }
187655
187656  do{
187657    if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
187658    if( pIter->pLeaf==0 ) break;
187659    if( bRev==0 && pIter->iRowid>=iMatch ) break;
187660    if( bRev!=0 && pIter->iRowid<=iMatch ) break;
187661    bMove = 1;
187662  }while( p->rc==SQLITE_OK );
187663}
187664
187665
187666/*
187667** Free the iterator object passed as the second argument.
187668*/
187669static void fts5MultiIterFree(Fts5Iter *pIter){
187670  if( pIter ){
187671    int i;
187672    for(i=0; i<pIter->nSeg; i++){
187673      fts5SegIterClear(&pIter->aSeg[i]);
187674    }
187675    fts5StructureRelease(pIter->pStruct);
187676    fts5BufferFree(&pIter->poslist);
187677    sqlite3_free(pIter);
187678  }
187679}
187680
187681static void fts5MultiIterAdvanced(
187682  Fts5Index *p,                   /* FTS5 backend to iterate within */
187683  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
187684  int iChanged,                   /* Index of sub-iterator just advanced */
187685  int iMinset                     /* Minimum entry in aFirst[] to set */
187686){
187687  int i;
187688  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
187689    int iEq;
187690    if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
187691      Fts5SegIter *pSeg = &pIter->aSeg[iEq];
187692      assert( p->rc==SQLITE_OK );
187693      pSeg->xNext(p, pSeg, 0);
187694      i = pIter->nSeg + iEq;
187695    }
187696  }
187697}
187698
187699/*
187700** Sub-iterator iChanged of iterator pIter has just been advanced. It still
187701** points to the same term though - just a different rowid. This function
187702** attempts to update the contents of the pIter->aFirst[] accordingly.
187703** If it does so successfully, 0 is returned. Otherwise 1.
187704**
187705** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
187706** on the iterator instead. That function does the same as this one, except
187707** that it deals with more complicated cases as well.
187708*/
187709static int fts5MultiIterAdvanceRowid(
187710  Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
187711  int iChanged,                   /* Index of sub-iterator just advanced */
187712  Fts5SegIter **ppFirst
187713){
187714  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
187715
187716  if( pNew->iRowid==pIter->iSwitchRowid
187717   || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
187718  ){
187719    int i;
187720    Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
187721    pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
187722    for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
187723      Fts5CResult *pRes = &pIter->aFirst[i];
187724
187725      assert( pNew->pLeaf );
187726      assert( pRes->bTermEq==0 || pOther->pLeaf );
187727
187728      if( pRes->bTermEq ){
187729        if( pNew->iRowid==pOther->iRowid ){
187730          return 1;
187731        }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
187732          pIter->iSwitchRowid = pOther->iRowid;
187733          pNew = pOther;
187734        }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
187735          pIter->iSwitchRowid = pOther->iRowid;
187736        }
187737      }
187738      pRes->iFirst = (u16)(pNew - pIter->aSeg);
187739      if( i==1 ) break;
187740
187741      pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
187742    }
187743  }
187744
187745  *ppFirst = pNew;
187746  return 0;
187747}
187748
187749/*
187750** Set the pIter->bEof variable based on the state of the sub-iterators.
187751*/
187752static void fts5MultiIterSetEof(Fts5Iter *pIter){
187753  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187754  pIter->base.bEof = pSeg->pLeaf==0;
187755  pIter->iSwitchRowid = pSeg->iRowid;
187756}
187757
187758/*
187759** Move the iterator to the next entry.
187760**
187761** If an error occurs, an error code is left in Fts5Index.rc. It is not
187762** considered an error if the iterator reaches EOF, or if it is already at
187763** EOF when this function is called.
187764*/
187765static void fts5MultiIterNext(
187766  Fts5Index *p,
187767  Fts5Iter *pIter,
187768  int bFrom,                      /* True if argument iFrom is valid */
187769  i64 iFrom                       /* Advance at least as far as this */
187770){
187771  int bUseFrom = bFrom;
187772  while( p->rc==SQLITE_OK ){
187773    int iFirst = pIter->aFirst[1].iFirst;
187774    int bNewTerm = 0;
187775    Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
187776    assert( p->rc==SQLITE_OK );
187777    if( bUseFrom && pSeg->pDlidx ){
187778      fts5SegIterNextFrom(p, pSeg, iFrom);
187779    }else{
187780      pSeg->xNext(p, pSeg, &bNewTerm);
187781    }
187782
187783    if( pSeg->pLeaf==0 || bNewTerm
187784     || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
187785    ){
187786      fts5MultiIterAdvanced(p, pIter, iFirst, 1);
187787      fts5MultiIterSetEof(pIter);
187788      pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
187789      if( pSeg->pLeaf==0 ) return;
187790    }
187791
187792    fts5AssertMultiIterSetup(p, pIter);
187793    assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
187794    if( pIter->bSkipEmpty==0 || pSeg->nPos ){
187795      pIter->xSetOutputs(pIter, pSeg);
187796      return;
187797    }
187798    bUseFrom = 0;
187799  }
187800}
187801
187802static void fts5MultiIterNext2(
187803  Fts5Index *p,
187804  Fts5Iter *pIter,
187805  int *pbNewTerm                  /* OUT: True if *might* be new term */
187806){
187807  assert( pIter->bSkipEmpty );
187808  if( p->rc==SQLITE_OK ){
187809    do {
187810      int iFirst = pIter->aFirst[1].iFirst;
187811      Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
187812      int bNewTerm = 0;
187813
187814      assert( p->rc==SQLITE_OK );
187815      pSeg->xNext(p, pSeg, &bNewTerm);
187816      if( pSeg->pLeaf==0 || bNewTerm
187817       || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
187818      ){
187819        fts5MultiIterAdvanced(p, pIter, iFirst, 1);
187820        fts5MultiIterSetEof(pIter);
187821        *pbNewTerm = 1;
187822      }else{
187823        *pbNewTerm = 0;
187824      }
187825      fts5AssertMultiIterSetup(p, pIter);
187826
187827    }while( fts5MultiIterIsEmpty(p, pIter) );
187828  }
187829}
187830
187831static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
187832  UNUSED_PARAM2(pUnused1, pUnused2);
187833}
187834
187835static Fts5Iter *fts5MultiIterAlloc(
187836  Fts5Index *p,                   /* FTS5 backend to iterate within */
187837  int nSeg
187838){
187839  Fts5Iter *pNew;
187840  int nSlot;                      /* Power of two >= nSeg */
187841
187842  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
187843  pNew = fts5IdxMalloc(p,
187844      sizeof(Fts5Iter) +                  /* pNew */
187845      sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
187846      sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
187847  );
187848  if( pNew ){
187849    pNew->nSeg = nSlot;
187850    pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
187851    pNew->pIndex = p;
187852    pNew->xSetOutputs = fts5IterSetOutputs_Noop;
187853  }
187854  return pNew;
187855}
187856
187857static void fts5PoslistCallback(
187858  Fts5Index *pUnused,
187859  void *pContext,
187860  const u8 *pChunk, int nChunk
187861){
187862  UNUSED_PARAM(pUnused);
187863  assert_nc( nChunk>=0 );
187864  if( nChunk>0 ){
187865    fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
187866  }
187867}
187868
187869typedef struct PoslistCallbackCtx PoslistCallbackCtx;
187870struct PoslistCallbackCtx {
187871  Fts5Buffer *pBuf;               /* Append to this buffer */
187872  Fts5Colset *pColset;            /* Restrict matches to this column */
187873  int eState;                     /* See above */
187874};
187875
187876typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
187877struct PoslistOffsetsCtx {
187878  Fts5Buffer *pBuf;               /* Append to this buffer */
187879  Fts5Colset *pColset;            /* Restrict matches to this column */
187880  int iRead;
187881  int iWrite;
187882};
187883
187884/*
187885** TODO: Make this more efficient!
187886*/
187887static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
187888  int i;
187889  for(i=0; i<pColset->nCol; i++){
187890    if( pColset->aiCol[i]==iCol ) return 1;
187891  }
187892  return 0;
187893}
187894
187895static void fts5PoslistOffsetsCallback(
187896  Fts5Index *pUnused,
187897  void *pContext,
187898  const u8 *pChunk, int nChunk
187899){
187900  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
187901  UNUSED_PARAM(pUnused);
187902  assert_nc( nChunk>=0 );
187903  if( nChunk>0 ){
187904    int i = 0;
187905    while( i<nChunk ){
187906      int iVal;
187907      i += fts5GetVarint32(&pChunk[i], iVal);
187908      iVal += pCtx->iRead - 2;
187909      pCtx->iRead = iVal;
187910      if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
187911        fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
187912        pCtx->iWrite = iVal;
187913      }
187914    }
187915  }
187916}
187917
187918static void fts5PoslistFilterCallback(
187919  Fts5Index *pUnused,
187920  void *pContext,
187921  const u8 *pChunk, int nChunk
187922){
187923  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
187924  UNUSED_PARAM(pUnused);
187925  assert_nc( nChunk>=0 );
187926  if( nChunk>0 ){
187927    /* Search through to find the first varint with value 1. This is the
187928    ** start of the next columns hits. */
187929    int i = 0;
187930    int iStart = 0;
187931
187932    if( pCtx->eState==2 ){
187933      int iCol;
187934      fts5FastGetVarint32(pChunk, i, iCol);
187935      if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
187936        pCtx->eState = 1;
187937        fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
187938      }else{
187939        pCtx->eState = 0;
187940      }
187941    }
187942
187943    do {
187944      while( i<nChunk && pChunk[i]!=0x01 ){
187945        while( pChunk[i] & 0x80 ) i++;
187946        i++;
187947      }
187948      if( pCtx->eState ){
187949        fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
187950      }
187951      if( i<nChunk ){
187952        int iCol;
187953        iStart = i;
187954        i++;
187955        if( i>=nChunk ){
187956          pCtx->eState = 2;
187957        }else{
187958          fts5FastGetVarint32(pChunk, i, iCol);
187959          pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
187960          if( pCtx->eState ){
187961            fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
187962            iStart = i;
187963          }
187964        }
187965      }
187966    }while( i<nChunk );
187967  }
187968}
187969
187970static void fts5ChunkIterate(
187971  Fts5Index *p,                   /* Index object */
187972  Fts5SegIter *pSeg,              /* Poslist of this iterator */
187973  void *pCtx,                     /* Context pointer for xChunk callback */
187974  void (*xChunk)(Fts5Index*, void*, const u8*, int)
187975){
187976  int nRem = pSeg->nPos;          /* Number of bytes still to come */
187977  Fts5Data *pData = 0;
187978  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
187979  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
187980  int pgno = pSeg->iLeafPgno;
187981  int pgnoSave = 0;
187982
187983  /* This function does notmwork with detail=none databases. */
187984  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
187985
187986  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
187987    pgnoSave = pgno+1;
187988  }
187989
187990  while( 1 ){
187991    xChunk(p, pCtx, pChunk, nChunk);
187992    nRem -= nChunk;
187993    fts5DataRelease(pData);
187994    if( nRem<=0 ){
187995      break;
187996    }else{
187997      pgno++;
187998      pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
187999      if( pData==0 ) break;
188000      pChunk = &pData->p[4];
188001      nChunk = MIN(nRem, pData->szLeaf - 4);
188002      if( pgno==pgnoSave ){
188003        assert( pSeg->pNextLeaf==0 );
188004        pSeg->pNextLeaf = pData;
188005        pData = 0;
188006      }
188007    }
188008  }
188009}
188010
188011/*
188012** Iterator pIter currently points to a valid entry (not EOF). This
188013** function appends the position list data for the current entry to
188014** buffer pBuf. It does not make a copy of the position-list size
188015** field.
188016*/
188017static void fts5SegiterPoslist(
188018  Fts5Index *p,
188019  Fts5SegIter *pSeg,
188020  Fts5Colset *pColset,
188021  Fts5Buffer *pBuf
188022){
188023  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
188024    if( pColset==0 ){
188025      fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
188026    }else{
188027      if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
188028        PoslistCallbackCtx sCtx;
188029        sCtx.pBuf = pBuf;
188030        sCtx.pColset = pColset;
188031        sCtx.eState = fts5IndexColsetTest(pColset, 0);
188032        assert( sCtx.eState==0 || sCtx.eState==1 );
188033        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
188034      }else{
188035        PoslistOffsetsCtx sCtx;
188036        memset(&sCtx, 0, sizeof(sCtx));
188037        sCtx.pBuf = pBuf;
188038        sCtx.pColset = pColset;
188039        fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
188040      }
188041    }
188042  }
188043}
188044
188045/*
188046** IN/OUT parameter (*pa) points to a position list n bytes in size. If
188047** the position list contains entries for column iCol, then (*pa) is set
188048** to point to the sub-position-list for that column and the number of
188049** bytes in it returned. Or, if the argument position list does not
188050** contain any entries for column iCol, return 0.
188051*/
188052static int fts5IndexExtractCol(
188053  const u8 **pa,                  /* IN/OUT: Pointer to poslist */
188054  int n,                          /* IN: Size of poslist in bytes */
188055  int iCol                        /* Column to extract from poslist */
188056){
188057  int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
188058  const u8 *p = *pa;
188059  const u8 *pEnd = &p[n];         /* One byte past end of position list */
188060
188061  while( iCol>iCurrent ){
188062    /* Advance pointer p until it points to pEnd or an 0x01 byte that is
188063    ** not part of a varint. Note that it is not possible for a negative
188064    ** or extremely large varint to occur within an uncorrupted position
188065    ** list. So the last byte of each varint may be assumed to have a clear
188066    ** 0x80 bit.  */
188067    while( *p!=0x01 ){
188068      while( *p++ & 0x80 );
188069      if( p>=pEnd ) return 0;
188070    }
188071    *pa = p++;
188072    iCurrent = *p++;
188073    if( iCurrent & 0x80 ){
188074      p--;
188075      p += fts5GetVarint32(p, iCurrent);
188076    }
188077  }
188078  if( iCol!=iCurrent ) return 0;
188079
188080  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
188081  ** not part of a varint */
188082  while( p<pEnd && *p!=0x01 ){
188083    while( *p++ & 0x80 );
188084  }
188085
188086  return p - (*pa);
188087}
188088
188089static int fts5IndexExtractColset (
188090  Fts5Colset *pColset,            /* Colset to filter on */
188091  const u8 *pPos, int nPos,       /* Position list */
188092  Fts5Buffer *pBuf                /* Output buffer */
188093){
188094  int rc = SQLITE_OK;
188095  int i;
188096
188097  fts5BufferZero(pBuf);
188098  for(i=0; i<pColset->nCol; i++){
188099    const u8 *pSub = pPos;
188100    int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
188101    if( nSub ){
188102      fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
188103    }
188104  }
188105  return rc;
188106}
188107
188108/*
188109** xSetOutputs callback used by detail=none tables.
188110*/
188111static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
188112  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
188113  pIter->base.iRowid = pSeg->iRowid;
188114  pIter->base.nData = pSeg->nPos;
188115}
188116
188117/*
188118** xSetOutputs callback used by detail=full and detail=col tables when no
188119** column filters are specified.
188120*/
188121static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
188122  pIter->base.iRowid = pSeg->iRowid;
188123  pIter->base.nData = pSeg->nPos;
188124
188125  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
188126  assert( pIter->pColset==0 );
188127
188128  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
188129    /* All data is stored on the current page. Populate the output
188130    ** variables to point into the body of the page object. */
188131    pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188132  }else{
188133    /* The data is distributed over two or more pages. Copy it into the
188134    ** Fts5Iter.poslist buffer and then set the output pointer to point
188135    ** to this buffer.  */
188136    fts5BufferZero(&pIter->poslist);
188137    fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
188138    pIter->base.pData = pIter->poslist.p;
188139  }
188140}
188141
188142/*
188143** xSetOutputs callback used by detail=col when there is a column filter
188144** and there are 100 or more columns. Also called as a fallback from
188145** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
188146*/
188147static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
188148  fts5BufferZero(&pIter->poslist);
188149  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
188150  pIter->base.iRowid = pSeg->iRowid;
188151  pIter->base.pData = pIter->poslist.p;
188152  pIter->base.nData = pIter->poslist.n;
188153}
188154
188155/*
188156** xSetOutputs callback used when:
188157**
188158**   * detail=col,
188159**   * there is a column filter, and
188160**   * the table contains 100 or fewer columns.
188161**
188162** The last point is to ensure all column numbers are stored as
188163** single-byte varints.
188164*/
188165static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
188166
188167  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188168  assert( pIter->pColset );
188169
188170  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
188171    fts5IterSetOutputs_Col(pIter, pSeg);
188172  }else{
188173    u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
188174    u8 *pEnd = (u8*)&a[pSeg->nPos];
188175    int iPrev = 0;
188176    int *aiCol = pIter->pColset->aiCol;
188177    int *aiColEnd = &aiCol[pIter->pColset->nCol];
188178
188179    u8 *aOut = pIter->poslist.p;
188180    int iPrevOut = 0;
188181
188182    pIter->base.iRowid = pSeg->iRowid;
188183
188184    while( a<pEnd ){
188185      iPrev += (int)a++[0] - 2;
188186      while( *aiCol<iPrev ){
188187        aiCol++;
188188        if( aiCol==aiColEnd ) goto setoutputs_col_out;
188189      }
188190      if( *aiCol==iPrev ){
188191        *aOut++ = (u8)((iPrev - iPrevOut) + 2);
188192        iPrevOut = iPrev;
188193      }
188194    }
188195
188196setoutputs_col_out:
188197    pIter->base.pData = pIter->poslist.p;
188198    pIter->base.nData = aOut - pIter->poslist.p;
188199  }
188200}
188201
188202/*
188203** xSetOutputs callback used by detail=full when there is a column filter.
188204*/
188205static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
188206  Fts5Colset *pColset = pIter->pColset;
188207  pIter->base.iRowid = pSeg->iRowid;
188208
188209  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
188210  assert( pColset );
188211
188212  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
188213    /* All data is stored on the current page. Populate the output
188214    ** variables to point into the body of the page object. */
188215    const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188216    if( pColset->nCol==1 ){
188217      pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
188218      pIter->base.pData = a;
188219    }else{
188220      fts5BufferZero(&pIter->poslist);
188221      fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
188222      pIter->base.pData = pIter->poslist.p;
188223      pIter->base.nData = pIter->poslist.n;
188224    }
188225  }else{
188226    /* The data is distributed over two or more pages. Copy it into the
188227    ** Fts5Iter.poslist buffer and then set the output pointer to point
188228    ** to this buffer.  */
188229    fts5BufferZero(&pIter->poslist);
188230    fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
188231    pIter->base.pData = pIter->poslist.p;
188232    pIter->base.nData = pIter->poslist.n;
188233  }
188234}
188235
188236static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
188237  if( *pRc==SQLITE_OK ){
188238    Fts5Config *pConfig = pIter->pIndex->pConfig;
188239    if( pConfig->eDetail==FTS5_DETAIL_NONE ){
188240      pIter->xSetOutputs = fts5IterSetOutputs_None;
188241    }
188242
188243    else if( pIter->pColset==0 ){
188244      pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
188245    }
188246
188247    else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
188248      pIter->xSetOutputs = fts5IterSetOutputs_Full;
188249    }
188250
188251    else{
188252      assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188253      if( pConfig->nCol<=100 ){
188254        pIter->xSetOutputs = fts5IterSetOutputs_Col100;
188255        sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
188256      }else{
188257        pIter->xSetOutputs = fts5IterSetOutputs_Col;
188258      }
188259    }
188260  }
188261}
188262
188263
188264/*
188265** Allocate a new Fts5Iter object.
188266**
188267** The new object will be used to iterate through data in structure pStruct.
188268** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
188269** is zero or greater, data from the first nSegment segments on level iLevel
188270** is merged.
188271**
188272** The iterator initially points to the first term/rowid entry in the
188273** iterated data.
188274*/
188275static void fts5MultiIterNew(
188276  Fts5Index *p,                   /* FTS5 backend to iterate within */
188277  Fts5Structure *pStruct,         /* Structure of specific index */
188278  int flags,                      /* FTS5INDEX_QUERY_XXX flags */
188279  Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
188280  const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
188281  int iLevel,                     /* Level to iterate (-1 for all) */
188282  int nSegment,                   /* Number of segments to merge (iLevel>=0) */
188283  Fts5Iter **ppOut                /* New object */
188284){
188285  int nSeg = 0;                   /* Number of segment-iters in use */
188286  int iIter = 0;                  /* */
188287  int iSeg;                       /* Used to iterate through segments */
188288  Fts5StructureLevel *pLvl;
188289  Fts5Iter *pNew;
188290
188291  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
188292
188293  /* Allocate space for the new multi-seg-iterator. */
188294  if( p->rc==SQLITE_OK ){
188295    if( iLevel<0 ){
188296      assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
188297      nSeg = pStruct->nSegment;
188298      nSeg += (p->pHash ? 1 : 0);
188299    }else{
188300      nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
188301    }
188302  }
188303  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
188304  if( pNew==0 ) return;
188305  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
188306  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
188307  pNew->pStruct = pStruct;
188308  pNew->pColset = pColset;
188309  fts5StructureRef(pStruct);
188310  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
188311    fts5IterSetOutputCb(&p->rc, pNew);
188312  }
188313
188314  /* Initialize each of the component segment iterators. */
188315  if( p->rc==SQLITE_OK ){
188316    if( iLevel<0 ){
188317      Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
188318      if( p->pHash ){
188319        /* Add a segment iterator for the current contents of the hash table. */
188320        Fts5SegIter *pIter = &pNew->aSeg[iIter++];
188321        fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
188322      }
188323      for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
188324        for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
188325          Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
188326          Fts5SegIter *pIter = &pNew->aSeg[iIter++];
188327          if( pTerm==0 ){
188328            fts5SegIterInit(p, pSeg, pIter);
188329          }else{
188330            fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
188331          }
188332        }
188333      }
188334    }else{
188335      pLvl = &pStruct->aLevel[iLevel];
188336      for(iSeg=nSeg-1; iSeg>=0; iSeg--){
188337        fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
188338      }
188339    }
188340    assert( iIter==nSeg );
188341  }
188342
188343  /* If the above was successful, each component iterators now points
188344  ** to the first entry in its segment. In this case initialize the
188345  ** aFirst[] array. Or, if an error has occurred, free the iterator
188346  ** object and set the output variable to NULL.  */
188347  if( p->rc==SQLITE_OK ){
188348    for(iIter=pNew->nSeg-1; iIter>0; iIter--){
188349      int iEq;
188350      if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
188351        Fts5SegIter *pSeg = &pNew->aSeg[iEq];
188352        if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
188353        fts5MultiIterAdvanced(p, pNew, iEq, iIter);
188354      }
188355    }
188356    fts5MultiIterSetEof(pNew);
188357    fts5AssertMultiIterSetup(p, pNew);
188358
188359    if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
188360      fts5MultiIterNext(p, pNew, 0, 0);
188361    }else if( pNew->base.bEof==0 ){
188362      Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
188363      pNew->xSetOutputs(pNew, pSeg);
188364    }
188365
188366  }else{
188367    fts5MultiIterFree(pNew);
188368    *ppOut = 0;
188369  }
188370}
188371
188372/*
188373** Create an Fts5Iter that iterates through the doclist provided
188374** as the second argument.
188375*/
188376static void fts5MultiIterNew2(
188377  Fts5Index *p,                   /* FTS5 backend to iterate within */
188378  Fts5Data *pData,                /* Doclist to iterate through */
188379  int bDesc,                      /* True for descending rowid order */
188380  Fts5Iter **ppOut                /* New object */
188381){
188382  Fts5Iter *pNew;
188383  pNew = fts5MultiIterAlloc(p, 2);
188384  if( pNew ){
188385    Fts5SegIter *pIter = &pNew->aSeg[1];
188386
188387    pIter->flags = FTS5_SEGITER_ONETERM;
188388    if( pData->szLeaf>0 ){
188389      pIter->pLeaf = pData;
188390      pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
188391      pIter->iEndofDoclist = pData->nn;
188392      pNew->aFirst[1].iFirst = 1;
188393      if( bDesc ){
188394        pNew->bRev = 1;
188395        pIter->flags |= FTS5_SEGITER_REVERSE;
188396        fts5SegIterReverseInitPage(p, pIter);
188397      }else{
188398        fts5SegIterLoadNPos(p, pIter);
188399      }
188400      pData = 0;
188401    }else{
188402      pNew->base.bEof = 1;
188403    }
188404    fts5SegIterSetNext(p, pIter);
188405
188406    *ppOut = pNew;
188407  }
188408
188409  fts5DataRelease(pData);
188410}
188411
188412/*
188413** Return true if the iterator is at EOF or if an error has occurred.
188414** False otherwise.
188415*/
188416static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
188417  assert( p->rc
188418      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
188419  );
188420  return (p->rc || pIter->base.bEof);
188421}
188422
188423/*
188424** Return the rowid of the entry that the iterator currently points
188425** to. If the iterator points to EOF when this function is called the
188426** results are undefined.
188427*/
188428static i64 fts5MultiIterRowid(Fts5Iter *pIter){
188429  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
188430  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
188431}
188432
188433/*
188434** Move the iterator to the next entry at or following iMatch.
188435*/
188436static void fts5MultiIterNextFrom(
188437  Fts5Index *p,
188438  Fts5Iter *pIter,
188439  i64 iMatch
188440){
188441  while( 1 ){
188442    i64 iRowid;
188443    fts5MultiIterNext(p, pIter, 1, iMatch);
188444    if( fts5MultiIterEof(p, pIter) ) break;
188445    iRowid = fts5MultiIterRowid(pIter);
188446    if( pIter->bRev==0 && iRowid>=iMatch ) break;
188447    if( pIter->bRev!=0 && iRowid<=iMatch ) break;
188448  }
188449}
188450
188451/*
188452** Return a pointer to a buffer containing the term associated with the
188453** entry that the iterator currently points to.
188454*/
188455static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
188456  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
188457  *pn = p->term.n;
188458  return p->term.p;
188459}
188460
188461/*
188462** Allocate a new segment-id for the structure pStruct. The new segment
188463** id must be between 1 and 65335 inclusive, and must not be used by
188464** any currently existing segment. If a free segment id cannot be found,
188465** SQLITE_FULL is returned.
188466**
188467** If an error has already occurred, this function is a no-op. 0 is
188468** returned in this case.
188469*/
188470static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
188471  int iSegid = 0;
188472
188473  if( p->rc==SQLITE_OK ){
188474    if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
188475      p->rc = SQLITE_FULL;
188476    }else{
188477      /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
188478      ** array is 63 elements, or 252 bytes, in size.  */
188479      u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
188480      int iLvl, iSeg;
188481      int i;
188482      u32 mask;
188483      memset(aUsed, 0, sizeof(aUsed));
188484      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188485        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188486          int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
188487          if( iId<=FTS5_MAX_SEGMENT ){
188488            aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
188489          }
188490        }
188491      }
188492
188493      for(i=0; aUsed[i]==0xFFFFFFFF; i++);
188494      mask = aUsed[i];
188495      for(iSegid=0; mask & (1 << iSegid); iSegid++);
188496      iSegid += 1 + i*32;
188497
188498#ifdef SQLITE_DEBUG
188499      for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188500        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188501          assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
188502        }
188503      }
188504      assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
188505
188506      {
188507        sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
188508        if( p->rc==SQLITE_OK ){
188509          u8 aBlob[2] = {0xff, 0xff};
188510          sqlite3_bind_int(pIdxSelect, 1, iSegid);
188511          sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
188512          assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
188513          p->rc = sqlite3_reset(pIdxSelect);
188514        }
188515      }
188516#endif
188517    }
188518  }
188519
188520  return iSegid;
188521}
188522
188523/*
188524** Discard all data currently cached in the hash-tables.
188525*/
188526static void fts5IndexDiscardData(Fts5Index *p){
188527  assert( p->pHash || p->nPendingData==0 );
188528  if( p->pHash ){
188529    sqlite3Fts5HashClear(p->pHash);
188530    p->nPendingData = 0;
188531  }
188532}
188533
188534/*
188535** Return the size of the prefix, in bytes, that buffer
188536** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
188537**
188538** Buffer (pNew/<length-unknown>) is guaranteed to be greater
188539** than buffer (pOld/nOld).
188540*/
188541static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
188542  int i;
188543  for(i=0; i<nOld; i++){
188544    if( pOld[i]!=pNew[i] ) break;
188545  }
188546  return i;
188547}
188548
188549static void fts5WriteDlidxClear(
188550  Fts5Index *p,
188551  Fts5SegWriter *pWriter,
188552  int bFlush                      /* If true, write dlidx to disk */
188553){
188554  int i;
188555  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
188556  for(i=0; i<pWriter->nDlidx; i++){
188557    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
188558    if( pDlidx->buf.n==0 ) break;
188559    if( bFlush ){
188560      assert( pDlidx->pgno!=0 );
188561      fts5DataWrite(p,
188562          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
188563          pDlidx->buf.p, pDlidx->buf.n
188564      );
188565    }
188566    sqlite3Fts5BufferZero(&pDlidx->buf);
188567    pDlidx->bPrevValid = 0;
188568  }
188569}
188570
188571/*
188572** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
188573** Any new array elements are zeroed before returning.
188574*/
188575static int fts5WriteDlidxGrow(
188576  Fts5Index *p,
188577  Fts5SegWriter *pWriter,
188578  int nLvl
188579){
188580  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
188581    Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
188582        pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
188583    );
188584    if( aDlidx==0 ){
188585      p->rc = SQLITE_NOMEM;
188586    }else{
188587      int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
188588      memset(&aDlidx[pWriter->nDlidx], 0, nByte);
188589      pWriter->aDlidx = aDlidx;
188590      pWriter->nDlidx = nLvl;
188591    }
188592  }
188593  return p->rc;
188594}
188595
188596/*
188597** If the current doclist-index accumulating in pWriter->aDlidx[] is large
188598** enough, flush it to disk and return 1. Otherwise discard it and return
188599** zero.
188600*/
188601static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
188602  int bFlag = 0;
188603
188604  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
188605  ** to the database, also write the doclist-index to disk.  */
188606  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
188607    bFlag = 1;
188608  }
188609  fts5WriteDlidxClear(p, pWriter, bFlag);
188610  pWriter->nEmpty = 0;
188611  return bFlag;
188612}
188613
188614/*
188615** This function is called whenever processing of the doclist for the
188616** last term on leaf page (pWriter->iBtPage) is completed.
188617**
188618** The doclist-index for that term is currently stored in-memory within the
188619** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
188620** writes it out to disk. Or, if it is too small to bother with, discards
188621** it.
188622**
188623** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
188624*/
188625static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
188626  int bFlag;
188627
188628  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
188629  if( pWriter->iBtPage==0 ) return;
188630  bFlag = fts5WriteFlushDlidx(p, pWriter);
188631
188632  if( p->rc==SQLITE_OK ){
188633    const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
188634    /* The following was already done in fts5WriteInit(): */
188635    /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
188636    sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
188637    sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
188638    sqlite3_step(p->pIdxWriter);
188639    p->rc = sqlite3_reset(p->pIdxWriter);
188640  }
188641  pWriter->iBtPage = 0;
188642}
188643
188644/*
188645** This is called once for each leaf page except the first that contains
188646** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
188647** is larger than all terms written to earlier leaves, and equal to or
188648** smaller than the first term on the new leaf.
188649**
188650** If an error occurs, an error code is left in Fts5Index.rc. If an error
188651** has already occurred when this function is called, it is a no-op.
188652*/
188653static void fts5WriteBtreeTerm(
188654  Fts5Index *p,                   /* FTS5 backend object */
188655  Fts5SegWriter *pWriter,         /* Writer object */
188656  int nTerm, const u8 *pTerm      /* First term on new page */
188657){
188658  fts5WriteFlushBtree(p, pWriter);
188659  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
188660  pWriter->iBtPage = pWriter->writer.pgno;
188661}
188662
188663/*
188664** This function is called when flushing a leaf page that contains no
188665** terms at all to disk.
188666*/
188667static void fts5WriteBtreeNoTerm(
188668  Fts5Index *p,                   /* FTS5 backend object */
188669  Fts5SegWriter *pWriter          /* Writer object */
188670){
188671  /* If there were no rowids on the leaf page either and the doclist-index
188672  ** has already been started, append an 0x00 byte to it.  */
188673  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
188674    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
188675    assert( pDlidx->bPrevValid );
188676    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
188677  }
188678
188679  /* Increment the "number of sequential leaves without a term" counter. */
188680  pWriter->nEmpty++;
188681}
188682
188683static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
188684  i64 iRowid;
188685  int iOff;
188686
188687  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
188688  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
188689  return iRowid;
188690}
188691
188692/*
188693** Rowid iRowid has just been appended to the current leaf page. It is the
188694** first on the page. This function appends an appropriate entry to the current
188695** doclist-index.
188696*/
188697static void fts5WriteDlidxAppend(
188698  Fts5Index *p,
188699  Fts5SegWriter *pWriter,
188700  i64 iRowid
188701){
188702  int i;
188703  int bDone = 0;
188704
188705  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
188706    i64 iVal;
188707    Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
188708
188709    if( pDlidx->buf.n>=p->pConfig->pgsz ){
188710      /* The current doclist-index page is full. Write it to disk and push
188711      ** a copy of iRowid (which will become the first rowid on the next
188712      ** doclist-index leaf page) up into the next level of the b-tree
188713      ** hierarchy. If the node being flushed is currently the root node,
188714      ** also push its first rowid upwards. */
188715      pDlidx->buf.p[0] = 0x01;    /* Not the root node */
188716      fts5DataWrite(p,
188717          FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
188718          pDlidx->buf.p, pDlidx->buf.n
188719      );
188720      fts5WriteDlidxGrow(p, pWriter, i+2);
188721      pDlidx = &pWriter->aDlidx[i];
188722      if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
188723        i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
188724
188725        /* This was the root node. Push its first rowid up to the new root. */
188726        pDlidx[1].pgno = pDlidx->pgno;
188727        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
188728        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
188729        sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
188730        pDlidx[1].bPrevValid = 1;
188731        pDlidx[1].iPrev = iFirst;
188732      }
188733
188734      sqlite3Fts5BufferZero(&pDlidx->buf);
188735      pDlidx->bPrevValid = 0;
188736      pDlidx->pgno++;
188737    }else{
188738      bDone = 1;
188739    }
188740
188741    if( pDlidx->bPrevValid ){
188742      iVal = iRowid - pDlidx->iPrev;
188743    }else{
188744      i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
188745      assert( pDlidx->buf.n==0 );
188746      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
188747      sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
188748      iVal = iRowid;
188749    }
188750
188751    sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
188752    pDlidx->bPrevValid = 1;
188753    pDlidx->iPrev = iRowid;
188754  }
188755}
188756
188757static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
188758  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
188759  Fts5PageWriter *pPage = &pWriter->writer;
188760  i64 iRowid;
188761
188762static int nCall = 0;
188763nCall++;
188764
188765  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
188766
188767  /* Set the szLeaf header field. */
188768  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
188769  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
188770
188771  if( pWriter->bFirstTermInPage ){
188772    /* No term was written to this page. */
188773    assert( pPage->pgidx.n==0 );
188774    fts5WriteBtreeNoTerm(p, pWriter);
188775  }else{
188776    /* Append the pgidx to the page buffer. Set the szLeaf header field. */
188777    fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
188778  }
188779
188780  /* Write the page out to disk */
188781  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
188782  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
188783
188784  /* Initialize the next page. */
188785  fts5BufferZero(&pPage->buf);
188786  fts5BufferZero(&pPage->pgidx);
188787  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
188788  pPage->iPrevPgidx = 0;
188789  pPage->pgno++;
188790
188791  /* Increase the leaves written counter */
188792  pWriter->nLeafWritten++;
188793
188794  /* The new leaf holds no terms or rowids */
188795  pWriter->bFirstTermInPage = 1;
188796  pWriter->bFirstRowidInPage = 1;
188797}
188798
188799/*
188800** Append term pTerm/nTerm to the segment being written by the writer passed
188801** as the second argument.
188802**
188803** If an error occurs, set the Fts5Index.rc error code. If an error has
188804** already occurred, this function is a no-op.
188805*/
188806static void fts5WriteAppendTerm(
188807  Fts5Index *p,
188808  Fts5SegWriter *pWriter,
188809  int nTerm, const u8 *pTerm
188810){
188811  int nPrefix;                    /* Bytes of prefix compression for term */
188812  Fts5PageWriter *pPage = &pWriter->writer;
188813  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
188814
188815  assert( p->rc==SQLITE_OK );
188816  assert( pPage->buf.n>=4 );
188817  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
188818
188819  /* If the current leaf page is full, flush it to disk. */
188820  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
188821    if( pPage->buf.n>4 ){
188822      fts5WriteFlushLeaf(p, pWriter);
188823    }
188824    fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
188825  }
188826
188827  /* TODO1: Updating pgidx here. */
188828  pPgidx->n += sqlite3Fts5PutVarint(
188829      &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
188830  );
188831  pPage->iPrevPgidx = pPage->buf.n;
188832#if 0
188833  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
188834  pPgidx->n += 2;
188835#endif
188836
188837  if( pWriter->bFirstTermInPage ){
188838    nPrefix = 0;
188839    if( pPage->pgno!=1 ){
188840      /* This is the first term on a leaf that is not the leftmost leaf in
188841      ** the segment b-tree. In this case it is necessary to add a term to
188842      ** the b-tree hierarchy that is (a) larger than the largest term
188843      ** already written to the segment and (b) smaller than or equal to
188844      ** this term. In other words, a prefix of (pTerm/nTerm) that is one
188845      ** byte longer than the longest prefix (pTerm/nTerm) shares with the
188846      ** previous term.
188847      **
188848      ** Usually, the previous term is available in pPage->term. The exception
188849      ** is if this is the first term written in an incremental-merge step.
188850      ** In this case the previous term is not available, so just write a
188851      ** copy of (pTerm/nTerm) into the parent node. This is slightly
188852      ** inefficient, but still correct.  */
188853      int n = nTerm;
188854      if( pPage->term.n ){
188855        n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
188856      }
188857      fts5WriteBtreeTerm(p, pWriter, n, pTerm);
188858      pPage = &pWriter->writer;
188859    }
188860  }else{
188861    nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
188862    fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
188863  }
188864
188865  /* Append the number of bytes of new data, then the term data itself
188866  ** to the page. */
188867  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
188868  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
188869
188870  /* Update the Fts5PageWriter.term field. */
188871  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
188872  pWriter->bFirstTermInPage = 0;
188873
188874  pWriter->bFirstRowidInPage = 0;
188875  pWriter->bFirstRowidInDoclist = 1;
188876
188877  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
188878  pWriter->aDlidx[0].pgno = pPage->pgno;
188879}
188880
188881/*
188882** Append a rowid and position-list size field to the writers output.
188883*/
188884static void fts5WriteAppendRowid(
188885  Fts5Index *p,
188886  Fts5SegWriter *pWriter,
188887  i64 iRowid
188888){
188889  if( p->rc==SQLITE_OK ){
188890    Fts5PageWriter *pPage = &pWriter->writer;
188891
188892    if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
188893      fts5WriteFlushLeaf(p, pWriter);
188894    }
188895
188896    /* If this is to be the first rowid written to the page, set the
188897    ** rowid-pointer in the page-header. Also append a value to the dlidx
188898    ** buffer, in case a doclist-index is required.  */
188899    if( pWriter->bFirstRowidInPage ){
188900      fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
188901      fts5WriteDlidxAppend(p, pWriter, iRowid);
188902    }
188903
188904    /* Write the rowid. */
188905    if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
188906      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
188907    }else{
188908      assert( p->rc || iRowid>pWriter->iPrevRowid );
188909      fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
188910    }
188911    pWriter->iPrevRowid = iRowid;
188912    pWriter->bFirstRowidInDoclist = 0;
188913    pWriter->bFirstRowidInPage = 0;
188914  }
188915}
188916
188917static void fts5WriteAppendPoslistData(
188918  Fts5Index *p,
188919  Fts5SegWriter *pWriter,
188920  const u8 *aData,
188921  int nData
188922){
188923  Fts5PageWriter *pPage = &pWriter->writer;
188924  const u8 *a = aData;
188925  int n = nData;
188926
188927  assert( p->pConfig->pgsz>0 );
188928  while( p->rc==SQLITE_OK
188929     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
188930  ){
188931    int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
188932    int nCopy = 0;
188933    while( nCopy<nReq ){
188934      i64 dummy;
188935      nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
188936    }
188937    fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
188938    a += nCopy;
188939    n -= nCopy;
188940    fts5WriteFlushLeaf(p, pWriter);
188941  }
188942  if( n>0 ){
188943    fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
188944  }
188945}
188946
188947/*
188948** Flush any data cached by the writer object to the database. Free any
188949** allocations associated with the writer.
188950*/
188951static void fts5WriteFinish(
188952  Fts5Index *p,
188953  Fts5SegWriter *pWriter,         /* Writer object */
188954  int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
188955){
188956  int i;
188957  Fts5PageWriter *pLeaf = &pWriter->writer;
188958  if( p->rc==SQLITE_OK ){
188959    assert( pLeaf->pgno>=1 );
188960    if( pLeaf->buf.n>4 ){
188961      fts5WriteFlushLeaf(p, pWriter);
188962    }
188963    *pnLeaf = pLeaf->pgno-1;
188964    if( pLeaf->pgno>1 ){
188965      fts5WriteFlushBtree(p, pWriter);
188966    }
188967  }
188968  fts5BufferFree(&pLeaf->term);
188969  fts5BufferFree(&pLeaf->buf);
188970  fts5BufferFree(&pLeaf->pgidx);
188971  fts5BufferFree(&pWriter->btterm);
188972
188973  for(i=0; i<pWriter->nDlidx; i++){
188974    sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
188975  }
188976  sqlite3_free(pWriter->aDlidx);
188977}
188978
188979static void fts5WriteInit(
188980  Fts5Index *p,
188981  Fts5SegWriter *pWriter,
188982  int iSegid
188983){
188984  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
188985
188986  memset(pWriter, 0, sizeof(Fts5SegWriter));
188987  pWriter->iSegid = iSegid;
188988
188989  fts5WriteDlidxGrow(p, pWriter, 1);
188990  pWriter->writer.pgno = 1;
188991  pWriter->bFirstTermInPage = 1;
188992  pWriter->iBtPage = 1;
188993
188994  assert( pWriter->writer.buf.n==0 );
188995  assert( pWriter->writer.pgidx.n==0 );
188996
188997  /* Grow the two buffers to pgsz + padding bytes in size. */
188998  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
188999  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
189000
189001  if( p->pIdxWriter==0 ){
189002    Fts5Config *pConfig = p->pConfig;
189003    fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
189004          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
189005          pConfig->zDb, pConfig->zName
189006    ));
189007  }
189008
189009  if( p->rc==SQLITE_OK ){
189010    /* Initialize the 4-byte leaf-page header to 0x00. */
189011    memset(pWriter->writer.buf.p, 0, 4);
189012    pWriter->writer.buf.n = 4;
189013
189014    /* Bind the current output segment id to the index-writer. This is an
189015    ** optimization over binding the same value over and over as rows are
189016    ** inserted into %_idx by the current writer.  */
189017    sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
189018  }
189019}
189020
189021/*
189022** Iterator pIter was used to iterate through the input segments of on an
189023** incremental merge operation. This function is called if the incremental
189024** merge step has finished but the input has not been completely exhausted.
189025*/
189026static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
189027  int i;
189028  Fts5Buffer buf;
189029  memset(&buf, 0, sizeof(Fts5Buffer));
189030  for(i=0; i<pIter->nSeg; i++){
189031    Fts5SegIter *pSeg = &pIter->aSeg[i];
189032    if( pSeg->pSeg==0 ){
189033      /* no-op */
189034    }else if( pSeg->pLeaf==0 ){
189035      /* All keys from this input segment have been transfered to the output.
189036      ** Set both the first and last page-numbers to 0 to indicate that the
189037      ** segment is now empty. */
189038      pSeg->pSeg->pgnoLast = 0;
189039      pSeg->pSeg->pgnoFirst = 0;
189040    }else{
189041      int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
189042      i64 iLeafRowid;
189043      Fts5Data *pData;
189044      int iId = pSeg->pSeg->iSegid;
189045      u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
189046
189047      iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
189048      pData = fts5DataRead(p, iLeafRowid);
189049      if( pData ){
189050        fts5BufferZero(&buf);
189051        fts5BufferGrow(&p->rc, &buf, pData->nn);
189052        fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
189053        fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
189054        fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
189055        fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
189056        if( p->rc==SQLITE_OK ){
189057          /* Set the szLeaf field */
189058          fts5PutU16(&buf.p[2], (u16)buf.n);
189059        }
189060
189061        /* Set up the new page-index array */
189062        fts5BufferAppendVarint(&p->rc, &buf, 4);
189063        if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
189064         && pSeg->iEndofDoclist<pData->szLeaf
189065        ){
189066          int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
189067          fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
189068          fts5BufferAppendBlob(&p->rc, &buf,
189069              pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
189070          );
189071        }
189072
189073        fts5DataRelease(pData);
189074        pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
189075        fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
189076        fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
189077      }
189078    }
189079  }
189080  fts5BufferFree(&buf);
189081}
189082
189083static void fts5MergeChunkCallback(
189084  Fts5Index *p,
189085  void *pCtx,
189086  const u8 *pChunk, int nChunk
189087){
189088  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
189089  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
189090}
189091
189092/*
189093**
189094*/
189095static void fts5IndexMergeLevel(
189096  Fts5Index *p,                   /* FTS5 backend object */
189097  Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
189098  int iLvl,                       /* Level to read input from */
189099  int *pnRem                      /* Write up to this many output leaves */
189100){
189101  Fts5Structure *pStruct = *ppStruct;
189102  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
189103  Fts5StructureLevel *pLvlOut;
189104  Fts5Iter *pIter = 0;       /* Iterator to read input data */
189105  int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
189106  int nInput;                     /* Number of input segments */
189107  Fts5SegWriter writer;           /* Writer object */
189108  Fts5StructureSegment *pSeg;     /* Output segment */
189109  Fts5Buffer term;
189110  int bOldest;                    /* True if the output segment is the oldest */
189111  int eDetail = p->pConfig->eDetail;
189112  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
189113
189114  assert( iLvl<pStruct->nLevel );
189115  assert( pLvl->nMerge<=pLvl->nSeg );
189116
189117  memset(&writer, 0, sizeof(Fts5SegWriter));
189118  memset(&term, 0, sizeof(Fts5Buffer));
189119  if( pLvl->nMerge ){
189120    pLvlOut = &pStruct->aLevel[iLvl+1];
189121    assert( pLvlOut->nSeg>0 );
189122    nInput = pLvl->nMerge;
189123    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
189124
189125    fts5WriteInit(p, &writer, pSeg->iSegid);
189126    writer.writer.pgno = pSeg->pgnoLast+1;
189127    writer.iBtPage = 0;
189128  }else{
189129    int iSegid = fts5AllocateSegid(p, pStruct);
189130
189131    /* Extend the Fts5Structure object as required to ensure the output
189132    ** segment exists. */
189133    if( iLvl==pStruct->nLevel-1 ){
189134      fts5StructureAddLevel(&p->rc, ppStruct);
189135      pStruct = *ppStruct;
189136    }
189137    fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
189138    if( p->rc ) return;
189139    pLvl = &pStruct->aLevel[iLvl];
189140    pLvlOut = &pStruct->aLevel[iLvl+1];
189141
189142    fts5WriteInit(p, &writer, iSegid);
189143
189144    /* Add the new segment to the output level */
189145    pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
189146    pLvlOut->nSeg++;
189147    pSeg->pgnoFirst = 1;
189148    pSeg->iSegid = iSegid;
189149    pStruct->nSegment++;
189150
189151    /* Read input from all segments in the input level */
189152    nInput = pLvl->nSeg;
189153  }
189154  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
189155
189156  assert( iLvl>=0 );
189157  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
189158      fts5MultiIterEof(p, pIter)==0;
189159      fts5MultiIterNext(p, pIter, 0, 0)
189160  ){
189161    Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189162    int nPos;                     /* position-list size field value */
189163    int nTerm;
189164    const u8 *pTerm;
189165
189166    /* Check for key annihilation. */
189167    if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
189168
189169    pTerm = fts5MultiIterTerm(pIter, &nTerm);
189170    if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
189171      if( pnRem && writer.nLeafWritten>nRem ){
189172        break;
189173      }
189174
189175      /* This is a new term. Append a term to the output segment. */
189176      fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
189177      fts5BufferSet(&p->rc, &term, nTerm, pTerm);
189178    }
189179
189180    /* Append the rowid to the output */
189181    /* WRITEPOSLISTSIZE */
189182    fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
189183
189184    if( eDetail==FTS5_DETAIL_NONE ){
189185      if( pSegIter->bDel ){
189186        fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
189187        if( pSegIter->nPos>0 ){
189188          fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
189189        }
189190      }
189191    }else{
189192      /* Append the position-list data to the output */
189193      nPos = pSegIter->nPos*2 + pSegIter->bDel;
189194      fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
189195      fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
189196    }
189197  }
189198
189199  /* Flush the last leaf page to disk. Set the output segment b-tree height
189200  ** and last leaf page number at the same time.  */
189201  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
189202
189203  if( fts5MultiIterEof(p, pIter) ){
189204    int i;
189205
189206    /* Remove the redundant segments from the %_data table */
189207    for(i=0; i<nInput; i++){
189208      fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
189209    }
189210
189211    /* Remove the redundant segments from the input level */
189212    if( pLvl->nSeg!=nInput ){
189213      int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
189214      memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
189215    }
189216    pStruct->nSegment -= nInput;
189217    pLvl->nSeg -= nInput;
189218    pLvl->nMerge = 0;
189219    if( pSeg->pgnoLast==0 ){
189220      pLvlOut->nSeg--;
189221      pStruct->nSegment--;
189222    }
189223  }else{
189224    assert( pSeg->pgnoLast>0 );
189225    fts5TrimSegments(p, pIter);
189226    pLvl->nMerge = nInput;
189227  }
189228
189229  fts5MultiIterFree(pIter);
189230  fts5BufferFree(&term);
189231  if( pnRem ) *pnRem -= writer.nLeafWritten;
189232}
189233
189234/*
189235** Do up to nPg pages of automerge work on the index.
189236**
189237** Return true if any changes were actually made, or false otherwise.
189238*/
189239static int fts5IndexMerge(
189240  Fts5Index *p,                   /* FTS5 backend object */
189241  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
189242  int nPg,                        /* Pages of work to do */
189243  int nMin                        /* Minimum number of segments to merge */
189244){
189245  int nRem = nPg;
189246  int bRet = 0;
189247  Fts5Structure *pStruct = *ppStruct;
189248  while( nRem>0 && p->rc==SQLITE_OK ){
189249    int iLvl;                   /* To iterate through levels */
189250    int iBestLvl = 0;           /* Level offering the most input segments */
189251    int nBest = 0;              /* Number of input segments on best level */
189252
189253    /* Set iBestLvl to the level to read input segments from. */
189254    assert( pStruct->nLevel>0 );
189255    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
189256      Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
189257      if( pLvl->nMerge ){
189258        if( pLvl->nMerge>nBest ){
189259          iBestLvl = iLvl;
189260          nBest = pLvl->nMerge;
189261        }
189262        break;
189263      }
189264      if( pLvl->nSeg>nBest ){
189265        nBest = pLvl->nSeg;
189266        iBestLvl = iLvl;
189267      }
189268    }
189269
189270    /* If nBest is still 0, then the index must be empty. */
189271#ifdef SQLITE_DEBUG
189272    for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
189273      assert( pStruct->aLevel[iLvl].nSeg==0 );
189274    }
189275#endif
189276
189277    if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
189278      break;
189279    }
189280    bRet = 1;
189281    fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
189282    if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
189283      fts5StructurePromote(p, iBestLvl+1, pStruct);
189284    }
189285  }
189286  *ppStruct = pStruct;
189287  return bRet;
189288}
189289
189290/*
189291** A total of nLeaf leaf pages of data has just been flushed to a level-0
189292** segment. This function updates the write-counter accordingly and, if
189293** necessary, performs incremental merge work.
189294**
189295** If an error occurs, set the Fts5Index.rc error code. If an error has
189296** already occurred, this function is a no-op.
189297*/
189298static void fts5IndexAutomerge(
189299  Fts5Index *p,                   /* FTS5 backend object */
189300  Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
189301  int nLeaf                       /* Number of output leaves just written */
189302){
189303  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
189304    Fts5Structure *pStruct = *ppStruct;
189305    u64 nWrite;                   /* Initial value of write-counter */
189306    int nWork;                    /* Number of work-quanta to perform */
189307    int nRem;                     /* Number of leaf pages left to write */
189308
189309    /* Update the write-counter. While doing so, set nWork. */
189310    nWrite = pStruct->nWriteCounter;
189311    nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
189312    pStruct->nWriteCounter += nLeaf;
189313    nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
189314
189315    fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
189316  }
189317}
189318
189319static void fts5IndexCrisismerge(
189320  Fts5Index *p,                   /* FTS5 backend object */
189321  Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
189322){
189323  const int nCrisis = p->pConfig->nCrisisMerge;
189324  Fts5Structure *pStruct = *ppStruct;
189325  int iLvl = 0;
189326
189327  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
189328  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
189329    fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
189330    assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
189331    fts5StructurePromote(p, iLvl+1, pStruct);
189332    iLvl++;
189333  }
189334  *ppStruct = pStruct;
189335}
189336
189337static int fts5IndexReturn(Fts5Index *p){
189338  int rc = p->rc;
189339  p->rc = SQLITE_OK;
189340  return rc;
189341}
189342
189343typedef struct Fts5FlushCtx Fts5FlushCtx;
189344struct Fts5FlushCtx {
189345  Fts5Index *pIdx;
189346  Fts5SegWriter writer;
189347};
189348
189349/*
189350** Buffer aBuf[] contains a list of varints, all small enough to fit
189351** in a 32-bit integer. Return the size of the largest prefix of this
189352** list nMax bytes or less in size.
189353*/
189354static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
189355  int ret;
189356  u32 dummy;
189357  ret = fts5GetVarint32(aBuf, dummy);
189358  if( ret<nMax ){
189359    while( 1 ){
189360      int i = fts5GetVarint32(&aBuf[ret], dummy);
189361      if( (ret + i) > nMax ) break;
189362      ret += i;
189363    }
189364  }
189365  return ret;
189366}
189367
189368/*
189369** Flush the contents of in-memory hash table iHash to a new level-0
189370** segment on disk. Also update the corresponding structure record.
189371**
189372** If an error occurs, set the Fts5Index.rc error code. If an error has
189373** already occurred, this function is a no-op.
189374*/
189375static void fts5FlushOneHash(Fts5Index *p){
189376  Fts5Hash *pHash = p->pHash;
189377  Fts5Structure *pStruct;
189378  int iSegid;
189379  int pgnoLast = 0;                 /* Last leaf page number in segment */
189380
189381  /* Obtain a reference to the index structure and allocate a new segment-id
189382  ** for the new level-0 segment.  */
189383  pStruct = fts5StructureRead(p);
189384  iSegid = fts5AllocateSegid(p, pStruct);
189385  fts5StructureInvalidate(p);
189386
189387  if( iSegid ){
189388    const int pgsz = p->pConfig->pgsz;
189389    int eDetail = p->pConfig->eDetail;
189390    Fts5StructureSegment *pSeg;   /* New segment within pStruct */
189391    Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
189392    Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
189393
189394    Fts5SegWriter writer;
189395    fts5WriteInit(p, &writer, iSegid);
189396
189397    pBuf = &writer.writer.buf;
189398    pPgidx = &writer.writer.pgidx;
189399
189400    /* fts5WriteInit() should have initialized the buffers to (most likely)
189401    ** the maximum space required. */
189402    assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
189403    assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
189404
189405    /* Begin scanning through hash table entries. This loop runs once for each
189406    ** term/doclist currently stored within the hash table. */
189407    if( p->rc==SQLITE_OK ){
189408      p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
189409    }
189410    while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
189411      const char *zTerm;          /* Buffer containing term */
189412      const u8 *pDoclist;         /* Pointer to doclist for this term */
189413      int nDoclist;               /* Size of doclist in bytes */
189414
189415      /* Write the term for this entry to disk. */
189416      sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
189417      fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
189418
189419      assert( writer.bFirstRowidInPage==0 );
189420      if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
189421        /* The entire doclist will fit on the current leaf. */
189422        fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
189423      }else{
189424        i64 iRowid = 0;
189425        i64 iDelta = 0;
189426        int iOff = 0;
189427
189428        /* The entire doclist will not fit on this leaf. The following
189429        ** loop iterates through the poslists that make up the current
189430        ** doclist.  */
189431        while( p->rc==SQLITE_OK && iOff<nDoclist ){
189432          iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
189433          iRowid += iDelta;
189434
189435          if( writer.bFirstRowidInPage ){
189436            fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
189437            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
189438            writer.bFirstRowidInPage = 0;
189439            fts5WriteDlidxAppend(p, &writer, iRowid);
189440          }else{
189441            pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
189442          }
189443          assert( pBuf->n<=pBuf->nSpace );
189444
189445          if( eDetail==FTS5_DETAIL_NONE ){
189446            if( iOff<nDoclist && pDoclist[iOff]==0 ){
189447              pBuf->p[pBuf->n++] = 0;
189448              iOff++;
189449              if( iOff<nDoclist && pDoclist[iOff]==0 ){
189450                pBuf->p[pBuf->n++] = 0;
189451                iOff++;
189452              }
189453            }
189454            if( (pBuf->n + pPgidx->n)>=pgsz ){
189455              fts5WriteFlushLeaf(p, &writer);
189456            }
189457          }else{
189458            int bDummy;
189459            int nPos;
189460            int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
189461            nCopy += nPos;
189462            if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
189463              /* The entire poslist will fit on the current leaf. So copy
189464              ** it in one go. */
189465              fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
189466            }else{
189467              /* The entire poslist will not fit on this leaf. So it needs
189468              ** to be broken into sections. The only qualification being
189469              ** that each varint must be stored contiguously.  */
189470              const u8 *pPoslist = &pDoclist[iOff];
189471              int iPos = 0;
189472              while( p->rc==SQLITE_OK ){
189473                int nSpace = pgsz - pBuf->n - pPgidx->n;
189474                int n = 0;
189475                if( (nCopy - iPos)<=nSpace ){
189476                  n = nCopy - iPos;
189477                }else{
189478                  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
189479                }
189480                assert( n>0 );
189481                fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
189482                iPos += n;
189483                if( (pBuf->n + pPgidx->n)>=pgsz ){
189484                  fts5WriteFlushLeaf(p, &writer);
189485                }
189486                if( iPos>=nCopy ) break;
189487              }
189488            }
189489            iOff += nCopy;
189490          }
189491        }
189492      }
189493
189494      /* TODO2: Doclist terminator written here. */
189495      /* pBuf->p[pBuf->n++] = '\0'; */
189496      assert( pBuf->n<=pBuf->nSpace );
189497      sqlite3Fts5HashScanNext(pHash);
189498    }
189499    sqlite3Fts5HashClear(pHash);
189500    fts5WriteFinish(p, &writer, &pgnoLast);
189501
189502    /* Update the Fts5Structure. It is written back to the database by the
189503    ** fts5StructureRelease() call below.  */
189504    if( pStruct->nLevel==0 ){
189505      fts5StructureAddLevel(&p->rc, &pStruct);
189506    }
189507    fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
189508    if( p->rc==SQLITE_OK ){
189509      pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
189510      pSeg->iSegid = iSegid;
189511      pSeg->pgnoFirst = 1;
189512      pSeg->pgnoLast = pgnoLast;
189513      pStruct->nSegment++;
189514    }
189515    fts5StructurePromote(p, 0, pStruct);
189516  }
189517
189518  fts5IndexAutomerge(p, &pStruct, pgnoLast);
189519  fts5IndexCrisismerge(p, &pStruct);
189520  fts5StructureWrite(p, pStruct);
189521  fts5StructureRelease(pStruct);
189522}
189523
189524/*
189525** Flush any data stored in the in-memory hash tables to the database.
189526*/
189527static void fts5IndexFlush(Fts5Index *p){
189528  /* Unless it is empty, flush the hash table to disk */
189529  if( p->nPendingData ){
189530    assert( p->pHash );
189531    p->nPendingData = 0;
189532    fts5FlushOneHash(p);
189533  }
189534}
189535
189536static Fts5Structure *fts5IndexOptimizeStruct(
189537  Fts5Index *p,
189538  Fts5Structure *pStruct
189539){
189540  Fts5Structure *pNew = 0;
189541  int nByte = sizeof(Fts5Structure);
189542  int nSeg = pStruct->nSegment;
189543  int i;
189544
189545  /* Figure out if this structure requires optimization. A structure does
189546  ** not require optimization if either:
189547  **
189548  **  + it consists of fewer than two segments, or
189549  **  + all segments are on the same level, or
189550  **  + all segments except one are currently inputs to a merge operation.
189551  **
189552  ** In the first case, return NULL. In the second, increment the ref-count
189553  ** on *pStruct and return a copy of the pointer to it.
189554  */
189555  if( nSeg<2 ) return 0;
189556  for(i=0; i<pStruct->nLevel; i++){
189557    int nThis = pStruct->aLevel[i].nSeg;
189558    if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
189559      fts5StructureRef(pStruct);
189560      return pStruct;
189561    }
189562    assert( pStruct->aLevel[i].nMerge<=nThis );
189563  }
189564
189565  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
189566  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
189567
189568  if( pNew ){
189569    Fts5StructureLevel *pLvl;
189570    nByte = nSeg * sizeof(Fts5StructureSegment);
189571    pNew->nLevel = pStruct->nLevel+1;
189572    pNew->nRef = 1;
189573    pNew->nWriteCounter = pStruct->nWriteCounter;
189574    pLvl = &pNew->aLevel[pStruct->nLevel];
189575    pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
189576    if( pLvl->aSeg ){
189577      int iLvl, iSeg;
189578      int iSegOut = 0;
189579      /* Iterate through all segments, from oldest to newest. Add them to
189580      ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
189581      ** segment in the data structure.  */
189582      for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
189583        for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
189584          pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
189585          iSegOut++;
189586        }
189587      }
189588      pNew->nSegment = pLvl->nSeg = nSeg;
189589    }else{
189590      sqlite3_free(pNew);
189591      pNew = 0;
189592    }
189593  }
189594
189595  return pNew;
189596}
189597
189598static int sqlite3Fts5IndexOptimize(Fts5Index *p){
189599  Fts5Structure *pStruct;
189600  Fts5Structure *pNew = 0;
189601
189602  assert( p->rc==SQLITE_OK );
189603  fts5IndexFlush(p);
189604  pStruct = fts5StructureRead(p);
189605  fts5StructureInvalidate(p);
189606
189607  if( pStruct ){
189608    pNew = fts5IndexOptimizeStruct(p, pStruct);
189609  }
189610  fts5StructureRelease(pStruct);
189611
189612  assert( pNew==0 || pNew->nSegment>0 );
189613  if( pNew ){
189614    int iLvl;
189615    for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
189616    while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
189617      int nRem = FTS5_OPT_WORK_UNIT;
189618      fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
189619    }
189620
189621    fts5StructureWrite(p, pNew);
189622    fts5StructureRelease(pNew);
189623  }
189624
189625  return fts5IndexReturn(p);
189626}
189627
189628/*
189629** This is called to implement the special "VALUES('merge', $nMerge)"
189630** INSERT command.
189631*/
189632static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
189633  Fts5Structure *pStruct = fts5StructureRead(p);
189634  if( pStruct ){
189635    int nMin = p->pConfig->nUsermerge;
189636    fts5StructureInvalidate(p);
189637    if( nMerge<0 ){
189638      Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
189639      fts5StructureRelease(pStruct);
189640      pStruct = pNew;
189641      nMin = 2;
189642      nMerge = nMerge*-1;
189643    }
189644    if( pStruct && pStruct->nLevel ){
189645      if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
189646        fts5StructureWrite(p, pStruct);
189647      }
189648    }
189649    fts5StructureRelease(pStruct);
189650  }
189651  return fts5IndexReturn(p);
189652}
189653
189654static void fts5AppendRowid(
189655  Fts5Index *p,
189656  i64 iDelta,
189657  Fts5Iter *pUnused,
189658  Fts5Buffer *pBuf
189659){
189660  UNUSED_PARAM(pUnused);
189661  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
189662}
189663
189664static void fts5AppendPoslist(
189665  Fts5Index *p,
189666  i64 iDelta,
189667  Fts5Iter *pMulti,
189668  Fts5Buffer *pBuf
189669){
189670  int nData = pMulti->base.nData;
189671  assert( nData>0 );
189672  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
189673    fts5BufferSafeAppendVarint(pBuf, iDelta);
189674    fts5BufferSafeAppendVarint(pBuf, nData*2);
189675    fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
189676  }
189677}
189678
189679
189680static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
189681  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
189682
189683  assert( pIter->aPoslist );
189684  if( p>=pIter->aEof ){
189685    pIter->aPoslist = 0;
189686  }else{
189687    i64 iDelta;
189688
189689    p += fts5GetVarint(p, (u64*)&iDelta);
189690    pIter->iRowid += iDelta;
189691
189692    /* Read position list size */
189693    if( p[0] & 0x80 ){
189694      int nPos;
189695      pIter->nSize = fts5GetVarint32(p, nPos);
189696      pIter->nPoslist = (nPos>>1);
189697    }else{
189698      pIter->nPoslist = ((int)(p[0])) >> 1;
189699      pIter->nSize = 1;
189700    }
189701
189702    pIter->aPoslist = p;
189703  }
189704}
189705
189706static void fts5DoclistIterInit(
189707  Fts5Buffer *pBuf,
189708  Fts5DoclistIter *pIter
189709){
189710  memset(pIter, 0, sizeof(*pIter));
189711  pIter->aPoslist = pBuf->p;
189712  pIter->aEof = &pBuf->p[pBuf->n];
189713  fts5DoclistIterNext(pIter);
189714}
189715
189716#if 0
189717/*
189718** Append a doclist to buffer pBuf.
189719**
189720** This function assumes that space within the buffer has already been
189721** allocated.
189722*/
189723static void fts5MergeAppendDocid(
189724  Fts5Buffer *pBuf,               /* Buffer to write to */
189725  i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
189726  i64 iRowid                      /* Rowid to append */
189727){
189728  assert( pBuf->n!=0 || (*piLastRowid)==0 );
189729  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
189730  *piLastRowid = iRowid;
189731}
189732#endif
189733
189734#define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
189735  assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
189736  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
189737  (iLastRowid) = (iRowid);                                     \
189738}
189739
189740/*
189741** Swap the contents of buffer *p1 with that of *p2.
189742*/
189743static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
189744  Fts5Buffer tmp = *p1;
189745  *p1 = *p2;
189746  *p2 = tmp;
189747}
189748
189749static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
189750  int i = *piOff;
189751  if( i>=pBuf->n ){
189752    *piOff = -1;
189753  }else{
189754    u64 iVal;
189755    *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
189756    *piRowid += iVal;
189757  }
189758}
189759
189760/*
189761** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
189762** In this case the buffers consist of a delta-encoded list of rowids only.
189763*/
189764static void fts5MergeRowidLists(
189765  Fts5Index *p,                   /* FTS5 backend object */
189766  Fts5Buffer *p1,                 /* First list to merge */
189767  Fts5Buffer *p2                  /* Second list to merge */
189768){
189769  int i1 = 0;
189770  int i2 = 0;
189771  i64 iRowid1 = 0;
189772  i64 iRowid2 = 0;
189773  i64 iOut = 0;
189774
189775  Fts5Buffer out;
189776  memset(&out, 0, sizeof(out));
189777  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
189778  if( p->rc ) return;
189779
189780  fts5NextRowid(p1, &i1, &iRowid1);
189781  fts5NextRowid(p2, &i2, &iRowid2);
189782  while( i1>=0 || i2>=0 ){
189783    if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
189784      assert( iOut==0 || iRowid1>iOut );
189785      fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
189786      iOut = iRowid1;
189787      fts5NextRowid(p1, &i1, &iRowid1);
189788    }else{
189789      assert( iOut==0 || iRowid2>iOut );
189790      fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
189791      iOut = iRowid2;
189792      if( i1>=0 && iRowid1==iRowid2 ){
189793        fts5NextRowid(p1, &i1, &iRowid1);
189794      }
189795      fts5NextRowid(p2, &i2, &iRowid2);
189796    }
189797  }
189798
189799  fts5BufferSwap(&out, p1);
189800  fts5BufferFree(&out);
189801}
189802
189803/*
189804** Buffers p1 and p2 contain doclists. This function merges the content
189805** of the two doclists together and sets buffer p1 to the result before
189806** returning.
189807**
189808** If an error occurs, an error code is left in p->rc. If an error has
189809** already occurred, this function is a no-op.
189810*/
189811static void fts5MergePrefixLists(
189812  Fts5Index *p,                   /* FTS5 backend object */
189813  Fts5Buffer *p1,                 /* First list to merge */
189814  Fts5Buffer *p2                  /* Second list to merge */
189815){
189816  if( p2->n ){
189817    i64 iLastRowid = 0;
189818    Fts5DoclistIter i1;
189819    Fts5DoclistIter i2;
189820    Fts5Buffer out = {0, 0, 0};
189821    Fts5Buffer tmp = {0, 0, 0};
189822
189823    if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
189824    fts5DoclistIterInit(p1, &i1);
189825    fts5DoclistIterInit(p2, &i2);
189826
189827    while( 1 ){
189828      if( i1.iRowid<i2.iRowid ){
189829        /* Copy entry from i1 */
189830        fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
189831        fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
189832        fts5DoclistIterNext(&i1);
189833        if( i1.aPoslist==0 ) break;
189834      }
189835      else if( i2.iRowid!=i1.iRowid ){
189836        /* Copy entry from i2 */
189837        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189838        fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
189839        fts5DoclistIterNext(&i2);
189840        if( i2.aPoslist==0 ) break;
189841      }
189842      else{
189843        /* Merge the two position lists. */
189844        i64 iPos1 = 0;
189845        i64 iPos2 = 0;
189846        int iOff1 = 0;
189847        int iOff2 = 0;
189848        u8 *a1 = &i1.aPoslist[i1.nSize];
189849        u8 *a2 = &i2.aPoslist[i2.nSize];
189850
189851        i64 iPrev = 0;
189852        Fts5PoslistWriter writer;
189853        memset(&writer, 0, sizeof(writer));
189854
189855        fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189856        fts5BufferZero(&tmp);
189857        sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
189858        if( p->rc ) break;
189859
189860        sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189861        sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189862        assert( iPos1>=0 && iPos2>=0 );
189863
189864        if( iPos1<iPos2 ){
189865          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189866          sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189867        }else{
189868          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189869          sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189870        }
189871
189872        if( iPos1>=0 && iPos2>=0 ){
189873          while( 1 ){
189874            if( iPos1<iPos2 ){
189875              if( iPos1!=iPrev ){
189876                sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189877              }
189878              sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189879              if( iPos1<0 ) break;
189880            }else{
189881              assert( iPos2!=iPrev );
189882              sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189883              sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189884              if( iPos2<0 ) break;
189885            }
189886          }
189887        }
189888
189889        if( iPos1>=0 ){
189890          if( iPos1!=iPrev ){
189891            sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189892          }
189893          fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
189894        }else{
189895          assert( iPos2>=0 && iPos2!=iPrev );
189896          sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189897          fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
189898        }
189899
189900        /* WRITEPOSLISTSIZE */
189901        fts5BufferSafeAppendVarint(&out, tmp.n * 2);
189902        fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
189903        fts5DoclistIterNext(&i1);
189904        fts5DoclistIterNext(&i2);
189905        if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
189906      }
189907    }
189908
189909    if( i1.aPoslist ){
189910      fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
189911      fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
189912    }
189913    else if( i2.aPoslist ){
189914      fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189915      fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
189916    }
189917
189918    fts5BufferSet(&p->rc, p1, out.n, out.p);
189919    fts5BufferFree(&tmp);
189920    fts5BufferFree(&out);
189921  }
189922}
189923
189924static void fts5SetupPrefixIter(
189925  Fts5Index *p,                   /* Index to read from */
189926  int bDesc,                      /* True for "ORDER BY rowid DESC" */
189927  const u8 *pToken,               /* Buffer containing prefix to match */
189928  int nToken,                     /* Size of buffer pToken in bytes */
189929  Fts5Colset *pColset,            /* Restrict matches to these columns */
189930  Fts5Iter **ppIter          /* OUT: New iterator */
189931){
189932  Fts5Structure *pStruct;
189933  Fts5Buffer *aBuf;
189934  const int nBuf = 32;
189935
189936  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
189937  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
189938  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
189939    xMerge = fts5MergeRowidLists;
189940    xAppend = fts5AppendRowid;
189941  }else{
189942    xMerge = fts5MergePrefixLists;
189943    xAppend = fts5AppendPoslist;
189944  }
189945
189946  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
189947  pStruct = fts5StructureRead(p);
189948
189949  if( aBuf && pStruct ){
189950    const int flags = FTS5INDEX_QUERY_SCAN
189951                    | FTS5INDEX_QUERY_SKIPEMPTY
189952                    | FTS5INDEX_QUERY_NOOUTPUT;
189953    int i;
189954    i64 iLastRowid = 0;
189955    Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
189956    Fts5Data *pData;
189957    Fts5Buffer doclist;
189958    int bNewTerm = 1;
189959
189960    memset(&doclist, 0, sizeof(doclist));
189961    fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
189962    fts5IterSetOutputCb(&p->rc, p1);
189963    for( /* no-op */ ;
189964        fts5MultiIterEof(p, p1)==0;
189965        fts5MultiIterNext2(p, p1, &bNewTerm)
189966    ){
189967      Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
189968      int nTerm = pSeg->term.n;
189969      const u8 *pTerm = pSeg->term.p;
189970      p1->xSetOutputs(p1, pSeg);
189971
189972      assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
189973      if( bNewTerm ){
189974        if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
189975      }
189976
189977      if( p1->base.nData==0 ) continue;
189978
189979      if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
189980        for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
189981          assert( i<nBuf );
189982          if( aBuf[i].n==0 ){
189983            fts5BufferSwap(&doclist, &aBuf[i]);
189984            fts5BufferZero(&doclist);
189985          }else{
189986            xMerge(p, &doclist, &aBuf[i]);
189987            fts5BufferZero(&aBuf[i]);
189988          }
189989        }
189990        iLastRowid = 0;
189991      }
189992
189993      xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
189994      iLastRowid = p1->base.iRowid;
189995    }
189996
189997    for(i=0; i<nBuf; i++){
189998      if( p->rc==SQLITE_OK ){
189999        xMerge(p, &doclist, &aBuf[i]);
190000      }
190001      fts5BufferFree(&aBuf[i]);
190002    }
190003    fts5MultiIterFree(p1);
190004
190005    pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
190006    if( pData ){
190007      pData->p = (u8*)&pData[1];
190008      pData->nn = pData->szLeaf = doclist.n;
190009      memcpy(pData->p, doclist.p, doclist.n);
190010      fts5MultiIterNew2(p, pData, bDesc, ppIter);
190011    }
190012    fts5BufferFree(&doclist);
190013  }
190014
190015  fts5StructureRelease(pStruct);
190016  sqlite3_free(aBuf);
190017}
190018
190019
190020/*
190021** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
190022** to the document with rowid iRowid.
190023*/
190024static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
190025  assert( p->rc==SQLITE_OK );
190026
190027  /* Allocate the hash table if it has not already been allocated */
190028  if( p->pHash==0 ){
190029    p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
190030  }
190031
190032  /* Flush the hash table to disk if required */
190033  if( iRowid<p->iWriteRowid
190034   || (iRowid==p->iWriteRowid && p->bDelete==0)
190035   || (p->nPendingData > p->pConfig->nHashSize)
190036  ){
190037    fts5IndexFlush(p);
190038  }
190039
190040  p->iWriteRowid = iRowid;
190041  p->bDelete = bDelete;
190042  return fts5IndexReturn(p);
190043}
190044
190045/*
190046** Commit data to disk.
190047*/
190048static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
190049  assert( p->rc==SQLITE_OK );
190050  fts5IndexFlush(p);
190051  if( bCommit ) fts5CloseReader(p);
190052  return fts5IndexReturn(p);
190053}
190054
190055/*
190056** Discard any data stored in the in-memory hash tables. Do not write it
190057** to the database. Additionally, assume that the contents of the %_data
190058** table may have changed on disk. So any in-memory caches of %_data
190059** records must be invalidated.
190060*/
190061static int sqlite3Fts5IndexRollback(Fts5Index *p){
190062  fts5CloseReader(p);
190063  fts5IndexDiscardData(p);
190064  fts5StructureInvalidate(p);
190065  /* assert( p->rc==SQLITE_OK ); */
190066  return SQLITE_OK;
190067}
190068
190069/*
190070** The %_data table is completely empty when this function is called. This
190071** function populates it with the initial structure objects for each index,
190072** and the initial version of the "averages" record (a zero-byte blob).
190073*/
190074static int sqlite3Fts5IndexReinit(Fts5Index *p){
190075  Fts5Structure s;
190076  fts5StructureInvalidate(p);
190077  memset(&s, 0, sizeof(Fts5Structure));
190078  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
190079  fts5StructureWrite(p, &s);
190080  return fts5IndexReturn(p);
190081}
190082
190083/*
190084** Open a new Fts5Index handle. If the bCreate argument is true, create
190085** and initialize the underlying %_data table.
190086**
190087** If successful, set *pp to point to the new object and return SQLITE_OK.
190088** Otherwise, set *pp to NULL and return an SQLite error code.
190089*/
190090static int sqlite3Fts5IndexOpen(
190091  Fts5Config *pConfig,
190092  int bCreate,
190093  Fts5Index **pp,
190094  char **pzErr
190095){
190096  int rc = SQLITE_OK;
190097  Fts5Index *p;                   /* New object */
190098
190099  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
190100  if( rc==SQLITE_OK ){
190101    p->pConfig = pConfig;
190102    p->nWorkUnit = FTS5_WORK_UNIT;
190103    p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
190104    if( p->zDataTbl && bCreate ){
190105      rc = sqlite3Fts5CreateTable(
190106          pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
190107      );
190108      if( rc==SQLITE_OK ){
190109        rc = sqlite3Fts5CreateTable(pConfig, "idx",
190110            "segid, term, pgno, PRIMARY KEY(segid, term)",
190111            1, pzErr
190112        );
190113      }
190114      if( rc==SQLITE_OK ){
190115        rc = sqlite3Fts5IndexReinit(p);
190116      }
190117    }
190118  }
190119
190120  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
190121  if( rc ){
190122    sqlite3Fts5IndexClose(p);
190123    *pp = 0;
190124  }
190125  return rc;
190126}
190127
190128/*
190129** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
190130*/
190131static int sqlite3Fts5IndexClose(Fts5Index *p){
190132  int rc = SQLITE_OK;
190133  if( p ){
190134    assert( p->pReader==0 );
190135    fts5StructureInvalidate(p);
190136    sqlite3_finalize(p->pWriter);
190137    sqlite3_finalize(p->pDeleter);
190138    sqlite3_finalize(p->pIdxWriter);
190139    sqlite3_finalize(p->pIdxDeleter);
190140    sqlite3_finalize(p->pIdxSelect);
190141    sqlite3_finalize(p->pDataVersion);
190142    sqlite3Fts5HashFree(p->pHash);
190143    sqlite3_free(p->zDataTbl);
190144    sqlite3_free(p);
190145  }
190146  return rc;
190147}
190148
190149/*
190150** Argument p points to a buffer containing utf-8 text that is n bytes in
190151** size. Return the number of bytes in the nChar character prefix of the
190152** buffer, or 0 if there are less than nChar characters in total.
190153*/
190154static int sqlite3Fts5IndexCharlenToBytelen(
190155  const char *p,
190156  int nByte,
190157  int nChar
190158){
190159  int n = 0;
190160  int i;
190161  for(i=0; i<nChar; i++){
190162    if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
190163    if( (unsigned char)p[n++]>=0xc0 ){
190164      while( (p[n] & 0xc0)==0x80 ) n++;
190165    }
190166  }
190167  return n;
190168}
190169
190170/*
190171** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
190172** unicode characters in the string.
190173*/
190174static int fts5IndexCharlen(const char *pIn, int nIn){
190175  int nChar = 0;
190176  int i = 0;
190177  while( i<nIn ){
190178    if( (unsigned char)pIn[i++]>=0xc0 ){
190179      while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
190180    }
190181    nChar++;
190182  }
190183  return nChar;
190184}
190185
190186/*
190187** Insert or remove data to or from the index. Each time a document is
190188** added to or removed from the index, this function is called one or more
190189** times.
190190**
190191** For an insert, it must be called once for each token in the new document.
190192** If the operation is a delete, it must be called (at least) once for each
190193** unique token in the document with an iCol value less than zero. The iPos
190194** argument is ignored for a delete.
190195*/
190196static int sqlite3Fts5IndexWrite(
190197  Fts5Index *p,                   /* Index to write to */
190198  int iCol,                       /* Column token appears in (-ve -> delete) */
190199  int iPos,                       /* Position of token within column */
190200  const char *pToken, int nToken  /* Token to add or remove to or from index */
190201){
190202  int i;                          /* Used to iterate through indexes */
190203  int rc = SQLITE_OK;             /* Return code */
190204  Fts5Config *pConfig = p->pConfig;
190205
190206  assert( p->rc==SQLITE_OK );
190207  assert( (iCol<0)==p->bDelete );
190208
190209  /* Add the entry to the main terms index. */
190210  rc = sqlite3Fts5HashWrite(
190211      p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
190212  );
190213
190214  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
190215    const int nChar = pConfig->aPrefix[i];
190216    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
190217    if( nByte ){
190218      rc = sqlite3Fts5HashWrite(p->pHash,
190219          p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
190220          nByte
190221      );
190222    }
190223  }
190224
190225  return rc;
190226}
190227
190228/*
190229** Open a new iterator to iterate though all rowid that match the
190230** specified token or token prefix.
190231*/
190232static int sqlite3Fts5IndexQuery(
190233  Fts5Index *p,                   /* FTS index to query */
190234  const char *pToken, int nToken, /* Token (or prefix) to query for */
190235  int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
190236  Fts5Colset *pColset,            /* Match these columns only */
190237  Fts5IndexIter **ppIter          /* OUT: New iterator object */
190238){
190239  Fts5Config *pConfig = p->pConfig;
190240  Fts5Iter *pRet = 0;
190241  Fts5Buffer buf = {0, 0, 0};
190242
190243  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
190244  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
190245
190246  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
190247    int iIdx = 0;                 /* Index to search */
190248    memcpy(&buf.p[1], pToken, nToken);
190249
190250    /* Figure out which index to search and set iIdx accordingly. If this
190251    ** is a prefix query for which there is no prefix index, set iIdx to
190252    ** greater than pConfig->nPrefix to indicate that the query will be
190253    ** satisfied by scanning multiple terms in the main index.
190254    **
190255    ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
190256    ** prefix-query. Instead of using a prefix-index (if one exists),
190257    ** evaluate the prefix query using the main FTS index. This is used
190258    ** for internal sanity checking by the integrity-check in debug
190259    ** mode only.  */
190260#ifdef SQLITE_DEBUG
190261    if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
190262      assert( flags & FTS5INDEX_QUERY_PREFIX );
190263      iIdx = 1+pConfig->nPrefix;
190264    }else
190265#endif
190266    if( flags & FTS5INDEX_QUERY_PREFIX ){
190267      int nChar = fts5IndexCharlen(pToken, nToken);
190268      for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
190269        if( pConfig->aPrefix[iIdx-1]==nChar ) break;
190270      }
190271    }
190272
190273    if( iIdx<=pConfig->nPrefix ){
190274      /* Straight index lookup */
190275      Fts5Structure *pStruct = fts5StructureRead(p);
190276      buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
190277      if( pStruct ){
190278        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
190279            pColset, buf.p, nToken+1, -1, 0, &pRet
190280        );
190281        fts5StructureRelease(pStruct);
190282      }
190283    }else{
190284      /* Scan multiple terms in the main index */
190285      int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
190286      buf.p[0] = FTS5_MAIN_PREFIX;
190287      fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
190288      assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
190289      fts5IterSetOutputCb(&p->rc, pRet);
190290      if( p->rc==SQLITE_OK ){
190291        Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
190292        if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
190293      }
190294    }
190295
190296    if( p->rc ){
190297      sqlite3Fts5IterClose(&pRet->base);
190298      pRet = 0;
190299      fts5CloseReader(p);
190300    }
190301
190302    *ppIter = &pRet->base;
190303    sqlite3Fts5BufferFree(&buf);
190304  }
190305  return fts5IndexReturn(p);
190306}
190307
190308/*
190309** Return true if the iterator passed as the only argument is at EOF.
190310*/
190311/*
190312** Move to the next matching rowid.
190313*/
190314static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
190315  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190316  assert( pIter->pIndex->rc==SQLITE_OK );
190317  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
190318  return fts5IndexReturn(pIter->pIndex);
190319}
190320
190321/*
190322** Move to the next matching term/rowid. Used by the fts5vocab module.
190323*/
190324static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
190325  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190326  Fts5Index *p = pIter->pIndex;
190327
190328  assert( pIter->pIndex->rc==SQLITE_OK );
190329
190330  fts5MultiIterNext(p, pIter, 0, 0);
190331  if( p->rc==SQLITE_OK ){
190332    Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190333    if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
190334      fts5DataRelease(pSeg->pLeaf);
190335      pSeg->pLeaf = 0;
190336      pIter->base.bEof = 1;
190337    }
190338  }
190339
190340  return fts5IndexReturn(pIter->pIndex);
190341}
190342
190343/*
190344** Move to the next matching rowid that occurs at or after iMatch. The
190345** definition of "at or after" depends on whether this iterator iterates
190346** in ascending or descending rowid order.
190347*/
190348static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
190349  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190350  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
190351  return fts5IndexReturn(pIter->pIndex);
190352}
190353
190354/*
190355** Return the current term.
190356*/
190357static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
190358  int n;
190359  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
190360  *pn = n-1;
190361  return &z[1];
190362}
190363
190364/*
190365** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
190366*/
190367static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
190368  if( pIndexIter ){
190369    Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190370    Fts5Index *pIndex = pIter->pIndex;
190371    fts5MultiIterFree(pIter);
190372    fts5CloseReader(pIndex);
190373  }
190374}
190375
190376/*
190377** Read and decode the "averages" record from the database.
190378**
190379** Parameter anSize must point to an array of size nCol, where nCol is
190380** the number of user defined columns in the FTS table.
190381*/
190382static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
190383  int nCol = p->pConfig->nCol;
190384  Fts5Data *pData;
190385
190386  *pnRow = 0;
190387  memset(anSize, 0, sizeof(i64) * nCol);
190388  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
190389  if( p->rc==SQLITE_OK && pData->nn ){
190390    int i = 0;
190391    int iCol;
190392    i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
190393    for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
190394      i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
190395    }
190396  }
190397
190398  fts5DataRelease(pData);
190399  return fts5IndexReturn(p);
190400}
190401
190402/*
190403** Replace the current "averages" record with the contents of the buffer
190404** supplied as the second argument.
190405*/
190406static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
190407  assert( p->rc==SQLITE_OK );
190408  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
190409  return fts5IndexReturn(p);
190410}
190411
190412/*
190413** Return the total number of blocks this module has read from the %_data
190414** table since it was created.
190415*/
190416static int sqlite3Fts5IndexReads(Fts5Index *p){
190417  return p->nRead;
190418}
190419
190420/*
190421** Set the 32-bit cookie value stored at the start of all structure
190422** records to the value passed as the second argument.
190423**
190424** Return SQLITE_OK if successful, or an SQLite error code if an error
190425** occurs.
190426*/
190427static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
190428  int rc;                              /* Return code */
190429  Fts5Config *pConfig = p->pConfig;    /* Configuration object */
190430  u8 aCookie[4];                       /* Binary representation of iNew */
190431  sqlite3_blob *pBlob = 0;
190432
190433  assert( p->rc==SQLITE_OK );
190434  sqlite3Fts5Put32(aCookie, iNew);
190435
190436  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
190437      "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
190438  );
190439  if( rc==SQLITE_OK ){
190440    sqlite3_blob_write(pBlob, aCookie, 4, 0);
190441    rc = sqlite3_blob_close(pBlob);
190442  }
190443
190444  return rc;
190445}
190446
190447static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
190448  Fts5Structure *pStruct;
190449  pStruct = fts5StructureRead(p);
190450  fts5StructureRelease(pStruct);
190451  return fts5IndexReturn(p);
190452}
190453
190454
190455/*************************************************************************
190456**************************************************************************
190457** Below this point is the implementation of the integrity-check
190458** functionality.
190459*/
190460
190461/*
190462** Return a simple checksum value based on the arguments.
190463*/
190464static u64 sqlite3Fts5IndexEntryCksum(
190465  i64 iRowid,
190466  int iCol,
190467  int iPos,
190468  int iIdx,
190469  const char *pTerm,
190470  int nTerm
190471){
190472  int i;
190473  u64 ret = iRowid;
190474  ret += (ret<<3) + iCol;
190475  ret += (ret<<3) + iPos;
190476  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
190477  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
190478  return ret;
190479}
190480
190481#ifdef SQLITE_DEBUG
190482/*
190483** This function is purely an internal test. It does not contribute to
190484** FTS functionality, or even the integrity-check, in any way.
190485**
190486** Instead, it tests that the same set of pgno/rowid combinations are
190487** visited regardless of whether the doclist-index identified by parameters
190488** iSegid/iLeaf is iterated in forwards or reverse order.
190489*/
190490static void fts5TestDlidxReverse(
190491  Fts5Index *p,
190492  int iSegid,                     /* Segment id to load from */
190493  int iLeaf                       /* Load doclist-index for this leaf */
190494){
190495  Fts5DlidxIter *pDlidx = 0;
190496  u64 cksum1 = 13;
190497  u64 cksum2 = 13;
190498
190499  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
190500      fts5DlidxIterEof(p, pDlidx)==0;
190501      fts5DlidxIterNext(p, pDlidx)
190502  ){
190503    i64 iRowid = fts5DlidxIterRowid(pDlidx);
190504    int pgno = fts5DlidxIterPgno(pDlidx);
190505    assert( pgno>iLeaf );
190506    cksum1 += iRowid + ((i64)pgno<<32);
190507  }
190508  fts5DlidxIterFree(pDlidx);
190509  pDlidx = 0;
190510
190511  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
190512      fts5DlidxIterEof(p, pDlidx)==0;
190513      fts5DlidxIterPrev(p, pDlidx)
190514  ){
190515    i64 iRowid = fts5DlidxIterRowid(pDlidx);
190516    int pgno = fts5DlidxIterPgno(pDlidx);
190517    assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
190518    cksum2 += iRowid + ((i64)pgno<<32);
190519  }
190520  fts5DlidxIterFree(pDlidx);
190521  pDlidx = 0;
190522
190523  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
190524}
190525
190526static int fts5QueryCksum(
190527  Fts5Index *p,                   /* Fts5 index object */
190528  int iIdx,
190529  const char *z,                  /* Index key to query for */
190530  int n,                          /* Size of index key in bytes */
190531  int flags,                      /* Flags for Fts5IndexQuery */
190532  u64 *pCksum                     /* IN/OUT: Checksum value */
190533){
190534  int eDetail = p->pConfig->eDetail;
190535  u64 cksum = *pCksum;
190536  Fts5IndexIter *pIter = 0;
190537  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
190538
190539  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
190540    i64 rowid = pIter->iRowid;
190541
190542    if( eDetail==FTS5_DETAIL_NONE ){
190543      cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
190544    }else{
190545      Fts5PoslistReader sReader;
190546      for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
190547          sReader.bEof==0;
190548          sqlite3Fts5PoslistReaderNext(&sReader)
190549      ){
190550        int iCol = FTS5_POS2COLUMN(sReader.iPos);
190551        int iOff = FTS5_POS2OFFSET(sReader.iPos);
190552        cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
190553      }
190554    }
190555    if( rc==SQLITE_OK ){
190556      rc = sqlite3Fts5IterNext(pIter);
190557    }
190558  }
190559  sqlite3Fts5IterClose(pIter);
190560
190561  *pCksum = cksum;
190562  return rc;
190563}
190564
190565
190566/*
190567** This function is also purely an internal test. It does not contribute to
190568** FTS functionality, or even the integrity-check, in any way.
190569*/
190570static void fts5TestTerm(
190571  Fts5Index *p,
190572  Fts5Buffer *pPrev,              /* Previous term */
190573  const char *z, int n,           /* Possibly new term to test */
190574  u64 expected,
190575  u64 *pCksum
190576){
190577  int rc = p->rc;
190578  if( pPrev->n==0 ){
190579    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
190580  }else
190581  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
190582    u64 cksum3 = *pCksum;
190583    const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
190584    int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
190585    int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
190586    int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
190587    u64 ck1 = 0;
190588    u64 ck2 = 0;
190589
190590    /* Check that the results returned for ASC and DESC queries are
190591    ** the same. If not, call this corruption.  */
190592    rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
190593    if( rc==SQLITE_OK ){
190594      int f = flags|FTS5INDEX_QUERY_DESC;
190595      rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190596    }
190597    if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190598
190599    /* If this is a prefix query, check that the results returned if the
190600    ** the index is disabled are the same. In both ASC and DESC order.
190601    **
190602    ** This check may only be performed if the hash table is empty. This
190603    ** is because the hash table only supports a single scan query at
190604    ** a time, and the multi-iter loop from which this function is called
190605    ** is already performing such a scan. */
190606    if( p->nPendingData==0 ){
190607      if( iIdx>0 && rc==SQLITE_OK ){
190608        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
190609        ck2 = 0;
190610        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190611        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190612      }
190613      if( iIdx>0 && rc==SQLITE_OK ){
190614        int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
190615        ck2 = 0;
190616        rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190617        if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190618      }
190619    }
190620
190621    cksum3 ^= ck1;
190622    fts5BufferSet(&rc, pPrev, n, (const u8*)z);
190623
190624    if( rc==SQLITE_OK && cksum3!=expected ){
190625      rc = FTS5_CORRUPT;
190626    }
190627    *pCksum = cksum3;
190628  }
190629  p->rc = rc;
190630}
190631
190632#else
190633# define fts5TestDlidxReverse(x,y,z)
190634# define fts5TestTerm(u,v,w,x,y,z)
190635#endif
190636
190637/*
190638** Check that:
190639**
190640**   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
190641**      contain zero terms.
190642**   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
190643**      contain zero rowids.
190644*/
190645static void fts5IndexIntegrityCheckEmpty(
190646  Fts5Index *p,
190647  Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
190648  int iFirst,
190649  int iNoRowid,
190650  int iLast
190651){
190652  int i;
190653
190654  /* Now check that the iter.nEmpty leaves following the current leaf
190655  ** (a) exist and (b) contain no terms. */
190656  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
190657    Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
190658    if( pLeaf ){
190659      if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
190660      if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
190661    }
190662    fts5DataRelease(pLeaf);
190663  }
190664}
190665
190666static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
190667  int iTermOff = 0;
190668  int ii;
190669
190670  Fts5Buffer buf1 = {0,0,0};
190671  Fts5Buffer buf2 = {0,0,0};
190672
190673  ii = pLeaf->szLeaf;
190674  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
190675    int res;
190676    int iOff;
190677    int nIncr;
190678
190679    ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
190680    iTermOff += nIncr;
190681    iOff = iTermOff;
190682
190683    if( iOff>=pLeaf->szLeaf ){
190684      p->rc = FTS5_CORRUPT;
190685    }else if( iTermOff==nIncr ){
190686      int nByte;
190687      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
190688      if( (iOff+nByte)>pLeaf->szLeaf ){
190689        p->rc = FTS5_CORRUPT;
190690      }else{
190691        fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
190692      }
190693    }else{
190694      int nKeep, nByte;
190695      iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
190696      iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
190697      if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
190698        p->rc = FTS5_CORRUPT;
190699      }else{
190700        buf1.n = nKeep;
190701        fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
190702      }
190703
190704      if( p->rc==SQLITE_OK ){
190705        res = fts5BufferCompare(&buf1, &buf2);
190706        if( res<=0 ) p->rc = FTS5_CORRUPT;
190707      }
190708    }
190709    fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
190710  }
190711
190712  fts5BufferFree(&buf1);
190713  fts5BufferFree(&buf2);
190714}
190715
190716static void fts5IndexIntegrityCheckSegment(
190717  Fts5Index *p,                   /* FTS5 backend object */
190718  Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
190719){
190720  Fts5Config *pConfig = p->pConfig;
190721  sqlite3_stmt *pStmt = 0;
190722  int rc2;
190723  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
190724  int iDlidxPrevLeaf = pSeg->pgnoLast;
190725
190726  if( pSeg->pgnoFirst==0 ) return;
190727
190728  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
190729      "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
190730      pConfig->zDb, pConfig->zName, pSeg->iSegid
190731  ));
190732
190733  /* Iterate through the b-tree hierarchy.  */
190734  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
190735    i64 iRow;                     /* Rowid for this leaf */
190736    Fts5Data *pLeaf;              /* Data for this leaf */
190737
190738    int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
190739    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
190740    int iIdxLeaf = sqlite3_column_int(pStmt, 2);
190741    int bIdxDlidx = sqlite3_column_int(pStmt, 3);
190742
190743    /* If the leaf in question has already been trimmed from the segment,
190744    ** ignore this b-tree entry. Otherwise, load it into memory. */
190745    if( iIdxLeaf<pSeg->pgnoFirst ) continue;
190746    iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
190747    pLeaf = fts5DataRead(p, iRow);
190748    if( pLeaf==0 ) break;
190749
190750    /* Check that the leaf contains at least one term, and that it is equal
190751    ** to or larger than the split-key in zIdxTerm.  Also check that if there
190752    ** is also a rowid pointer within the leaf page header, it points to a
190753    ** location before the term.  */
190754    if( pLeaf->nn<=pLeaf->szLeaf ){
190755      p->rc = FTS5_CORRUPT;
190756    }else{
190757      int iOff;                   /* Offset of first term on leaf */
190758      int iRowidOff;              /* Offset of first rowid on leaf */
190759      int nTerm;                  /* Size of term on leaf in bytes */
190760      int res;                    /* Comparison of term and split-key */
190761
190762      iOff = fts5LeafFirstTermOff(pLeaf);
190763      iRowidOff = fts5LeafFirstRowidOff(pLeaf);
190764      if( iRowidOff>=iOff ){
190765        p->rc = FTS5_CORRUPT;
190766      }else{
190767        iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
190768        res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
190769        if( res==0 ) res = nTerm - nIdxTerm;
190770        if( res<0 ) p->rc = FTS5_CORRUPT;
190771      }
190772
190773      fts5IntegrityCheckPgidx(p, pLeaf);
190774    }
190775    fts5DataRelease(pLeaf);
190776    if( p->rc ) break;
190777
190778    /* Now check that the iter.nEmpty leaves following the current leaf
190779    ** (a) exist and (b) contain no terms. */
190780    fts5IndexIntegrityCheckEmpty(
190781        p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
190782    );
190783    if( p->rc ) break;
190784
190785    /* If there is a doclist-index, check that it looks right. */
190786    if( bIdxDlidx ){
190787      Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
190788      int iPrevLeaf = iIdxLeaf;
190789      int iSegid = pSeg->iSegid;
190790      int iPg = 0;
190791      i64 iKey;
190792
190793      for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
190794          fts5DlidxIterEof(p, pDlidx)==0;
190795          fts5DlidxIterNext(p, pDlidx)
190796      ){
190797
190798        /* Check any rowid-less pages that occur before the current leaf. */
190799        for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
190800          iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
190801          pLeaf = fts5DataRead(p, iKey);
190802          if( pLeaf ){
190803            if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
190804            fts5DataRelease(pLeaf);
190805          }
190806        }
190807        iPrevLeaf = fts5DlidxIterPgno(pDlidx);
190808
190809        /* Check that the leaf page indicated by the iterator really does
190810        ** contain the rowid suggested by the same. */
190811        iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
190812        pLeaf = fts5DataRead(p, iKey);
190813        if( pLeaf ){
190814          i64 iRowid;
190815          int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
190816          ASSERT_SZLEAF_OK(pLeaf);
190817          if( iRowidOff>=pLeaf->szLeaf ){
190818            p->rc = FTS5_CORRUPT;
190819          }else{
190820            fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
190821            if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
190822          }
190823          fts5DataRelease(pLeaf);
190824        }
190825      }
190826
190827      iDlidxPrevLeaf = iPg;
190828      fts5DlidxIterFree(pDlidx);
190829      fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
190830    }else{
190831      iDlidxPrevLeaf = pSeg->pgnoLast;
190832      /* TODO: Check there is no doclist index */
190833    }
190834
190835    iIdxPrevLeaf = iIdxLeaf;
190836  }
190837
190838  rc2 = sqlite3_finalize(pStmt);
190839  if( p->rc==SQLITE_OK ) p->rc = rc2;
190840
190841  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
190842#if 0
190843  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
190844    p->rc = FTS5_CORRUPT;
190845  }
190846#endif
190847}
190848
190849
190850/*
190851** Run internal checks to ensure that the FTS index (a) is internally
190852** consistent and (b) contains entries for which the XOR of the checksums
190853** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
190854**
190855** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
190856** checksum does not match. Return SQLITE_OK if all checks pass without
190857** error, or some other SQLite error code if another error (e.g. OOM)
190858** occurs.
190859*/
190860static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
190861  int eDetail = p->pConfig->eDetail;
190862  u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
190863  Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
190864  Fts5Iter *pIter;                /* Used to iterate through entire index */
190865  Fts5Structure *pStruct;         /* Index structure */
190866
190867#ifdef SQLITE_DEBUG
190868  /* Used by extra internal tests only run if NDEBUG is not defined */
190869  u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
190870  Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
190871#endif
190872  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
190873
190874  /* Load the FTS index structure */
190875  pStruct = fts5StructureRead(p);
190876
190877  /* Check that the internal nodes of each segment match the leaves */
190878  if( pStruct ){
190879    int iLvl, iSeg;
190880    for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190881      for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190882        Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
190883        fts5IndexIntegrityCheckSegment(p, pSeg);
190884      }
190885    }
190886  }
190887
190888  /* The cksum argument passed to this function is a checksum calculated
190889  ** based on all expected entries in the FTS index (including prefix index
190890  ** entries). This block checks that a checksum calculated based on the
190891  ** actual contents of FTS index is identical.
190892  **
190893  ** Two versions of the same checksum are calculated. The first (stack
190894  ** variable cksum2) based on entries extracted from the full-text index
190895  ** while doing a linear scan of each individual index in turn.
190896  **
190897  ** As each term visited by the linear scans, a separate query for the
190898  ** same term is performed. cksum3 is calculated based on the entries
190899  ** extracted by these queries.
190900  */
190901  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
190902      fts5MultiIterEof(p, pIter)==0;
190903      fts5MultiIterNext(p, pIter, 0, 0)
190904  ){
190905    int n;                      /* Size of term in bytes */
190906    i64 iPos = 0;               /* Position read from poslist */
190907    int iOff = 0;               /* Offset within poslist */
190908    i64 iRowid = fts5MultiIterRowid(pIter);
190909    char *z = (char*)fts5MultiIterTerm(pIter, &n);
190910
190911    /* If this is a new term, query for it. Update cksum3 with the results. */
190912    fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
190913
190914    if( eDetail==FTS5_DETAIL_NONE ){
190915      if( 0==fts5MultiIterIsEmpty(p, pIter) ){
190916        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
190917      }
190918    }else{
190919      poslist.n = 0;
190920      fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
190921      while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
190922        int iCol = FTS5_POS2COLUMN(iPos);
190923        int iTokOff = FTS5_POS2OFFSET(iPos);
190924        cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
190925      }
190926    }
190927  }
190928  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
190929
190930  fts5MultiIterFree(pIter);
190931  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
190932
190933  fts5StructureRelease(pStruct);
190934#ifdef SQLITE_DEBUG
190935  fts5BufferFree(&term);
190936#endif
190937  fts5BufferFree(&poslist);
190938  return fts5IndexReturn(p);
190939}
190940
190941/*************************************************************************
190942**************************************************************************
190943** Below this point is the implementation of the fts5_decode() scalar
190944** function only.
190945*/
190946
190947/*
190948** Decode a segment-data rowid from the %_data table. This function is
190949** the opposite of macro FTS5_SEGMENT_ROWID().
190950*/
190951static void fts5DecodeRowid(
190952  i64 iRowid,                     /* Rowid from %_data table */
190953  int *piSegid,                   /* OUT: Segment id */
190954  int *pbDlidx,                   /* OUT: Dlidx flag */
190955  int *piHeight,                  /* OUT: Height */
190956  int *piPgno                     /* OUT: Page number */
190957){
190958  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
190959  iRowid >>= FTS5_DATA_PAGE_B;
190960
190961  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
190962  iRowid >>= FTS5_DATA_HEIGHT_B;
190963
190964  *pbDlidx = (int)(iRowid & 0x0001);
190965  iRowid >>= FTS5_DATA_DLI_B;
190966
190967  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
190968}
190969
190970static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
190971  int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
190972  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
190973
190974  if( iSegid==0 ){
190975    if( iKey==FTS5_AVERAGES_ROWID ){
190976      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
190977    }else{
190978      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
190979    }
190980  }
190981  else{
190982    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
190983        bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
190984    );
190985  }
190986}
190987
190988static void fts5DebugStructure(
190989  int *pRc,                       /* IN/OUT: error code */
190990  Fts5Buffer *pBuf,
190991  Fts5Structure *p
190992){
190993  int iLvl, iSeg;                 /* Iterate through levels, segments */
190994
190995  for(iLvl=0; iLvl<p->nLevel; iLvl++){
190996    Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
190997    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
190998        " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
190999    );
191000    for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
191001      Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
191002      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
191003          pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
191004      );
191005    }
191006    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
191007  }
191008}
191009
191010/*
191011** This is part of the fts5_decode() debugging aid.
191012**
191013** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
191014** function appends a human-readable representation of the same object
191015** to the buffer passed as the second argument.
191016*/
191017static void fts5DecodeStructure(
191018  int *pRc,                       /* IN/OUT: error code */
191019  Fts5Buffer *pBuf,
191020  const u8 *pBlob, int nBlob
191021){
191022  int rc;                         /* Return code */
191023  Fts5Structure *p = 0;           /* Decoded structure object */
191024
191025  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
191026  if( rc!=SQLITE_OK ){
191027    *pRc = rc;
191028    return;
191029  }
191030
191031  fts5DebugStructure(pRc, pBuf, p);
191032  fts5StructureRelease(p);
191033}
191034
191035/*
191036** This is part of the fts5_decode() debugging aid.
191037**
191038** Arguments pBlob/nBlob contain an "averages" record. This function
191039** appends a human-readable representation of record to the buffer passed
191040** as the second argument.
191041*/
191042static void fts5DecodeAverages(
191043  int *pRc,                       /* IN/OUT: error code */
191044  Fts5Buffer *pBuf,
191045  const u8 *pBlob, int nBlob
191046){
191047  int i = 0;
191048  const char *zSpace = "";
191049
191050  while( i<nBlob ){
191051    u64 iVal;
191052    i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
191053    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
191054    zSpace = " ";
191055  }
191056}
191057
191058/*
191059** Buffer (a/n) is assumed to contain a list of serialized varints. Read
191060** each varint and append its string representation to buffer pBuf. Return
191061** after either the input buffer is exhausted or a 0 value is read.
191062**
191063** The return value is the number of bytes read from the input buffer.
191064*/
191065static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
191066  int iOff = 0;
191067  while( iOff<n ){
191068    int iVal;
191069    iOff += fts5GetVarint32(&a[iOff], iVal);
191070    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
191071  }
191072  return iOff;
191073}
191074
191075/*
191076** The start of buffer (a/n) contains the start of a doclist. The doclist
191077** may or may not finish within the buffer. This function appends a text
191078** representation of the part of the doclist that is present to buffer
191079** pBuf.
191080**
191081** The return value is the number of bytes read from the input buffer.
191082*/
191083static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
191084  i64 iDocid = 0;
191085  int iOff = 0;
191086
191087  if( n>0 ){
191088    iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
191089    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
191090  }
191091  while( iOff<n ){
191092    int nPos;
191093    int bDel;
191094    iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
191095    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
191096    iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
191097    if( iOff<n ){
191098      i64 iDelta;
191099      iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
191100      iDocid += iDelta;
191101      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
191102    }
191103  }
191104
191105  return iOff;
191106}
191107
191108/*
191109** This function is part of the fts5_decode() debugging function. It is
191110** only ever used with detail=none tables.
191111**
191112** Buffer (pData/nData) contains a doclist in the format used by detail=none
191113** tables. This function appends a human-readable version of that list to
191114** buffer pBuf.
191115**
191116** If *pRc is other than SQLITE_OK when this function is called, it is a
191117** no-op. If an OOM or other error occurs within this function, *pRc is
191118** set to an SQLite error code before returning. The final state of buffer
191119** pBuf is undefined in this case.
191120*/
191121static void fts5DecodeRowidList(
191122  int *pRc,                       /* IN/OUT: Error code */
191123  Fts5Buffer *pBuf,               /* Buffer to append text to */
191124  const u8 *pData, int nData      /* Data to decode list-of-rowids from */
191125){
191126  int i = 0;
191127  i64 iRowid = 0;
191128
191129  while( i<nData ){
191130    const char *zApp = "";
191131    u64 iVal;
191132    i += sqlite3Fts5GetVarint(&pData[i], &iVal);
191133    iRowid += iVal;
191134
191135    if( i<nData && pData[i]==0x00 ){
191136      i++;
191137      if( i<nData && pData[i]==0x00 ){
191138        i++;
191139        zApp = "+";
191140      }else{
191141        zApp = "*";
191142      }
191143    }
191144
191145    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
191146  }
191147}
191148
191149/*
191150** The implementation of user-defined scalar function fts5_decode().
191151*/
191152static void fts5DecodeFunction(
191153  sqlite3_context *pCtx,          /* Function call context */
191154  int nArg,                       /* Number of args (always 2) */
191155  sqlite3_value **apVal           /* Function arguments */
191156){
191157  i64 iRowid;                     /* Rowid for record being decoded */
191158  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
191159  const u8 *aBlob; int n;         /* Record to decode */
191160  u8 *a = 0;
191161  Fts5Buffer s;                   /* Build up text to return here */
191162  int rc = SQLITE_OK;             /* Return code */
191163  int nSpace = 0;
191164  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
191165
191166  assert( nArg==2 );
191167  UNUSED_PARAM(nArg);
191168  memset(&s, 0, sizeof(Fts5Buffer));
191169  iRowid = sqlite3_value_int64(apVal[0]);
191170
191171  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
191172  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
191173  ** buffer overreads even if the record is corrupt.  */
191174  n = sqlite3_value_bytes(apVal[1]);
191175  aBlob = sqlite3_value_blob(apVal[1]);
191176  nSpace = n + FTS5_DATA_ZERO_PADDING;
191177  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
191178  if( a==0 ) goto decode_out;
191179  memcpy(a, aBlob, n);
191180
191181
191182  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
191183
191184  fts5DebugRowid(&rc, &s, iRowid);
191185  if( bDlidx ){
191186    Fts5Data dlidx;
191187    Fts5DlidxLvl lvl;
191188
191189    dlidx.p = a;
191190    dlidx.nn = n;
191191
191192    memset(&lvl, 0, sizeof(Fts5DlidxLvl));
191193    lvl.pData = &dlidx;
191194    lvl.iLeafPgno = iPgno;
191195
191196    for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
191197      sqlite3Fts5BufferAppendPrintf(&rc, &s,
191198          " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
191199      );
191200    }
191201  }else if( iSegid==0 ){
191202    if( iRowid==FTS5_AVERAGES_ROWID ){
191203      fts5DecodeAverages(&rc, &s, a, n);
191204    }else{
191205      fts5DecodeStructure(&rc, &s, a, n);
191206    }
191207  }else if( eDetailNone ){
191208    Fts5Buffer term;              /* Current term read from page */
191209    int szLeaf;
191210    int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
191211    int iTermOff;
191212    int nKeep = 0;
191213    int iOff;
191214
191215    memset(&term, 0, sizeof(Fts5Buffer));
191216
191217    /* Decode any entries that occur before the first term. */
191218    if( szLeaf<n ){
191219      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
191220    }else{
191221      iTermOff = szLeaf;
191222    }
191223    fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
191224
191225    iOff = iTermOff;
191226    while( iOff<szLeaf ){
191227      int nAppend;
191228
191229      /* Read the term data for the next term*/
191230      iOff += fts5GetVarint32(&a[iOff], nAppend);
191231      term.n = nKeep;
191232      fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
191233      sqlite3Fts5BufferAppendPrintf(
191234          &rc, &s, " term=%.*s", term.n, (const char*)term.p
191235      );
191236      iOff += nAppend;
191237
191238      /* Figure out where the doclist for this term ends */
191239      if( iPgidxOff<n ){
191240        int nIncr;
191241        iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
191242        iTermOff += nIncr;
191243      }else{
191244        iTermOff = szLeaf;
191245      }
191246
191247      fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
191248      iOff = iTermOff;
191249      if( iOff<szLeaf ){
191250        iOff += fts5GetVarint32(&a[iOff], nKeep);
191251      }
191252    }
191253
191254    fts5BufferFree(&term);
191255  }else{
191256    Fts5Buffer term;              /* Current term read from page */
191257    int szLeaf;                   /* Offset of pgidx in a[] */
191258    int iPgidxOff;
191259    int iPgidxPrev = 0;           /* Previous value read from pgidx */
191260    int iTermOff = 0;
191261    int iRowidOff = 0;
191262    int iOff;
191263    int nDoclist;
191264
191265    memset(&term, 0, sizeof(Fts5Buffer));
191266
191267    if( n<4 ){
191268      sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
191269      goto decode_out;
191270    }else{
191271      iRowidOff = fts5GetU16(&a[0]);
191272      iPgidxOff = szLeaf = fts5GetU16(&a[2]);
191273      if( iPgidxOff<n ){
191274        fts5GetVarint32(&a[iPgidxOff], iTermOff);
191275      }
191276    }
191277
191278    /* Decode the position list tail at the start of the page */
191279    if( iRowidOff!=0 ){
191280      iOff = iRowidOff;
191281    }else if( iTermOff!=0 ){
191282      iOff = iTermOff;
191283    }else{
191284      iOff = szLeaf;
191285    }
191286    fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
191287
191288    /* Decode any more doclist data that appears on the page before the
191289    ** first term. */
191290    nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
191291    fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
191292
191293    while( iPgidxOff<n ){
191294      int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
191295      int nByte;                            /* Bytes of data */
191296      int iEnd;
191297
191298      iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
191299      iPgidxPrev += nByte;
191300      iOff = iPgidxPrev;
191301
191302      if( iPgidxOff<n ){
191303        fts5GetVarint32(&a[iPgidxOff], nByte);
191304        iEnd = iPgidxPrev + nByte;
191305      }else{
191306        iEnd = szLeaf;
191307      }
191308
191309      if( bFirst==0 ){
191310        iOff += fts5GetVarint32(&a[iOff], nByte);
191311        term.n = nByte;
191312      }
191313      iOff += fts5GetVarint32(&a[iOff], nByte);
191314      fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
191315      iOff += nByte;
191316
191317      sqlite3Fts5BufferAppendPrintf(
191318          &rc, &s, " term=%.*s", term.n, (const char*)term.p
191319      );
191320      iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
191321    }
191322
191323    fts5BufferFree(&term);
191324  }
191325
191326 decode_out:
191327  sqlite3_free(a);
191328  if( rc==SQLITE_OK ){
191329    sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
191330  }else{
191331    sqlite3_result_error_code(pCtx, rc);
191332  }
191333  fts5BufferFree(&s);
191334}
191335
191336/*
191337** The implementation of user-defined scalar function fts5_rowid().
191338*/
191339static void fts5RowidFunction(
191340  sqlite3_context *pCtx,          /* Function call context */
191341  int nArg,                       /* Number of args (always 2) */
191342  sqlite3_value **apVal           /* Function arguments */
191343){
191344  const char *zArg;
191345  if( nArg==0 ){
191346    sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
191347  }else{
191348    zArg = (const char*)sqlite3_value_text(apVal[0]);
191349    if( 0==sqlite3_stricmp(zArg, "segment") ){
191350      i64 iRowid;
191351      int segid, pgno;
191352      if( nArg!=3 ){
191353        sqlite3_result_error(pCtx,
191354            "should be: fts5_rowid('segment', segid, pgno))", -1
191355        );
191356      }else{
191357        segid = sqlite3_value_int(apVal[1]);
191358        pgno = sqlite3_value_int(apVal[2]);
191359        iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
191360        sqlite3_result_int64(pCtx, iRowid);
191361      }
191362    }else{
191363      sqlite3_result_error(pCtx,
191364        "first arg to fts5_rowid() must be 'segment'" , -1
191365      );
191366    }
191367  }
191368}
191369
191370/*
191371** This is called as part of registering the FTS5 module with database
191372** connection db. It registers several user-defined scalar functions useful
191373** with FTS5.
191374**
191375** If successful, SQLITE_OK is returned. If an error occurs, some other
191376** SQLite error code is returned instead.
191377*/
191378static int sqlite3Fts5IndexInit(sqlite3 *db){
191379  int rc = sqlite3_create_function(
191380      db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
191381  );
191382
191383  if( rc==SQLITE_OK ){
191384    rc = sqlite3_create_function(
191385        db, "fts5_decode_none", 2,
191386        SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
191387    );
191388  }
191389
191390  if( rc==SQLITE_OK ){
191391    rc = sqlite3_create_function(
191392        db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
191393    );
191394  }
191395  return rc;
191396}
191397
191398
191399static int sqlite3Fts5IndexReset(Fts5Index *p){
191400  assert( p->pStruct==0 || p->iStructVersion!=0 );
191401  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
191402    fts5StructureInvalidate(p);
191403  }
191404  return fts5IndexReturn(p);
191405}
191406
191407/*
191408** 2014 Jun 09
191409**
191410** The author disclaims copyright to this source code.  In place of
191411** a legal notice, here is a blessing:
191412**
191413**    May you do good and not evil.
191414**    May you find forgiveness for yourself and forgive others.
191415**    May you share freely, never taking more than you give.
191416**
191417******************************************************************************
191418**
191419** This is an SQLite module implementing full-text search.
191420*/
191421
191422
191423/* #include "fts5Int.h" */
191424
191425/*
191426** This variable is set to false when running tests for which the on disk
191427** structures should not be corrupt. Otherwise, true. If it is false, extra
191428** assert() conditions in the fts5 code are activated - conditions that are
191429** only true if it is guaranteed that the fts5 database is not corrupt.
191430*/
191431SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
191432
191433
191434typedef struct Fts5Auxdata Fts5Auxdata;
191435typedef struct Fts5Auxiliary Fts5Auxiliary;
191436typedef struct Fts5Cursor Fts5Cursor;
191437typedef struct Fts5Sorter Fts5Sorter;
191438typedef struct Fts5Table Fts5Table;
191439typedef struct Fts5TokenizerModule Fts5TokenizerModule;
191440
191441/*
191442** NOTES ON TRANSACTIONS:
191443**
191444** SQLite invokes the following virtual table methods as transactions are
191445** opened and closed by the user:
191446**
191447**     xBegin():    Start of a new transaction.
191448**     xSync():     Initial part of two-phase commit.
191449**     xCommit():   Final part of two-phase commit.
191450**     xRollback(): Rollback the transaction.
191451**
191452** Anything that is required as part of a commit that may fail is performed
191453** in the xSync() callback. Current versions of SQLite ignore any errors
191454** returned by xCommit().
191455**
191456** And as sub-transactions are opened/closed:
191457**
191458**     xSavepoint(int S):  Open savepoint S.
191459**     xRelease(int S):    Commit and close savepoint S.
191460**     xRollbackTo(int S): Rollback to start of savepoint S.
191461**
191462** During a write-transaction the fts5_index.c module may cache some data
191463** in-memory. It is flushed to disk whenever xSync(), xRelease() or
191464** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
191465** is called.
191466**
191467** Additionally, if SQLITE_DEBUG is defined, an instance of the following
191468** structure is used to record the current transaction state. This information
191469** is not required, but it is used in the assert() statements executed by
191470** function fts5CheckTransactionState() (see below).
191471*/
191472struct Fts5TransactionState {
191473  int eState;                     /* 0==closed, 1==open, 2==synced */
191474  int iSavepoint;                 /* Number of open savepoints (0 -> none) */
191475};
191476
191477/*
191478** A single object of this type is allocated when the FTS5 module is
191479** registered with a database handle. It is used to store pointers to
191480** all registered FTS5 extensions - tokenizers and auxiliary functions.
191481*/
191482struct Fts5Global {
191483  fts5_api api;                   /* User visible part of object (see fts5.h) */
191484  sqlite3 *db;                    /* Associated database connection */
191485  i64 iNextId;                    /* Used to allocate unique cursor ids */
191486  Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
191487  Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
191488  Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
191489  Fts5Cursor *pCsr;               /* First in list of all open cursors */
191490};
191491
191492/*
191493** Each auxiliary function registered with the FTS5 module is represented
191494** by an object of the following type. All such objects are stored as part
191495** of the Fts5Global.pAux list.
191496*/
191497struct Fts5Auxiliary {
191498  Fts5Global *pGlobal;            /* Global context for this function */
191499  char *zFunc;                    /* Function name (nul-terminated) */
191500  void *pUserData;                /* User-data pointer */
191501  fts5_extension_function xFunc;  /* Callback function */
191502  void (*xDestroy)(void*);        /* Destructor function */
191503  Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
191504};
191505
191506/*
191507** Each tokenizer module registered with the FTS5 module is represented
191508** by an object of the following type. All such objects are stored as part
191509** of the Fts5Global.pTok list.
191510*/
191511struct Fts5TokenizerModule {
191512  char *zName;                    /* Name of tokenizer */
191513  void *pUserData;                /* User pointer passed to xCreate() */
191514  fts5_tokenizer x;               /* Tokenizer functions */
191515  void (*xDestroy)(void*);        /* Destructor function */
191516  Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
191517};
191518
191519/*
191520** Virtual-table object.
191521*/
191522struct Fts5Table {
191523  sqlite3_vtab base;              /* Base class used by SQLite core */
191524  Fts5Config *pConfig;            /* Virtual table configuration */
191525  Fts5Index *pIndex;              /* Full-text index */
191526  Fts5Storage *pStorage;          /* Document store */
191527  Fts5Global *pGlobal;            /* Global (connection wide) data */
191528  Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
191529#ifdef SQLITE_DEBUG
191530  struct Fts5TransactionState ts;
191531#endif
191532};
191533
191534struct Fts5MatchPhrase {
191535  Fts5Buffer *pPoslist;           /* Pointer to current poslist */
191536  int nTerm;                      /* Size of phrase in terms */
191537};
191538
191539/*
191540** pStmt:
191541**   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
191542**
191543** aIdx[]:
191544**   There is one entry in the aIdx[] array for each phrase in the query,
191545**   the value of which is the offset within aPoslist[] following the last
191546**   byte of the position list for the corresponding phrase.
191547*/
191548struct Fts5Sorter {
191549  sqlite3_stmt *pStmt;
191550  i64 iRowid;                     /* Current rowid */
191551  const u8 *aPoslist;             /* Position lists for current row */
191552  int nIdx;                       /* Number of entries in aIdx[] */
191553  int aIdx[1];                    /* Offsets into aPoslist for current row */
191554};
191555
191556
191557/*
191558** Virtual-table cursor object.
191559**
191560** iSpecial:
191561**   If this is a 'special' query (refer to function fts5SpecialMatch()),
191562**   then this variable contains the result of the query.
191563**
191564** iFirstRowid, iLastRowid:
191565**   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
191566**   cursor iterates in ascending order of rowids, iFirstRowid is the lower
191567**   limit of rowids to return, and iLastRowid the upper. In other words, the
191568**   WHERE clause in the user's query might have been:
191569**
191570**       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
191571**
191572**   If the cursor iterates in descending order of rowid, iFirstRowid
191573**   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
191574**   the lower.
191575*/
191576struct Fts5Cursor {
191577  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
191578  Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
191579  int *aColumnSize;               /* Values for xColumnSize() */
191580  i64 iCsrId;                     /* Cursor id */
191581
191582  /* Zero from this point onwards on cursor reset */
191583  int ePlan;                      /* FTS5_PLAN_XXX value */
191584  int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
191585  i64 iFirstRowid;                /* Return no rowids earlier than this */
191586  i64 iLastRowid;                 /* Return no rowids later than this */
191587  sqlite3_stmt *pStmt;            /* Statement used to read %_content */
191588  Fts5Expr *pExpr;                /* Expression for MATCH queries */
191589  Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
191590  int csrflags;                   /* Mask of cursor flags (see below) */
191591  i64 iSpecial;                   /* Result of special query */
191592
191593  /* "rank" function. Populated on demand from vtab.xColumn(). */
191594  char *zRank;                    /* Custom rank function */
191595  char *zRankArgs;                /* Custom rank function args */
191596  Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
191597  int nRankArg;                   /* Number of trailing arguments for rank() */
191598  sqlite3_value **apRankArg;      /* Array of trailing arguments */
191599  sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
191600
191601  /* Auxiliary data storage */
191602  Fts5Auxiliary *pAux;            /* Currently executing extension function */
191603  Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
191604
191605  /* Cache used by auxiliary functions xInst() and xInstCount() */
191606  Fts5PoslistReader *aInstIter;   /* One for each phrase */
191607  int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
191608  int nInstCount;                 /* Number of phrase instances */
191609  int *aInst;                     /* 3 integers per phrase instance */
191610};
191611
191612/*
191613** Bits that make up the "idxNum" parameter passed indirectly by
191614** xBestIndex() to xFilter().
191615*/
191616#define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
191617#define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
191618#define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
191619#define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
191620#define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
191621
191622#define FTS5_BI_ORDER_RANK   0x0020
191623#define FTS5_BI_ORDER_ROWID  0x0040
191624#define FTS5_BI_ORDER_DESC   0x0080
191625
191626/*
191627** Values for Fts5Cursor.csrflags
191628*/
191629#define FTS5CSR_EOF               0x01
191630#define FTS5CSR_REQUIRE_CONTENT   0x02
191631#define FTS5CSR_REQUIRE_DOCSIZE   0x04
191632#define FTS5CSR_REQUIRE_INST      0x08
191633#define FTS5CSR_FREE_ZRANK        0x10
191634#define FTS5CSR_REQUIRE_RESEEK    0x20
191635#define FTS5CSR_REQUIRE_POSLIST   0x40
191636
191637#define BitFlagAllTest(x,y) (((x) & (y))==(y))
191638#define BitFlagTest(x,y)    (((x) & (y))!=0)
191639
191640
191641/*
191642** Macros to Set(), Clear() and Test() cursor flags.
191643*/
191644#define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
191645#define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
191646#define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
191647
191648struct Fts5Auxdata {
191649  Fts5Auxiliary *pAux;            /* Extension to which this belongs */
191650  void *pPtr;                     /* Pointer value */
191651  void(*xDelete)(void*);          /* Destructor */
191652  Fts5Auxdata *pNext;             /* Next object in linked list */
191653};
191654
191655#ifdef SQLITE_DEBUG
191656#define FTS5_BEGIN      1
191657#define FTS5_SYNC       2
191658#define FTS5_COMMIT     3
191659#define FTS5_ROLLBACK   4
191660#define FTS5_SAVEPOINT  5
191661#define FTS5_RELEASE    6
191662#define FTS5_ROLLBACKTO 7
191663static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
191664  switch( op ){
191665    case FTS5_BEGIN:
191666      assert( p->ts.eState==0 );
191667      p->ts.eState = 1;
191668      p->ts.iSavepoint = -1;
191669      break;
191670
191671    case FTS5_SYNC:
191672      assert( p->ts.eState==1 );
191673      p->ts.eState = 2;
191674      break;
191675
191676    case FTS5_COMMIT:
191677      assert( p->ts.eState==2 );
191678      p->ts.eState = 0;
191679      break;
191680
191681    case FTS5_ROLLBACK:
191682      assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
191683      p->ts.eState = 0;
191684      break;
191685
191686    case FTS5_SAVEPOINT:
191687      assert( p->ts.eState==1 );
191688      assert( iSavepoint>=0 );
191689      assert( iSavepoint>p->ts.iSavepoint );
191690      p->ts.iSavepoint = iSavepoint;
191691      break;
191692
191693    case FTS5_RELEASE:
191694      assert( p->ts.eState==1 );
191695      assert( iSavepoint>=0 );
191696      assert( iSavepoint<=p->ts.iSavepoint );
191697      p->ts.iSavepoint = iSavepoint-1;
191698      break;
191699
191700    case FTS5_ROLLBACKTO:
191701      assert( p->ts.eState==1 );
191702      assert( iSavepoint>=0 );
191703      assert( iSavepoint<=p->ts.iSavepoint );
191704      p->ts.iSavepoint = iSavepoint;
191705      break;
191706  }
191707}
191708#else
191709# define fts5CheckTransactionState(x,y,z)
191710#endif
191711
191712/*
191713** Return true if pTab is a contentless table.
191714*/
191715static int fts5IsContentless(Fts5Table *pTab){
191716  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
191717}
191718
191719/*
191720** Delete a virtual table handle allocated by fts5InitVtab().
191721*/
191722static void fts5FreeVtab(Fts5Table *pTab){
191723  if( pTab ){
191724    sqlite3Fts5IndexClose(pTab->pIndex);
191725    sqlite3Fts5StorageClose(pTab->pStorage);
191726    sqlite3Fts5ConfigFree(pTab->pConfig);
191727    sqlite3_free(pTab);
191728  }
191729}
191730
191731/*
191732** The xDisconnect() virtual table method.
191733*/
191734static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
191735  fts5FreeVtab((Fts5Table*)pVtab);
191736  return SQLITE_OK;
191737}
191738
191739/*
191740** The xDestroy() virtual table method.
191741*/
191742static int fts5DestroyMethod(sqlite3_vtab *pVtab){
191743  Fts5Table *pTab = (Fts5Table*)pVtab;
191744  int rc = sqlite3Fts5DropAll(pTab->pConfig);
191745  if( rc==SQLITE_OK ){
191746    fts5FreeVtab((Fts5Table*)pVtab);
191747  }
191748  return rc;
191749}
191750
191751/*
191752** This function is the implementation of both the xConnect and xCreate
191753** methods of the FTS3 virtual table.
191754**
191755** The argv[] array contains the following:
191756**
191757**   argv[0]   -> module name  ("fts5")
191758**   argv[1]   -> database name
191759**   argv[2]   -> table name
191760**   argv[...] -> "column name" and other module argument fields.
191761*/
191762static int fts5InitVtab(
191763  int bCreate,                    /* True for xCreate, false for xConnect */
191764  sqlite3 *db,                    /* The SQLite database connection */
191765  void *pAux,                     /* Hash table containing tokenizers */
191766  int argc,                       /* Number of elements in argv array */
191767  const char * const *argv,       /* xCreate/xConnect argument array */
191768  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
191769  char **pzErr                    /* Write any error message here */
191770){
191771  Fts5Global *pGlobal = (Fts5Global*)pAux;
191772  const char **azConfig = (const char**)argv;
191773  int rc = SQLITE_OK;             /* Return code */
191774  Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
191775  Fts5Table *pTab = 0;            /* New virtual table object */
191776
191777  /* Allocate the new vtab object and parse the configuration */
191778  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
191779  if( rc==SQLITE_OK ){
191780    rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
191781    assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
191782  }
191783  if( rc==SQLITE_OK ){
191784    pTab->pConfig = pConfig;
191785    pTab->pGlobal = pGlobal;
191786  }
191787
191788  /* Open the index sub-system */
191789  if( rc==SQLITE_OK ){
191790    rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
191791  }
191792
191793  /* Open the storage sub-system */
191794  if( rc==SQLITE_OK ){
191795    rc = sqlite3Fts5StorageOpen(
191796        pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
191797    );
191798  }
191799
191800  /* Call sqlite3_declare_vtab() */
191801  if( rc==SQLITE_OK ){
191802    rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
191803  }
191804
191805  /* Load the initial configuration */
191806  if( rc==SQLITE_OK ){
191807    assert( pConfig->pzErrmsg==0 );
191808    pConfig->pzErrmsg = pzErr;
191809    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
191810    sqlite3Fts5IndexRollback(pTab->pIndex);
191811    pConfig->pzErrmsg = 0;
191812  }
191813
191814  if( rc!=SQLITE_OK ){
191815    fts5FreeVtab(pTab);
191816    pTab = 0;
191817  }else if( bCreate ){
191818    fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
191819  }
191820  *ppVTab = (sqlite3_vtab*)pTab;
191821  return rc;
191822}
191823
191824/*
191825** The xConnect() and xCreate() methods for the virtual table. All the
191826** work is done in function fts5InitVtab().
191827*/
191828static int fts5ConnectMethod(
191829  sqlite3 *db,                    /* Database connection */
191830  void *pAux,                     /* Pointer to tokenizer hash table */
191831  int argc,                       /* Number of elements in argv array */
191832  const char * const *argv,       /* xCreate/xConnect argument array */
191833  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
191834  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
191835){
191836  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
191837}
191838static int fts5CreateMethod(
191839  sqlite3 *db,                    /* Database connection */
191840  void *pAux,                     /* Pointer to tokenizer hash table */
191841  int argc,                       /* Number of elements in argv array */
191842  const char * const *argv,       /* xCreate/xConnect argument array */
191843  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
191844  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
191845){
191846  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
191847}
191848
191849/*
191850** The different query plans.
191851*/
191852#define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
191853#define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
191854#define FTS5_PLAN_SPECIAL        3       /* An internal query */
191855#define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
191856#define FTS5_PLAN_SCAN           5       /* No usable constraint */
191857#define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
191858
191859/*
191860** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
191861** extension is currently being used by a version of SQLite too old to
191862** support index-info flags. In that case this function is a no-op.
191863*/
191864static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
191865#if SQLITE_VERSION_NUMBER>=3008012
191866#ifndef SQLITE_CORE
191867  if( sqlite3_libversion_number()>=3008012 )
191868#endif
191869  {
191870    pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
191871  }
191872#endif
191873}
191874
191875/*
191876** Implementation of the xBestIndex method for FTS5 tables. Within the
191877** WHERE constraint, it searches for the following:
191878**
191879**   1. A MATCH constraint against the special column.
191880**   2. A MATCH constraint against the "rank" column.
191881**   3. An == constraint against the rowid column.
191882**   4. A < or <= constraint against the rowid column.
191883**   5. A > or >= constraint against the rowid column.
191884**
191885** Within the ORDER BY, either:
191886**
191887**   5. ORDER BY rank [ASC|DESC]
191888**   6. ORDER BY rowid [ASC|DESC]
191889**
191890** Costs are assigned as follows:
191891**
191892**  a) If an unusable MATCH operator is present in the WHERE clause, the
191893**     cost is unconditionally set to 1e50 (a really big number).
191894**
191895**  a) If a MATCH operator is present, the cost depends on the other
191896**     constraints also present. As follows:
191897**
191898**       * No other constraints:         cost=1000.0
191899**       * One rowid range constraint:   cost=750.0
191900**       * Both rowid range constraints: cost=500.0
191901**       * An == rowid constraint:       cost=100.0
191902**
191903**  b) Otherwise, if there is no MATCH:
191904**
191905**       * No other constraints:         cost=1000000.0
191906**       * One rowid range constraint:   cost=750000.0
191907**       * Both rowid range constraints: cost=250000.0
191908**       * An == rowid constraint:       cost=10.0
191909**
191910** Costs are not modified by the ORDER BY clause.
191911*/
191912static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
191913  Fts5Table *pTab = (Fts5Table*)pVTab;
191914  Fts5Config *pConfig = pTab->pConfig;
191915  int idxFlags = 0;               /* Parameter passed through to xFilter() */
191916  int bHasMatch;
191917  int iNext;
191918  int i;
191919
191920  struct Constraint {
191921    int op;                       /* Mask against sqlite3_index_constraint.op */
191922    int fts5op;                   /* FTS5 mask for idxFlags */
191923    int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
191924    int omit;                     /* True to omit this if found */
191925    int iConsIndex;               /* Index in pInfo->aConstraint[] */
191926  } aConstraint[] = {
191927    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
191928                                    FTS5_BI_MATCH,    1, 1, -1},
191929    {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
191930                                    FTS5_BI_RANK,     2, 1, -1},
191931    {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
191932    {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
191933                                    FTS5_BI_ROWID_LE, 0, 0, -1},
191934    {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
191935                                    FTS5_BI_ROWID_GE, 0, 0, -1},
191936  };
191937
191938  int aColMap[3];
191939  aColMap[0] = -1;
191940  aColMap[1] = pConfig->nCol;
191941  aColMap[2] = pConfig->nCol+1;
191942
191943  /* Set idxFlags flags for all WHERE clause terms that will be used. */
191944  for(i=0; i<pInfo->nConstraint; i++){
191945    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
191946    int j;
191947    for(j=0; j<ArraySize(aConstraint); j++){
191948      struct Constraint *pC = &aConstraint[j];
191949      if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
191950        if( p->usable ){
191951          pC->iConsIndex = i;
191952          idxFlags |= pC->fts5op;
191953        }else if( j==0 ){
191954          /* As there exists an unusable MATCH constraint this is an
191955          ** unusable plan. Set a prohibitively high cost. */
191956          pInfo->estimatedCost = 1e50;
191957          return SQLITE_OK;
191958        }
191959      }
191960    }
191961  }
191962
191963  /* Set idxFlags flags for the ORDER BY clause */
191964  if( pInfo->nOrderBy==1 ){
191965    int iSort = pInfo->aOrderBy[0].iColumn;
191966    if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
191967      idxFlags |= FTS5_BI_ORDER_RANK;
191968    }else if( iSort==-1 ){
191969      idxFlags |= FTS5_BI_ORDER_ROWID;
191970    }
191971    if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
191972      pInfo->orderByConsumed = 1;
191973      if( pInfo->aOrderBy[0].desc ){
191974        idxFlags |= FTS5_BI_ORDER_DESC;
191975      }
191976    }
191977  }
191978
191979  /* Calculate the estimated cost based on the flags set in idxFlags. */
191980  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
191981  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
191982    pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
191983    if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
191984  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
191985    pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
191986  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
191987    pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
191988  }else{
191989    pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
191990  }
191991
191992  /* Assign argvIndex values to each constraint in use. */
191993  iNext = 1;
191994  for(i=0; i<ArraySize(aConstraint); i++){
191995    struct Constraint *pC = &aConstraint[i];
191996    if( pC->iConsIndex>=0 ){
191997      pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
191998      pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
191999    }
192000  }
192001
192002  pInfo->idxNum = idxFlags;
192003  return SQLITE_OK;
192004}
192005
192006static int fts5NewTransaction(Fts5Table *pTab){
192007  Fts5Cursor *pCsr;
192008  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
192009    if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
192010  }
192011  return sqlite3Fts5StorageReset(pTab->pStorage);
192012}
192013
192014/*
192015** Implementation of xOpen method.
192016*/
192017static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
192018  Fts5Table *pTab = (Fts5Table*)pVTab;
192019  Fts5Config *pConfig = pTab->pConfig;
192020  Fts5Cursor *pCsr = 0;           /* New cursor object */
192021  int nByte;                      /* Bytes of space to allocate */
192022  int rc;                         /* Return code */
192023
192024  rc = fts5NewTransaction(pTab);
192025  if( rc==SQLITE_OK ){
192026    nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
192027    pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
192028    if( pCsr ){
192029      Fts5Global *pGlobal = pTab->pGlobal;
192030      memset(pCsr, 0, nByte);
192031      pCsr->aColumnSize = (int*)&pCsr[1];
192032      pCsr->pNext = pGlobal->pCsr;
192033      pGlobal->pCsr = pCsr;
192034      pCsr->iCsrId = ++pGlobal->iNextId;
192035    }else{
192036      rc = SQLITE_NOMEM;
192037    }
192038  }
192039  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
192040  return rc;
192041}
192042
192043static int fts5StmtType(Fts5Cursor *pCsr){
192044  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
192045    return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
192046  }
192047  return FTS5_STMT_LOOKUP;
192048}
192049
192050/*
192051** This function is called after the cursor passed as the only argument
192052** is moved to point at a different row. It clears all cached data
192053** specific to the previous row stored by the cursor object.
192054*/
192055static void fts5CsrNewrow(Fts5Cursor *pCsr){
192056  CsrFlagSet(pCsr,
192057      FTS5CSR_REQUIRE_CONTENT
192058    | FTS5CSR_REQUIRE_DOCSIZE
192059    | FTS5CSR_REQUIRE_INST
192060    | FTS5CSR_REQUIRE_POSLIST
192061  );
192062}
192063
192064static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
192065  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192066  Fts5Auxdata *pData;
192067  Fts5Auxdata *pNext;
192068
192069  sqlite3_free(pCsr->aInstIter);
192070  sqlite3_free(pCsr->aInst);
192071  if( pCsr->pStmt ){
192072    int eStmt = fts5StmtType(pCsr);
192073    sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
192074  }
192075  if( pCsr->pSorter ){
192076    Fts5Sorter *pSorter = pCsr->pSorter;
192077    sqlite3_finalize(pSorter->pStmt);
192078    sqlite3_free(pSorter);
192079  }
192080
192081  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
192082    sqlite3Fts5ExprFree(pCsr->pExpr);
192083  }
192084
192085  for(pData=pCsr->pAuxdata; pData; pData=pNext){
192086    pNext = pData->pNext;
192087    if( pData->xDelete ) pData->xDelete(pData->pPtr);
192088    sqlite3_free(pData);
192089  }
192090
192091  sqlite3_finalize(pCsr->pRankArgStmt);
192092  sqlite3_free(pCsr->apRankArg);
192093
192094  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
192095    sqlite3_free(pCsr->zRank);
192096    sqlite3_free(pCsr->zRankArgs);
192097  }
192098
192099  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
192100}
192101
192102
192103/*
192104** Close the cursor.  For additional information see the documentation
192105** on the xClose method of the virtual table interface.
192106*/
192107static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
192108  if( pCursor ){
192109    Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192110    Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192111    Fts5Cursor **pp;
192112
192113    fts5FreeCursorComponents(pCsr);
192114    /* Remove the cursor from the Fts5Global.pCsr list */
192115    for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
192116    *pp = pCsr->pNext;
192117
192118    sqlite3_free(pCsr);
192119  }
192120  return SQLITE_OK;
192121}
192122
192123static int fts5SorterNext(Fts5Cursor *pCsr){
192124  Fts5Sorter *pSorter = pCsr->pSorter;
192125  int rc;
192126
192127  rc = sqlite3_step(pSorter->pStmt);
192128  if( rc==SQLITE_DONE ){
192129    rc = SQLITE_OK;
192130    CsrFlagSet(pCsr, FTS5CSR_EOF);
192131  }else if( rc==SQLITE_ROW ){
192132    const u8 *a;
192133    const u8 *aBlob;
192134    int nBlob;
192135    int i;
192136    int iOff = 0;
192137    rc = SQLITE_OK;
192138
192139    pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
192140    nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
192141    aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
192142
192143    /* nBlob==0 in detail=none mode. */
192144    if( nBlob>0 ){
192145      for(i=0; i<(pSorter->nIdx-1); i++){
192146        int iVal;
192147        a += fts5GetVarint32(a, iVal);
192148        iOff += iVal;
192149        pSorter->aIdx[i] = iOff;
192150      }
192151      pSorter->aIdx[i] = &aBlob[nBlob] - a;
192152      pSorter->aPoslist = a;
192153    }
192154
192155    fts5CsrNewrow(pCsr);
192156  }
192157
192158  return rc;
192159}
192160
192161
192162/*
192163** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
192164** open on table pTab.
192165*/
192166static void fts5TripCursors(Fts5Table *pTab){
192167  Fts5Cursor *pCsr;
192168  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
192169    if( pCsr->ePlan==FTS5_PLAN_MATCH
192170     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
192171    ){
192172      CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
192173    }
192174  }
192175}
192176
192177/*
192178** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
192179** argument, close and reopen all Fts5IndexIter iterators that the cursor
192180** is using. Then attempt to move the cursor to a rowid equal to or laster
192181** (in the cursors sort order - ASC or DESC) than the current rowid.
192182**
192183** If the new rowid is not equal to the old, set output parameter *pbSkip
192184** to 1 before returning. Otherwise, leave it unchanged.
192185**
192186** Return SQLITE_OK if successful or if no reseek was required, or an
192187** error code if an error occurred.
192188*/
192189static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
192190  int rc = SQLITE_OK;
192191  assert( *pbSkip==0 );
192192  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
192193    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192194    int bDesc = pCsr->bDesc;
192195    i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
192196
192197    rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
192198    if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
192199      *pbSkip = 1;
192200    }
192201
192202    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
192203    fts5CsrNewrow(pCsr);
192204    if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
192205      CsrFlagSet(pCsr, FTS5CSR_EOF);
192206      *pbSkip = 1;
192207    }
192208  }
192209  return rc;
192210}
192211
192212
192213/*
192214** Advance the cursor to the next row in the table that matches the
192215** search criteria.
192216**
192217** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
192218** even if we reach end-of-file.  The fts5EofMethod() will be called
192219** subsequently to determine whether or not an EOF was hit.
192220*/
192221static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
192222  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192223  int rc;
192224
192225  assert( (pCsr->ePlan<3)==
192226          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
192227  );
192228  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
192229
192230  if( pCsr->ePlan<3 ){
192231    int bSkip = 0;
192232    if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
192233    rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
192234    CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
192235    fts5CsrNewrow(pCsr);
192236  }else{
192237    switch( pCsr->ePlan ){
192238      case FTS5_PLAN_SPECIAL: {
192239        CsrFlagSet(pCsr, FTS5CSR_EOF);
192240        rc = SQLITE_OK;
192241        break;
192242      }
192243
192244      case FTS5_PLAN_SORTED_MATCH: {
192245        rc = fts5SorterNext(pCsr);
192246        break;
192247      }
192248
192249      default:
192250        rc = sqlite3_step(pCsr->pStmt);
192251        if( rc!=SQLITE_ROW ){
192252          CsrFlagSet(pCsr, FTS5CSR_EOF);
192253          rc = sqlite3_reset(pCsr->pStmt);
192254        }else{
192255          rc = SQLITE_OK;
192256        }
192257        break;
192258    }
192259  }
192260
192261  return rc;
192262}
192263
192264
192265static int fts5PrepareStatement(
192266  sqlite3_stmt **ppStmt,
192267  Fts5Config *pConfig,
192268  const char *zFmt,
192269  ...
192270){
192271  sqlite3_stmt *pRet = 0;
192272  int rc;
192273  char *zSql;
192274  va_list ap;
192275
192276  va_start(ap, zFmt);
192277  zSql = sqlite3_vmprintf(zFmt, ap);
192278  if( zSql==0 ){
192279    rc = SQLITE_NOMEM;
192280  }else{
192281    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
192282    if( rc!=SQLITE_OK ){
192283      *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
192284    }
192285    sqlite3_free(zSql);
192286  }
192287
192288  va_end(ap);
192289  *ppStmt = pRet;
192290  return rc;
192291}
192292
192293static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
192294  Fts5Config *pConfig = pTab->pConfig;
192295  Fts5Sorter *pSorter;
192296  int nPhrase;
192297  int nByte;
192298  int rc;
192299  const char *zRank = pCsr->zRank;
192300  const char *zRankArgs = pCsr->zRankArgs;
192301
192302  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
192303  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
192304  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
192305  if( pSorter==0 ) return SQLITE_NOMEM;
192306  memset(pSorter, 0, nByte);
192307  pSorter->nIdx = nPhrase;
192308
192309  /* TODO: It would be better to have some system for reusing statement
192310  ** handles here, rather than preparing a new one for each query. But that
192311  ** is not possible as SQLite reference counts the virtual table objects.
192312  ** And since the statement required here reads from this very virtual
192313  ** table, saving it creates a circular reference.
192314  **
192315  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
192316  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
192317      "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
192318      pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
192319      (zRankArgs ? ", " : ""),
192320      (zRankArgs ? zRankArgs : ""),
192321      bDesc ? "DESC" : "ASC"
192322  );
192323
192324  pCsr->pSorter = pSorter;
192325  if( rc==SQLITE_OK ){
192326    assert( pTab->pSortCsr==0 );
192327    pTab->pSortCsr = pCsr;
192328    rc = fts5SorterNext(pCsr);
192329    pTab->pSortCsr = 0;
192330  }
192331
192332  if( rc!=SQLITE_OK ){
192333    sqlite3_finalize(pSorter->pStmt);
192334    sqlite3_free(pSorter);
192335    pCsr->pSorter = 0;
192336  }
192337
192338  return rc;
192339}
192340
192341static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
192342  int rc;
192343  Fts5Expr *pExpr = pCsr->pExpr;
192344  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
192345  if( sqlite3Fts5ExprEof(pExpr) ){
192346    CsrFlagSet(pCsr, FTS5CSR_EOF);
192347  }
192348  fts5CsrNewrow(pCsr);
192349  return rc;
192350}
192351
192352/*
192353** Process a "special" query. A special query is identified as one with a
192354** MATCH expression that begins with a '*' character. The remainder of
192355** the text passed to the MATCH operator are used as  the special query
192356** parameters.
192357*/
192358static int fts5SpecialMatch(
192359  Fts5Table *pTab,
192360  Fts5Cursor *pCsr,
192361  const char *zQuery
192362){
192363  int rc = SQLITE_OK;             /* Return code */
192364  const char *z = zQuery;         /* Special query text */
192365  int n;                          /* Number of bytes in text at z */
192366
192367  while( z[0]==' ' ) z++;
192368  for(n=0; z[n] && z[n]!=' '; n++);
192369
192370  assert( pTab->base.zErrMsg==0 );
192371  pCsr->ePlan = FTS5_PLAN_SPECIAL;
192372
192373  if( 0==sqlite3_strnicmp("reads", z, n) ){
192374    pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
192375  }
192376  else if( 0==sqlite3_strnicmp("id", z, n) ){
192377    pCsr->iSpecial = pCsr->iCsrId;
192378  }
192379  else{
192380    /* An unrecognized directive. Return an error message. */
192381    pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
192382    rc = SQLITE_ERROR;
192383  }
192384
192385  return rc;
192386}
192387
192388/*
192389** Search for an auxiliary function named zName that can be used with table
192390** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
192391** structure. Otherwise, if no such function exists, return NULL.
192392*/
192393static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
192394  Fts5Auxiliary *pAux;
192395
192396  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
192397    if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
192398  }
192399
192400  /* No function of the specified name was found. Return 0. */
192401  return 0;
192402}
192403
192404
192405static int fts5FindRankFunction(Fts5Cursor *pCsr){
192406  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192407  Fts5Config *pConfig = pTab->pConfig;
192408  int rc = SQLITE_OK;
192409  Fts5Auxiliary *pAux = 0;
192410  const char *zRank = pCsr->zRank;
192411  const char *zRankArgs = pCsr->zRankArgs;
192412
192413  if( zRankArgs ){
192414    char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
192415    if( zSql ){
192416      sqlite3_stmt *pStmt = 0;
192417      rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
192418      sqlite3_free(zSql);
192419      assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
192420      if( rc==SQLITE_OK ){
192421        if( SQLITE_ROW==sqlite3_step(pStmt) ){
192422          int nByte;
192423          pCsr->nRankArg = sqlite3_column_count(pStmt);
192424          nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
192425          pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
192426          if( rc==SQLITE_OK ){
192427            int i;
192428            for(i=0; i<pCsr->nRankArg; i++){
192429              pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
192430            }
192431          }
192432          pCsr->pRankArgStmt = pStmt;
192433        }else{
192434          rc = sqlite3_finalize(pStmt);
192435          assert( rc!=SQLITE_OK );
192436        }
192437      }
192438    }
192439  }
192440
192441  if( rc==SQLITE_OK ){
192442    pAux = fts5FindAuxiliary(pTab, zRank);
192443    if( pAux==0 ){
192444      assert( pTab->base.zErrMsg==0 );
192445      pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
192446      rc = SQLITE_ERROR;
192447    }
192448  }
192449
192450  pCsr->pRank = pAux;
192451  return rc;
192452}
192453
192454
192455static int fts5CursorParseRank(
192456  Fts5Config *pConfig,
192457  Fts5Cursor *pCsr,
192458  sqlite3_value *pRank
192459){
192460  int rc = SQLITE_OK;
192461  if( pRank ){
192462    const char *z = (const char*)sqlite3_value_text(pRank);
192463    char *zRank = 0;
192464    char *zRankArgs = 0;
192465
192466    if( z==0 ){
192467      if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
192468    }else{
192469      rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
192470    }
192471    if( rc==SQLITE_OK ){
192472      pCsr->zRank = zRank;
192473      pCsr->zRankArgs = zRankArgs;
192474      CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
192475    }else if( rc==SQLITE_ERROR ){
192476      pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
192477          "parse error in rank function: %s", z
192478      );
192479    }
192480  }else{
192481    if( pConfig->zRank ){
192482      pCsr->zRank = (char*)pConfig->zRank;
192483      pCsr->zRankArgs = (char*)pConfig->zRankArgs;
192484    }else{
192485      pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
192486      pCsr->zRankArgs = 0;
192487    }
192488  }
192489  return rc;
192490}
192491
192492static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
192493  if( pVal ){
192494    int eType = sqlite3_value_numeric_type(pVal);
192495    if( eType==SQLITE_INTEGER ){
192496      return sqlite3_value_int64(pVal);
192497    }
192498  }
192499  return iDefault;
192500}
192501
192502/*
192503** This is the xFilter interface for the virtual table.  See
192504** the virtual table xFilter method documentation for additional
192505** information.
192506**
192507** There are three possible query strategies:
192508**
192509**   1. Full-text search using a MATCH operator.
192510**   2. A by-rowid lookup.
192511**   3. A full-table scan.
192512*/
192513static int fts5FilterMethod(
192514  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
192515  int idxNum,                     /* Strategy index */
192516  const char *zUnused,            /* Unused */
192517  int nVal,                       /* Number of elements in apVal */
192518  sqlite3_value **apVal           /* Arguments for the indexing scheme */
192519){
192520  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192521  Fts5Config *pConfig = pTab->pConfig;
192522  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192523  int rc = SQLITE_OK;             /* Error code */
192524  int iVal = 0;                   /* Counter for apVal[] */
192525  int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
192526  int bOrderByRank;               /* True if ORDER BY rank */
192527  sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
192528  sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
192529  sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
192530  sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
192531  sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
192532  char **pzErrmsg = pConfig->pzErrmsg;
192533
192534  UNUSED_PARAM(zUnused);
192535  UNUSED_PARAM(nVal);
192536
192537  if( pCsr->ePlan ){
192538    fts5FreeCursorComponents(pCsr);
192539    memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
192540  }
192541
192542  assert( pCsr->pStmt==0 );
192543  assert( pCsr->pExpr==0 );
192544  assert( pCsr->csrflags==0 );
192545  assert( pCsr->pRank==0 );
192546  assert( pCsr->zRank==0 );
192547  assert( pCsr->zRankArgs==0 );
192548
192549  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
192550  pConfig->pzErrmsg = &pTab->base.zErrMsg;
192551
192552  /* Decode the arguments passed through to this function.
192553  **
192554  ** Note: The following set of if(...) statements must be in the same
192555  ** order as the corresponding entries in the struct at the top of
192556  ** fts5BestIndexMethod().  */
192557  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
192558  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
192559  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
192560  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
192561  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
192562  assert( iVal==nVal );
192563  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
192564  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
192565
192566  /* Set the cursor upper and lower rowid limits. Only some strategies
192567  ** actually use them. This is ok, as the xBestIndex() method leaves the
192568  ** sqlite3_index_constraint.omit flag clear for range constraints
192569  ** on the rowid field.  */
192570  if( pRowidEq ){
192571    pRowidLe = pRowidGe = pRowidEq;
192572  }
192573  if( bDesc ){
192574    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
192575    pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
192576  }else{
192577    pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
192578    pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
192579  }
192580
192581  if( pTab->pSortCsr ){
192582    /* If pSortCsr is non-NULL, then this call is being made as part of
192583    ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
192584    ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
192585    ** return results to the user for this query. The current cursor
192586    ** (pCursor) is used to execute the query issued by function
192587    ** fts5CursorFirstSorted() above.  */
192588    assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
192589    assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
192590    assert( pCsr->iLastRowid==LARGEST_INT64 );
192591    assert( pCsr->iFirstRowid==SMALLEST_INT64 );
192592    pCsr->ePlan = FTS5_PLAN_SOURCE;
192593    pCsr->pExpr = pTab->pSortCsr->pExpr;
192594    rc = fts5CursorFirst(pTab, pCsr, bDesc);
192595  }else if( pMatch ){
192596    const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
192597    if( zExpr==0 ) zExpr = "";
192598
192599    rc = fts5CursorParseRank(pConfig, pCsr, pRank);
192600    if( rc==SQLITE_OK ){
192601      if( zExpr[0]=='*' ){
192602        /* The user has issued a query of the form "MATCH '*...'". This
192603        ** indicates that the MATCH expression is not a full text query,
192604        ** but a request for an internal parameter.  */
192605        rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
192606      }else{
192607        char **pzErr = &pTab->base.zErrMsg;
192608        rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
192609        if( rc==SQLITE_OK ){
192610          if( bOrderByRank ){
192611            pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
192612            rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
192613          }else{
192614            pCsr->ePlan = FTS5_PLAN_MATCH;
192615            rc = fts5CursorFirst(pTab, pCsr, bDesc);
192616          }
192617        }
192618      }
192619    }
192620  }else if( pConfig->zContent==0 ){
192621    *pConfig->pzErrmsg = sqlite3_mprintf(
192622        "%s: table does not support scanning", pConfig->zName
192623    );
192624    rc = SQLITE_ERROR;
192625  }else{
192626    /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
192627    ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
192628    pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
192629    rc = sqlite3Fts5StorageStmt(
192630        pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
192631    );
192632    if( rc==SQLITE_OK ){
192633      if( pCsr->ePlan==FTS5_PLAN_ROWID ){
192634        sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
192635      }else{
192636        sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
192637        sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
192638      }
192639      rc = fts5NextMethod(pCursor);
192640    }
192641  }
192642
192643  pConfig->pzErrmsg = pzErrmsg;
192644  return rc;
192645}
192646
192647/*
192648** This is the xEof method of the virtual table. SQLite calls this
192649** routine to find out if it has reached the end of a result set.
192650*/
192651static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
192652  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192653  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
192654}
192655
192656/*
192657** Return the rowid that the cursor currently points to.
192658*/
192659static i64 fts5CursorRowid(Fts5Cursor *pCsr){
192660  assert( pCsr->ePlan==FTS5_PLAN_MATCH
192661       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
192662       || pCsr->ePlan==FTS5_PLAN_SOURCE
192663  );
192664  if( pCsr->pSorter ){
192665    return pCsr->pSorter->iRowid;
192666  }else{
192667    return sqlite3Fts5ExprRowid(pCsr->pExpr);
192668  }
192669}
192670
192671/*
192672** This is the xRowid method. The SQLite core calls this routine to
192673** retrieve the rowid for the current row of the result set. fts5
192674** exposes %_content.rowid as the rowid for the virtual table. The
192675** rowid should be written to *pRowid.
192676*/
192677static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
192678  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192679  int ePlan = pCsr->ePlan;
192680
192681  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
192682  switch( ePlan ){
192683    case FTS5_PLAN_SPECIAL:
192684      *pRowid = 0;
192685      break;
192686
192687    case FTS5_PLAN_SOURCE:
192688    case FTS5_PLAN_MATCH:
192689    case FTS5_PLAN_SORTED_MATCH:
192690      *pRowid = fts5CursorRowid(pCsr);
192691      break;
192692
192693    default:
192694      *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
192695      break;
192696  }
192697
192698  return SQLITE_OK;
192699}
192700
192701/*
192702** If the cursor requires seeking (bSeekRequired flag is set), seek it.
192703** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
192704**
192705** If argument bErrormsg is true and an error occurs, an error message may
192706** be left in sqlite3_vtab.zErrMsg.
192707*/
192708static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
192709  int rc = SQLITE_OK;
192710
192711  /* If the cursor does not yet have a statement handle, obtain one now. */
192712  if( pCsr->pStmt==0 ){
192713    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192714    int eStmt = fts5StmtType(pCsr);
192715    rc = sqlite3Fts5StorageStmt(
192716        pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
192717    );
192718    assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
192719    assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
192720  }
192721
192722  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
192723    assert( pCsr->pExpr );
192724    sqlite3_reset(pCsr->pStmt);
192725    sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
192726    rc = sqlite3_step(pCsr->pStmt);
192727    if( rc==SQLITE_ROW ){
192728      rc = SQLITE_OK;
192729      CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
192730    }else{
192731      rc = sqlite3_reset(pCsr->pStmt);
192732      if( rc==SQLITE_OK ){
192733        rc = FTS5_CORRUPT;
192734      }
192735    }
192736  }
192737  return rc;
192738}
192739
192740static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
192741  va_list ap;                     /* ... printf arguments */
192742  va_start(ap, zFormat);
192743  assert( p->base.zErrMsg==0 );
192744  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
192745  va_end(ap);
192746}
192747
192748/*
192749** This function is called to handle an FTS INSERT command. In other words,
192750** an INSERT statement of the form:
192751**
192752**     INSERT INTO fts(fts) VALUES($pCmd)
192753**     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
192754**
192755** Argument pVal is the value assigned to column "fts" by the INSERT
192756** statement. This function returns SQLITE_OK if successful, or an SQLite
192757** error code if an error occurs.
192758**
192759** The commands implemented by this function are documented in the "Special
192760** INSERT Directives" section of the documentation. It should be updated if
192761** more commands are added to this function.
192762*/
192763static int fts5SpecialInsert(
192764  Fts5Table *pTab,                /* Fts5 table object */
192765  const char *zCmd,               /* Text inserted into table-name column */
192766  sqlite3_value *pVal             /* Value inserted into rank column */
192767){
192768  Fts5Config *pConfig = pTab->pConfig;
192769  int rc = SQLITE_OK;
192770  int bError = 0;
192771
192772  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
192773    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
192774      fts5SetVtabError(pTab,
192775          "'delete-all' may only be used with a "
192776          "contentless or external content fts5 table"
192777      );
192778      rc = SQLITE_ERROR;
192779    }else{
192780      rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
192781    }
192782  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
192783    if( pConfig->eContent==FTS5_CONTENT_NONE ){
192784      fts5SetVtabError(pTab,
192785          "'rebuild' may not be used with a contentless fts5 table"
192786      );
192787      rc = SQLITE_ERROR;
192788    }else{
192789      rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
192790    }
192791  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
192792    rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
192793  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
192794    int nMerge = sqlite3_value_int(pVal);
192795    rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
192796  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
192797    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
192798#ifdef SQLITE_DEBUG
192799  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
192800    pConfig->bPrefixIndex = sqlite3_value_int(pVal);
192801#endif
192802  }else{
192803    rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
192804    if( rc==SQLITE_OK ){
192805      rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
192806    }
192807    if( rc==SQLITE_OK ){
192808      if( bError ){
192809        rc = SQLITE_ERROR;
192810      }else{
192811        rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
192812      }
192813    }
192814  }
192815  return rc;
192816}
192817
192818static int fts5SpecialDelete(
192819  Fts5Table *pTab,
192820  sqlite3_value **apVal
192821){
192822  int rc = SQLITE_OK;
192823  int eType1 = sqlite3_value_type(apVal[1]);
192824  if( eType1==SQLITE_INTEGER ){
192825    sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
192826    rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
192827  }
192828  return rc;
192829}
192830
192831static void fts5StorageInsert(
192832  int *pRc,
192833  Fts5Table *pTab,
192834  sqlite3_value **apVal,
192835  i64 *piRowid
192836){
192837  int rc = *pRc;
192838  if( rc==SQLITE_OK ){
192839    rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
192840  }
192841  if( rc==SQLITE_OK ){
192842    rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
192843  }
192844  *pRc = rc;
192845}
192846
192847/*
192848** This function is the implementation of the xUpdate callback used by
192849** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
192850** inserted, updated or deleted.
192851**
192852** A delete specifies a single argument - the rowid of the row to remove.
192853**
192854** Update and insert operations pass:
192855**
192856**   1. The "old" rowid, or NULL.
192857**   2. The "new" rowid.
192858**   3. Values for each of the nCol matchable columns.
192859**   4. Values for the two hidden columns (<tablename> and "rank").
192860*/
192861static int fts5UpdateMethod(
192862  sqlite3_vtab *pVtab,            /* Virtual table handle */
192863  int nArg,                       /* Size of argument array */
192864  sqlite3_value **apVal,          /* Array of arguments */
192865  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
192866){
192867  Fts5Table *pTab = (Fts5Table*)pVtab;
192868  Fts5Config *pConfig = pTab->pConfig;
192869  int eType0;                     /* value_type() of apVal[0] */
192870  int rc = SQLITE_OK;             /* Return code */
192871
192872  /* A transaction must be open when this is called. */
192873  assert( pTab->ts.eState==1 );
192874
192875  assert( pVtab->zErrMsg==0 );
192876  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
192877  assert( nArg==1
192878      || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
192879      || sqlite3_value_type(apVal[1])==SQLITE_NULL
192880  );
192881  assert( pTab->pConfig->pzErrmsg==0 );
192882  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
192883
192884  /* Put any active cursors into REQUIRE_SEEK state. */
192885  fts5TripCursors(pTab);
192886
192887  eType0 = sqlite3_value_type(apVal[0]);
192888  if( eType0==SQLITE_NULL
192889   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
192890  ){
192891    /* A "special" INSERT op. These are handled separately. */
192892    const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
192893    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
192894      && 0==sqlite3_stricmp("delete", z)
192895    ){
192896      rc = fts5SpecialDelete(pTab, apVal);
192897    }else{
192898      rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
192899    }
192900  }else{
192901    /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
192902    ** any conflict on the rowid value must be detected before any
192903    ** modifications are made to the database file. There are 4 cases:
192904    **
192905    **   1) DELETE
192906    **   2) UPDATE (rowid not modified)
192907    **   3) UPDATE (rowid modified)
192908    **   4) INSERT
192909    **
192910    ** Cases 3 and 4 may violate the rowid constraint.
192911    */
192912    int eConflict = SQLITE_ABORT;
192913    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
192914      eConflict = sqlite3_vtab_on_conflict(pConfig->db);
192915    }
192916
192917    assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
192918    assert( nArg!=1 || eType0==SQLITE_INTEGER );
192919
192920    /* Filter out attempts to run UPDATE or DELETE on contentless tables.
192921    ** This is not suported.  */
192922    if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
192923      pTab->base.zErrMsg = sqlite3_mprintf(
192924          "cannot %s contentless fts5 table: %s",
192925          (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
192926      );
192927      rc = SQLITE_ERROR;
192928    }
192929
192930    /* DELETE */
192931    else if( nArg==1 ){
192932      i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
192933      rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
192934    }
192935
192936    /* INSERT */
192937    else if( eType0!=SQLITE_INTEGER ){
192938      /* If this is a REPLACE, first remove the current entry (if any) */
192939      if( eConflict==SQLITE_REPLACE
192940       && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
192941      ){
192942        i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
192943        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
192944      }
192945      fts5StorageInsert(&rc, pTab, apVal, pRowid);
192946    }
192947
192948    /* UPDATE */
192949    else{
192950      i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
192951      i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
192952      if( iOld!=iNew ){
192953        if( eConflict==SQLITE_REPLACE ){
192954          rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192955          if( rc==SQLITE_OK ){
192956            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
192957          }
192958          fts5StorageInsert(&rc, pTab, apVal, pRowid);
192959        }else{
192960          rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
192961          if( rc==SQLITE_OK ){
192962            rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192963          }
192964          if( rc==SQLITE_OK ){
192965            rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
192966          }
192967        }
192968      }else{
192969        rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192970        fts5StorageInsert(&rc, pTab, apVal, pRowid);
192971      }
192972    }
192973  }
192974
192975  pTab->pConfig->pzErrmsg = 0;
192976  return rc;
192977}
192978
192979/*
192980** Implementation of xSync() method.
192981*/
192982static int fts5SyncMethod(sqlite3_vtab *pVtab){
192983  int rc;
192984  Fts5Table *pTab = (Fts5Table*)pVtab;
192985  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
192986  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
192987  fts5TripCursors(pTab);
192988  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
192989  pTab->pConfig->pzErrmsg = 0;
192990  return rc;
192991}
192992
192993/*
192994** Implementation of xBegin() method.
192995*/
192996static int fts5BeginMethod(sqlite3_vtab *pVtab){
192997  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
192998  fts5NewTransaction((Fts5Table*)pVtab);
192999  return SQLITE_OK;
193000}
193001
193002/*
193003** Implementation of xCommit() method. This is a no-op. The contents of
193004** the pending-terms hash-table have already been flushed into the database
193005** by fts5SyncMethod().
193006*/
193007static int fts5CommitMethod(sqlite3_vtab *pVtab){
193008  UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
193009  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
193010  return SQLITE_OK;
193011}
193012
193013/*
193014** Implementation of xRollback(). Discard the contents of the pending-terms
193015** hash-table. Any changes made to the database are reverted by SQLite.
193016*/
193017static int fts5RollbackMethod(sqlite3_vtab *pVtab){
193018  int rc;
193019  Fts5Table *pTab = (Fts5Table*)pVtab;
193020  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
193021  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
193022  return rc;
193023}
193024
193025static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
193026
193027static void *fts5ApiUserData(Fts5Context *pCtx){
193028  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193029  return pCsr->pAux->pUserData;
193030}
193031
193032static int fts5ApiColumnCount(Fts5Context *pCtx){
193033  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193034  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
193035}
193036
193037static int fts5ApiColumnTotalSize(
193038  Fts5Context *pCtx,
193039  int iCol,
193040  sqlite3_int64 *pnToken
193041){
193042  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193043  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193044  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
193045}
193046
193047static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
193048  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193049  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193050  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
193051}
193052
193053static int fts5ApiTokenize(
193054  Fts5Context *pCtx,
193055  const char *pText, int nText,
193056  void *pUserData,
193057  int (*xToken)(void*, int, const char*, int, int, int)
193058){
193059  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193060  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193061  return sqlite3Fts5Tokenize(
193062      pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
193063  );
193064}
193065
193066static int fts5ApiPhraseCount(Fts5Context *pCtx){
193067  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193068  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193069}
193070
193071static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
193072  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193073  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
193074}
193075
193076static int fts5ApiColumnText(
193077  Fts5Context *pCtx,
193078  int iCol,
193079  const char **pz,
193080  int *pn
193081){
193082  int rc = SQLITE_OK;
193083  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193084  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
193085    *pz = 0;
193086    *pn = 0;
193087  }else{
193088    rc = fts5SeekCursor(pCsr, 0);
193089    if( rc==SQLITE_OK ){
193090      *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
193091      *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
193092    }
193093  }
193094  return rc;
193095}
193096
193097static int fts5CsrPoslist(
193098  Fts5Cursor *pCsr,
193099  int iPhrase,
193100  const u8 **pa,
193101  int *pn
193102){
193103  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193104  int rc = SQLITE_OK;
193105  int bLive = (pCsr->pSorter==0);
193106
193107  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
193108
193109    if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
193110      Fts5PoslistPopulator *aPopulator;
193111      int i;
193112      aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
193113      if( aPopulator==0 ) rc = SQLITE_NOMEM;
193114      for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
193115        int n; const char *z;
193116        rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
193117        if( rc==SQLITE_OK ){
193118          rc = sqlite3Fts5ExprPopulatePoslists(
193119              pConfig, pCsr->pExpr, aPopulator, i, z, n
193120          );
193121        }
193122      }
193123      sqlite3_free(aPopulator);
193124
193125      if( pCsr->pSorter ){
193126        sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
193127      }
193128    }
193129    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
193130  }
193131
193132  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
193133    Fts5Sorter *pSorter = pCsr->pSorter;
193134    int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
193135    *pn = pSorter->aIdx[iPhrase] - i1;
193136    *pa = &pSorter->aPoslist[i1];
193137  }else{
193138    *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
193139  }
193140
193141  return rc;
193142}
193143
193144/*
193145** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
193146** correctly for the current view. Return SQLITE_OK if successful, or an
193147** SQLite error code otherwise.
193148*/
193149static int fts5CacheInstArray(Fts5Cursor *pCsr){
193150  int rc = SQLITE_OK;
193151  Fts5PoslistReader *aIter;       /* One iterator for each phrase */
193152  int nIter;                      /* Number of iterators/phrases */
193153
193154  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193155  if( pCsr->aInstIter==0 ){
193156    int nByte = sizeof(Fts5PoslistReader) * nIter;
193157    pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
193158  }
193159  aIter = pCsr->aInstIter;
193160
193161  if( aIter ){
193162    int nInst = 0;                /* Number instances seen so far */
193163    int i;
193164
193165    /* Initialize all iterators */
193166    for(i=0; i<nIter && rc==SQLITE_OK; i++){
193167      const u8 *a;
193168      int n;
193169      rc = fts5CsrPoslist(pCsr, i, &a, &n);
193170      if( rc==SQLITE_OK ){
193171        sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
193172      }
193173    }
193174
193175    if( rc==SQLITE_OK ){
193176      while( 1 ){
193177        int *aInst;
193178        int iBest = -1;
193179        for(i=0; i<nIter; i++){
193180          if( (aIter[i].bEof==0)
193181              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
193182            ){
193183            iBest = i;
193184          }
193185        }
193186        if( iBest<0 ) break;
193187
193188        nInst++;
193189        if( nInst>=pCsr->nInstAlloc ){
193190          pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
193191          aInst = (int*)sqlite3_realloc(
193192              pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
193193              );
193194          if( aInst ){
193195            pCsr->aInst = aInst;
193196          }else{
193197            rc = SQLITE_NOMEM;
193198            break;
193199          }
193200        }
193201
193202        aInst = &pCsr->aInst[3 * (nInst-1)];
193203        aInst[0] = iBest;
193204        aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
193205        aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
193206        sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
193207      }
193208    }
193209
193210    pCsr->nInstCount = nInst;
193211    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
193212  }
193213  return rc;
193214}
193215
193216static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
193217  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193218  int rc = SQLITE_OK;
193219  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
193220   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
193221    *pnInst = pCsr->nInstCount;
193222  }
193223  return rc;
193224}
193225
193226static int fts5ApiInst(
193227  Fts5Context *pCtx,
193228  int iIdx,
193229  int *piPhrase,
193230  int *piCol,
193231  int *piOff
193232){
193233  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193234  int rc = SQLITE_OK;
193235  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
193236   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
193237  ){
193238    if( iIdx<0 || iIdx>=pCsr->nInstCount ){
193239      rc = SQLITE_RANGE;
193240#if 0
193241    }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
193242      *piPhrase = pCsr->aInst[iIdx*3];
193243      *piCol = pCsr->aInst[iIdx*3 + 2];
193244      *piOff = -1;
193245#endif
193246    }else{
193247      *piPhrase = pCsr->aInst[iIdx*3];
193248      *piCol = pCsr->aInst[iIdx*3 + 1];
193249      *piOff = pCsr->aInst[iIdx*3 + 2];
193250    }
193251  }
193252  return rc;
193253}
193254
193255static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
193256  return fts5CursorRowid((Fts5Cursor*)pCtx);
193257}
193258
193259static int fts5ColumnSizeCb(
193260  void *pContext,                 /* Pointer to int */
193261  int tflags,
193262  const char *pUnused,            /* Buffer containing token */
193263  int nUnused,                    /* Size of token in bytes */
193264  int iUnused1,                   /* Start offset of token */
193265  int iUnused2                    /* End offset of token */
193266){
193267  int *pCnt = (int*)pContext;
193268  UNUSED_PARAM2(pUnused, nUnused);
193269  UNUSED_PARAM2(iUnused1, iUnused2);
193270  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
193271    (*pCnt)++;
193272  }
193273  return SQLITE_OK;
193274}
193275
193276static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
193277  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193278  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193279  Fts5Config *pConfig = pTab->pConfig;
193280  int rc = SQLITE_OK;
193281
193282  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
193283    if( pConfig->bColumnsize ){
193284      i64 iRowid = fts5CursorRowid(pCsr);
193285      rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
193286    }else if( pConfig->zContent==0 ){
193287      int i;
193288      for(i=0; i<pConfig->nCol; i++){
193289        if( pConfig->abUnindexed[i]==0 ){
193290          pCsr->aColumnSize[i] = -1;
193291        }
193292      }
193293    }else{
193294      int i;
193295      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
193296        if( pConfig->abUnindexed[i]==0 ){
193297          const char *z; int n;
193298          void *p = (void*)(&pCsr->aColumnSize[i]);
193299          pCsr->aColumnSize[i] = 0;
193300          rc = fts5ApiColumnText(pCtx, i, &z, &n);
193301          if( rc==SQLITE_OK ){
193302            rc = sqlite3Fts5Tokenize(
193303                pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
193304            );
193305          }
193306        }
193307      }
193308    }
193309    CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
193310  }
193311  if( iCol<0 ){
193312    int i;
193313    *pnToken = 0;
193314    for(i=0; i<pConfig->nCol; i++){
193315      *pnToken += pCsr->aColumnSize[i];
193316    }
193317  }else if( iCol<pConfig->nCol ){
193318    *pnToken = pCsr->aColumnSize[iCol];
193319  }else{
193320    *pnToken = 0;
193321    rc = SQLITE_RANGE;
193322  }
193323  return rc;
193324}
193325
193326/*
193327** Implementation of the xSetAuxdata() method.
193328*/
193329static int fts5ApiSetAuxdata(
193330  Fts5Context *pCtx,              /* Fts5 context */
193331  void *pPtr,                     /* Pointer to save as auxdata */
193332  void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
193333){
193334  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193335  Fts5Auxdata *pData;
193336
193337  /* Search through the cursors list of Fts5Auxdata objects for one that
193338  ** corresponds to the currently executing auxiliary function.  */
193339  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
193340    if( pData->pAux==pCsr->pAux ) break;
193341  }
193342
193343  if( pData ){
193344    if( pData->xDelete ){
193345      pData->xDelete(pData->pPtr);
193346    }
193347  }else{
193348    int rc = SQLITE_OK;
193349    pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
193350    if( pData==0 ){
193351      if( xDelete ) xDelete(pPtr);
193352      return rc;
193353    }
193354    pData->pAux = pCsr->pAux;
193355    pData->pNext = pCsr->pAuxdata;
193356    pCsr->pAuxdata = pData;
193357  }
193358
193359  pData->xDelete = xDelete;
193360  pData->pPtr = pPtr;
193361  return SQLITE_OK;
193362}
193363
193364static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
193365  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193366  Fts5Auxdata *pData;
193367  void *pRet = 0;
193368
193369  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
193370    if( pData->pAux==pCsr->pAux ) break;
193371  }
193372
193373  if( pData ){
193374    pRet = pData->pPtr;
193375    if( bClear ){
193376      pData->pPtr = 0;
193377      pData->xDelete = 0;
193378    }
193379  }
193380
193381  return pRet;
193382}
193383
193384static void fts5ApiPhraseNext(
193385  Fts5Context *pUnused,
193386  Fts5PhraseIter *pIter,
193387  int *piCol, int *piOff
193388){
193389  UNUSED_PARAM(pUnused);
193390  if( pIter->a>=pIter->b ){
193391    *piCol = -1;
193392    *piOff = -1;
193393  }else{
193394    int iVal;
193395    pIter->a += fts5GetVarint32(pIter->a, iVal);
193396    if( iVal==1 ){
193397      pIter->a += fts5GetVarint32(pIter->a, iVal);
193398      *piCol = iVal;
193399      *piOff = 0;
193400      pIter->a += fts5GetVarint32(pIter->a, iVal);
193401    }
193402    *piOff += (iVal-2);
193403  }
193404}
193405
193406static int fts5ApiPhraseFirst(
193407  Fts5Context *pCtx,
193408  int iPhrase,
193409  Fts5PhraseIter *pIter,
193410  int *piCol, int *piOff
193411){
193412  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193413  int n;
193414  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
193415  if( rc==SQLITE_OK ){
193416    pIter->b = &pIter->a[n];
193417    *piCol = 0;
193418    *piOff = 0;
193419    fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
193420  }
193421  return rc;
193422}
193423
193424static void fts5ApiPhraseNextColumn(
193425  Fts5Context *pCtx,
193426  Fts5PhraseIter *pIter,
193427  int *piCol
193428){
193429  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193430  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193431
193432  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193433    if( pIter->a>=pIter->b ){
193434      *piCol = -1;
193435    }else{
193436      int iIncr;
193437      pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
193438      *piCol += (iIncr-2);
193439    }
193440  }else{
193441    while( 1 ){
193442      int dummy;
193443      if( pIter->a>=pIter->b ){
193444        *piCol = -1;
193445        return;
193446      }
193447      if( pIter->a[0]==0x01 ) break;
193448      pIter->a += fts5GetVarint32(pIter->a, dummy);
193449    }
193450    pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
193451  }
193452}
193453
193454static int fts5ApiPhraseFirstColumn(
193455  Fts5Context *pCtx,
193456  int iPhrase,
193457  Fts5PhraseIter *pIter,
193458  int *piCol
193459){
193460  int rc = SQLITE_OK;
193461  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193462  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193463
193464  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193465    Fts5Sorter *pSorter = pCsr->pSorter;
193466    int n;
193467    if( pSorter ){
193468      int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
193469      n = pSorter->aIdx[iPhrase] - i1;
193470      pIter->a = &pSorter->aPoslist[i1];
193471    }else{
193472      rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
193473    }
193474    if( rc==SQLITE_OK ){
193475      pIter->b = &pIter->a[n];
193476      *piCol = 0;
193477      fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
193478    }
193479  }else{
193480    int n;
193481    rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
193482    if( rc==SQLITE_OK ){
193483      pIter->b = &pIter->a[n];
193484      if( n<=0 ){
193485        *piCol = -1;
193486      }else if( pIter->a[0]==0x01 ){
193487        pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
193488      }else{
193489        *piCol = 0;
193490      }
193491    }
193492  }
193493
193494  return rc;
193495}
193496
193497
193498static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
193499    int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
193500);
193501
193502static const Fts5ExtensionApi sFts5Api = {
193503  2,                            /* iVersion */
193504  fts5ApiUserData,
193505  fts5ApiColumnCount,
193506  fts5ApiRowCount,
193507  fts5ApiColumnTotalSize,
193508  fts5ApiTokenize,
193509  fts5ApiPhraseCount,
193510  fts5ApiPhraseSize,
193511  fts5ApiInstCount,
193512  fts5ApiInst,
193513  fts5ApiRowid,
193514  fts5ApiColumnText,
193515  fts5ApiColumnSize,
193516  fts5ApiQueryPhrase,
193517  fts5ApiSetAuxdata,
193518  fts5ApiGetAuxdata,
193519  fts5ApiPhraseFirst,
193520  fts5ApiPhraseNext,
193521  fts5ApiPhraseFirstColumn,
193522  fts5ApiPhraseNextColumn,
193523};
193524
193525/*
193526** Implementation of API function xQueryPhrase().
193527*/
193528static int fts5ApiQueryPhrase(
193529  Fts5Context *pCtx,
193530  int iPhrase,
193531  void *pUserData,
193532  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
193533){
193534  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193535  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193536  int rc;
193537  Fts5Cursor *pNew = 0;
193538
193539  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
193540  if( rc==SQLITE_OK ){
193541    pNew->ePlan = FTS5_PLAN_MATCH;
193542    pNew->iFirstRowid = SMALLEST_INT64;
193543    pNew->iLastRowid = LARGEST_INT64;
193544    pNew->base.pVtab = (sqlite3_vtab*)pTab;
193545    rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
193546  }
193547
193548  if( rc==SQLITE_OK ){
193549    for(rc = fts5CursorFirst(pTab, pNew, 0);
193550        rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
193551        rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
193552    ){
193553      rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
193554      if( rc!=SQLITE_OK ){
193555        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
193556        break;
193557      }
193558    }
193559  }
193560
193561  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
193562  return rc;
193563}
193564
193565static void fts5ApiInvoke(
193566  Fts5Auxiliary *pAux,
193567  Fts5Cursor *pCsr,
193568  sqlite3_context *context,
193569  int argc,
193570  sqlite3_value **argv
193571){
193572  assert( pCsr->pAux==0 );
193573  pCsr->pAux = pAux;
193574  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
193575  pCsr->pAux = 0;
193576}
193577
193578static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
193579  Fts5Cursor *pCsr;
193580  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193581    if( pCsr->iCsrId==iCsrId ) break;
193582  }
193583  return pCsr;
193584}
193585
193586static void fts5ApiCallback(
193587  sqlite3_context *context,
193588  int argc,
193589  sqlite3_value **argv
193590){
193591
193592  Fts5Auxiliary *pAux;
193593  Fts5Cursor *pCsr;
193594  i64 iCsrId;
193595
193596  assert( argc>=1 );
193597  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
193598  iCsrId = sqlite3_value_int64(argv[0]);
193599
193600  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
193601  if( pCsr==0 ){
193602    char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
193603    sqlite3_result_error(context, zErr, -1);
193604    sqlite3_free(zErr);
193605  }else{
193606    fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
193607  }
193608}
193609
193610
193611/*
193612** Given cursor id iId, return a pointer to the corresponding Fts5Index
193613** object. Or NULL If the cursor id does not exist.
193614**
193615** If successful, set *ppConfig to point to the associated config object
193616** before returning.
193617*/
193618static Fts5Index *sqlite3Fts5IndexFromCsrid(
193619  Fts5Global *pGlobal,            /* FTS5 global context for db handle */
193620  i64 iCsrId,                     /* Id of cursor to find */
193621  Fts5Config **ppConfig           /* OUT: Configuration object */
193622){
193623  Fts5Cursor *pCsr;
193624  Fts5Table *pTab;
193625
193626  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
193627  pTab = (Fts5Table*)pCsr->base.pVtab;
193628  *ppConfig = pTab->pConfig;
193629
193630  return pTab->pIndex;
193631}
193632
193633/*
193634** Return a "position-list blob" corresponding to the current position of
193635** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
193636** the current position-list for each phrase in the query associated with
193637** cursor pCsr.
193638**
193639** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
193640** the number of phrases in the query. Following the varints are the
193641** concatenated position lists for each phrase, in order.
193642**
193643** The first varint (if it exists) contains the size of the position list
193644** for phrase 0. The second (same disclaimer) contains the size of position
193645** list 1. And so on. There is no size field for the final position list,
193646** as it can be derived from the total size of the blob.
193647*/
193648static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
193649  int i;
193650  int rc = SQLITE_OK;
193651  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193652  Fts5Buffer val;
193653
193654  memset(&val, 0, sizeof(Fts5Buffer));
193655  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
193656    case FTS5_DETAIL_FULL:
193657
193658      /* Append the varints */
193659      for(i=0; i<(nPhrase-1); i++){
193660        const u8 *dummy;
193661        int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
193662        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
193663      }
193664
193665      /* Append the position lists */
193666      for(i=0; i<nPhrase; i++){
193667        const u8 *pPoslist;
193668        int nPoslist;
193669        nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
193670        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
193671      }
193672      break;
193673
193674    case FTS5_DETAIL_COLUMNS:
193675
193676      /* Append the varints */
193677      for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
193678        const u8 *dummy;
193679        int nByte;
193680        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
193681        sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
193682      }
193683
193684      /* Append the position lists */
193685      for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
193686        const u8 *pPoslist;
193687        int nPoslist;
193688        rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
193689        sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
193690      }
193691      break;
193692
193693    default:
193694      break;
193695  }
193696
193697  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
193698  return rc;
193699}
193700
193701/*
193702** This is the xColumn method, called by SQLite to request a value from
193703** the row that the supplied cursor currently points to.
193704*/
193705static int fts5ColumnMethod(
193706  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
193707  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
193708  int iCol                        /* Index of column to read value from */
193709){
193710  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
193711  Fts5Config *pConfig = pTab->pConfig;
193712  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193713  int rc = SQLITE_OK;
193714
193715  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
193716
193717  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
193718    if( iCol==pConfig->nCol ){
193719      sqlite3_result_int64(pCtx, pCsr->iSpecial);
193720    }
193721  }else
193722
193723  if( iCol==pConfig->nCol ){
193724    /* User is requesting the value of the special column with the same name
193725    ** as the table. Return the cursor integer id number. This value is only
193726    ** useful in that it may be passed as the first argument to an FTS5
193727    ** auxiliary function.  */
193728    sqlite3_result_int64(pCtx, pCsr->iCsrId);
193729  }else if( iCol==pConfig->nCol+1 ){
193730
193731    /* The value of the "rank" column. */
193732    if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
193733      fts5PoslistBlob(pCtx, pCsr);
193734    }else if(
193735        pCsr->ePlan==FTS5_PLAN_MATCH
193736     || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
193737    ){
193738      if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
193739        fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
193740      }
193741    }
193742  }else if( !fts5IsContentless(pTab) ){
193743    rc = fts5SeekCursor(pCsr, 1);
193744    if( rc==SQLITE_OK ){
193745      sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
193746    }
193747  }
193748  return rc;
193749}
193750
193751
193752/*
193753** This routine implements the xFindFunction method for the FTS3
193754** virtual table.
193755*/
193756static int fts5FindFunctionMethod(
193757  sqlite3_vtab *pVtab,            /* Virtual table handle */
193758  int nUnused,                    /* Number of SQL function arguments */
193759  const char *zName,              /* Name of SQL function */
193760  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
193761  void **ppArg                    /* OUT: User data for *pxFunc */
193762){
193763  Fts5Table *pTab = (Fts5Table*)pVtab;
193764  Fts5Auxiliary *pAux;
193765
193766  UNUSED_PARAM(nUnused);
193767  pAux = fts5FindAuxiliary(pTab, zName);
193768  if( pAux ){
193769    *pxFunc = fts5ApiCallback;
193770    *ppArg = (void*)pAux;
193771    return 1;
193772  }
193773
193774  /* No function of the specified name was found. Return 0. */
193775  return 0;
193776}
193777
193778/*
193779** Implementation of FTS5 xRename method. Rename an fts5 table.
193780*/
193781static int fts5RenameMethod(
193782  sqlite3_vtab *pVtab,            /* Virtual table handle */
193783  const char *zName               /* New name of table */
193784){
193785  Fts5Table *pTab = (Fts5Table*)pVtab;
193786  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
193787}
193788
193789/*
193790** The xSavepoint() method.
193791**
193792** Flush the contents of the pending-terms table to disk.
193793*/
193794static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
193795  Fts5Table *pTab = (Fts5Table*)pVtab;
193796  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193797  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
193798  fts5TripCursors(pTab);
193799  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
193800}
193801
193802/*
193803** The xRelease() method.
193804**
193805** This is a no-op.
193806*/
193807static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
193808  Fts5Table *pTab = (Fts5Table*)pVtab;
193809  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193810  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
193811  fts5TripCursors(pTab);
193812  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
193813}
193814
193815/*
193816** The xRollbackTo() method.
193817**
193818** Discard the contents of the pending terms table.
193819*/
193820static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
193821  Fts5Table *pTab = (Fts5Table*)pVtab;
193822  UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193823  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
193824  fts5TripCursors(pTab);
193825  return sqlite3Fts5StorageRollback(pTab->pStorage);
193826}
193827
193828/*
193829** Register a new auxiliary function with global context pGlobal.
193830*/
193831static int fts5CreateAux(
193832  fts5_api *pApi,                 /* Global context (one per db handle) */
193833  const char *zName,              /* Name of new function */
193834  void *pUserData,                /* User data for aux. function */
193835  fts5_extension_function xFunc,  /* Aux. function implementation */
193836  void(*xDestroy)(void*)          /* Destructor for pUserData */
193837){
193838  Fts5Global *pGlobal = (Fts5Global*)pApi;
193839  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
193840  if( rc==SQLITE_OK ){
193841    Fts5Auxiliary *pAux;
193842    int nName;                      /* Size of zName in bytes, including \0 */
193843    int nByte;                      /* Bytes of space to allocate */
193844
193845    nName = (int)strlen(zName) + 1;
193846    nByte = sizeof(Fts5Auxiliary) + nName;
193847    pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
193848    if( pAux ){
193849      memset(pAux, 0, nByte);
193850      pAux->zFunc = (char*)&pAux[1];
193851      memcpy(pAux->zFunc, zName, nName);
193852      pAux->pGlobal = pGlobal;
193853      pAux->pUserData = pUserData;
193854      pAux->xFunc = xFunc;
193855      pAux->xDestroy = xDestroy;
193856      pAux->pNext = pGlobal->pAux;
193857      pGlobal->pAux = pAux;
193858    }else{
193859      rc = SQLITE_NOMEM;
193860    }
193861  }
193862
193863  return rc;
193864}
193865
193866/*
193867** Register a new tokenizer. This is the implementation of the
193868** fts5_api.xCreateTokenizer() method.
193869*/
193870static int fts5CreateTokenizer(
193871  fts5_api *pApi,                 /* Global context (one per db handle) */
193872  const char *zName,              /* Name of new function */
193873  void *pUserData,                /* User data for aux. function */
193874  fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
193875  void(*xDestroy)(void*)          /* Destructor for pUserData */
193876){
193877  Fts5Global *pGlobal = (Fts5Global*)pApi;
193878  Fts5TokenizerModule *pNew;
193879  int nName;                      /* Size of zName and its \0 terminator */
193880  int nByte;                      /* Bytes of space to allocate */
193881  int rc = SQLITE_OK;
193882
193883  nName = (int)strlen(zName) + 1;
193884  nByte = sizeof(Fts5TokenizerModule) + nName;
193885  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
193886  if( pNew ){
193887    memset(pNew, 0, nByte);
193888    pNew->zName = (char*)&pNew[1];
193889    memcpy(pNew->zName, zName, nName);
193890    pNew->pUserData = pUserData;
193891    pNew->x = *pTokenizer;
193892    pNew->xDestroy = xDestroy;
193893    pNew->pNext = pGlobal->pTok;
193894    pGlobal->pTok = pNew;
193895    if( pNew->pNext==0 ){
193896      pGlobal->pDfltTok = pNew;
193897    }
193898  }else{
193899    rc = SQLITE_NOMEM;
193900  }
193901
193902  return rc;
193903}
193904
193905static Fts5TokenizerModule *fts5LocateTokenizer(
193906  Fts5Global *pGlobal,
193907  const char *zName
193908){
193909  Fts5TokenizerModule *pMod = 0;
193910
193911  if( zName==0 ){
193912    pMod = pGlobal->pDfltTok;
193913  }else{
193914    for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
193915      if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
193916    }
193917  }
193918
193919  return pMod;
193920}
193921
193922/*
193923** Find a tokenizer. This is the implementation of the
193924** fts5_api.xFindTokenizer() method.
193925*/
193926static int fts5FindTokenizer(
193927  fts5_api *pApi,                 /* Global context (one per db handle) */
193928  const char *zName,              /* Name of new function */
193929  void **ppUserData,
193930  fts5_tokenizer *pTokenizer      /* Populate this object */
193931){
193932  int rc = SQLITE_OK;
193933  Fts5TokenizerModule *pMod;
193934
193935  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
193936  if( pMod ){
193937    *pTokenizer = pMod->x;
193938    *ppUserData = pMod->pUserData;
193939  }else{
193940    memset(pTokenizer, 0, sizeof(fts5_tokenizer));
193941    rc = SQLITE_ERROR;
193942  }
193943
193944  return rc;
193945}
193946
193947static int sqlite3Fts5GetTokenizer(
193948  Fts5Global *pGlobal,
193949  const char **azArg,
193950  int nArg,
193951  Fts5Tokenizer **ppTok,
193952  fts5_tokenizer **ppTokApi,
193953  char **pzErr
193954){
193955  Fts5TokenizerModule *pMod;
193956  int rc = SQLITE_OK;
193957
193958  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
193959  if( pMod==0 ){
193960    assert( nArg>0 );
193961    rc = SQLITE_ERROR;
193962    *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
193963  }else{
193964    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
193965    *ppTokApi = &pMod->x;
193966    if( rc!=SQLITE_OK && pzErr ){
193967      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
193968    }
193969  }
193970
193971  if( rc!=SQLITE_OK ){
193972    *ppTokApi = 0;
193973    *ppTok = 0;
193974  }
193975
193976  return rc;
193977}
193978
193979static void fts5ModuleDestroy(void *pCtx){
193980  Fts5TokenizerModule *pTok, *pNextTok;
193981  Fts5Auxiliary *pAux, *pNextAux;
193982  Fts5Global *pGlobal = (Fts5Global*)pCtx;
193983
193984  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
193985    pNextAux = pAux->pNext;
193986    if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
193987    sqlite3_free(pAux);
193988  }
193989
193990  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
193991    pNextTok = pTok->pNext;
193992    if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
193993    sqlite3_free(pTok);
193994  }
193995
193996  sqlite3_free(pGlobal);
193997}
193998
193999static void fts5Fts5Func(
194000  sqlite3_context *pCtx,          /* Function call context */
194001  int nArg,                       /* Number of args */
194002  sqlite3_value **apUnused        /* Function arguments */
194003){
194004  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
194005  char buf[8];
194006  UNUSED_PARAM2(nArg, apUnused);
194007  assert( nArg==0 );
194008  assert( sizeof(buf)>=sizeof(pGlobal) );
194009  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
194010  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
194011}
194012
194013/*
194014** Implementation of fts5_source_id() function.
194015*/
194016static void fts5SourceIdFunc(
194017  sqlite3_context *pCtx,          /* Function call context */
194018  int nArg,                       /* Number of args */
194019  sqlite3_value **apUnused        /* Function arguments */
194020){
194021  assert( nArg==0 );
194022  UNUSED_PARAM2(nArg, apUnused);
194023  sqlite3_result_text(pCtx, "fts5: 2016-08-11 18:53:32 a12d8059770df4bca59e321c266410344242bf7b", -1, SQLITE_TRANSIENT);
194024}
194025
194026static int fts5Init(sqlite3 *db){
194027  static const sqlite3_module fts5Mod = {
194028    /* iVersion      */ 2,
194029    /* xCreate       */ fts5CreateMethod,
194030    /* xConnect      */ fts5ConnectMethod,
194031    /* xBestIndex    */ fts5BestIndexMethod,
194032    /* xDisconnect   */ fts5DisconnectMethod,
194033    /* xDestroy      */ fts5DestroyMethod,
194034    /* xOpen         */ fts5OpenMethod,
194035    /* xClose        */ fts5CloseMethod,
194036    /* xFilter       */ fts5FilterMethod,
194037    /* xNext         */ fts5NextMethod,
194038    /* xEof          */ fts5EofMethod,
194039    /* xColumn       */ fts5ColumnMethod,
194040    /* xRowid        */ fts5RowidMethod,
194041    /* xUpdate       */ fts5UpdateMethod,
194042    /* xBegin        */ fts5BeginMethod,
194043    /* xSync         */ fts5SyncMethod,
194044    /* xCommit       */ fts5CommitMethod,
194045    /* xRollback     */ fts5RollbackMethod,
194046    /* xFindFunction */ fts5FindFunctionMethod,
194047    /* xRename       */ fts5RenameMethod,
194048    /* xSavepoint    */ fts5SavepointMethod,
194049    /* xRelease      */ fts5ReleaseMethod,
194050    /* xRollbackTo   */ fts5RollbackToMethod,
194051  };
194052
194053  int rc;
194054  Fts5Global *pGlobal = 0;
194055
194056  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
194057  if( pGlobal==0 ){
194058    rc = SQLITE_NOMEM;
194059  }else{
194060    void *p = (void*)pGlobal;
194061    memset(pGlobal, 0, sizeof(Fts5Global));
194062    pGlobal->db = db;
194063    pGlobal->api.iVersion = 2;
194064    pGlobal->api.xCreateFunction = fts5CreateAux;
194065    pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
194066    pGlobal->api.xFindTokenizer = fts5FindTokenizer;
194067    rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
194068    if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
194069    if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
194070    if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
194071    if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
194072    if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
194073    if( rc==SQLITE_OK ){
194074      rc = sqlite3_create_function(
194075          db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
194076      );
194077    }
194078    if( rc==SQLITE_OK ){
194079      rc = sqlite3_create_function(
194080          db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
194081      );
194082    }
194083  }
194084
194085  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
194086  ** fts5_test_mi.c is compiled and linked into the executable. And call
194087  ** its entry point to enable the matchinfo() demo.  */
194088#ifdef SQLITE_FTS5_ENABLE_TEST_MI
194089  if( rc==SQLITE_OK ){
194090    extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
194091    rc = sqlite3Fts5TestRegisterMatchinfo(db);
194092  }
194093#endif
194094
194095  return rc;
194096}
194097
194098/*
194099** The following functions are used to register the module with SQLite. If
194100** this module is being built as part of the SQLite core (SQLITE_CORE is
194101** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
194102**
194103** Or, if this module is being built as a loadable extension,
194104** sqlite3Fts5Init() is omitted and the two standard entry points
194105** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
194106*/
194107#ifndef SQLITE_CORE
194108#ifdef _WIN32
194109__declspec(dllexport)
194110#endif
194111SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
194112  sqlite3 *db,
194113  char **pzErrMsg,
194114  const sqlite3_api_routines *pApi
194115){
194116  SQLITE_EXTENSION_INIT2(pApi);
194117  (void)pzErrMsg;  /* Unused parameter */
194118  return fts5Init(db);
194119}
194120
194121#ifdef _WIN32
194122__declspec(dllexport)
194123#endif
194124SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
194125  sqlite3 *db,
194126  char **pzErrMsg,
194127  const sqlite3_api_routines *pApi
194128){
194129  SQLITE_EXTENSION_INIT2(pApi);
194130  (void)pzErrMsg;  /* Unused parameter */
194131  return fts5Init(db);
194132}
194133#else
194134SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
194135  return fts5Init(db);
194136}
194137#endif
194138
194139/*
194140** 2014 May 31
194141**
194142** The author disclaims copyright to this source code.  In place of
194143** a legal notice, here is a blessing:
194144**
194145**    May you do good and not evil.
194146**    May you find forgiveness for yourself and forgive others.
194147**    May you share freely, never taking more than you give.
194148**
194149******************************************************************************
194150**
194151*/
194152
194153
194154
194155/* #include "fts5Int.h" */
194156
194157struct Fts5Storage {
194158  Fts5Config *pConfig;
194159  Fts5Index *pIndex;
194160  int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
194161  i64 nTotalRow;                  /* Total number of rows in FTS table */
194162  i64 *aTotalSize;                /* Total sizes of each column */
194163  sqlite3_stmt *aStmt[11];
194164};
194165
194166
194167#if FTS5_STMT_SCAN_ASC!=0
194168# error "FTS5_STMT_SCAN_ASC mismatch"
194169#endif
194170#if FTS5_STMT_SCAN_DESC!=1
194171# error "FTS5_STMT_SCAN_DESC mismatch"
194172#endif
194173#if FTS5_STMT_LOOKUP!=2
194174# error "FTS5_STMT_LOOKUP mismatch"
194175#endif
194176
194177#define FTS5_STMT_INSERT_CONTENT  3
194178#define FTS5_STMT_REPLACE_CONTENT 4
194179#define FTS5_STMT_DELETE_CONTENT  5
194180#define FTS5_STMT_REPLACE_DOCSIZE  6
194181#define FTS5_STMT_DELETE_DOCSIZE  7
194182#define FTS5_STMT_LOOKUP_DOCSIZE  8
194183#define FTS5_STMT_REPLACE_CONFIG 9
194184#define FTS5_STMT_SCAN 10
194185
194186/*
194187** Prepare the two insert statements - Fts5Storage.pInsertContent and
194188** Fts5Storage.pInsertDocsize - if they have not already been prepared.
194189** Return SQLITE_OK if successful, or an SQLite error code if an error
194190** occurs.
194191*/
194192static int fts5StorageGetStmt(
194193  Fts5Storage *p,                 /* Storage handle */
194194  int eStmt,                      /* FTS5_STMT_XXX constant */
194195  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
194196  char **pzErrMsg                 /* OUT: Error message (if any) */
194197){
194198  int rc = SQLITE_OK;
194199
194200  /* If there is no %_docsize table, there should be no requests for
194201  ** statements to operate on it.  */
194202  assert( p->pConfig->bColumnsize || (
194203        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
194204     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
194205     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
194206  ));
194207
194208  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
194209  if( p->aStmt[eStmt]==0 ){
194210    const char *azStmt[] = {
194211      "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
194212      "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
194213      "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
194214
194215      "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
194216      "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
194217      "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
194218      "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
194219      "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
194220
194221      "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
194222
194223      "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
194224      "SELECT %s FROM %s AS T",                         /* SCAN */
194225    };
194226    Fts5Config *pC = p->pConfig;
194227    char *zSql = 0;
194228
194229    switch( eStmt ){
194230      case FTS5_STMT_SCAN:
194231        zSql = sqlite3_mprintf(azStmt[eStmt],
194232            pC->zContentExprlist, pC->zContent
194233        );
194234        break;
194235
194236      case FTS5_STMT_SCAN_ASC:
194237      case FTS5_STMT_SCAN_DESC:
194238        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
194239            pC->zContent, pC->zContentRowid, pC->zContentRowid,
194240            pC->zContentRowid
194241        );
194242        break;
194243
194244      case FTS5_STMT_LOOKUP:
194245        zSql = sqlite3_mprintf(azStmt[eStmt],
194246            pC->zContentExprlist, pC->zContent, pC->zContentRowid
194247        );
194248        break;
194249
194250      case FTS5_STMT_INSERT_CONTENT:
194251      case FTS5_STMT_REPLACE_CONTENT: {
194252        int nCol = pC->nCol + 1;
194253        char *zBind;
194254        int i;
194255
194256        zBind = sqlite3_malloc(1 + nCol*2);
194257        if( zBind ){
194258          for(i=0; i<nCol; i++){
194259            zBind[i*2] = '?';
194260            zBind[i*2 + 1] = ',';
194261          }
194262          zBind[i*2-1] = '\0';
194263          zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
194264          sqlite3_free(zBind);
194265        }
194266        break;
194267      }
194268
194269      default:
194270        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
194271        break;
194272    }
194273
194274    if( zSql==0 ){
194275      rc = SQLITE_NOMEM;
194276    }else{
194277      rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
194278      sqlite3_free(zSql);
194279      if( rc!=SQLITE_OK && pzErrMsg ){
194280        *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
194281      }
194282    }
194283  }
194284
194285  *ppStmt = p->aStmt[eStmt];
194286  sqlite3_reset(*ppStmt);
194287  return rc;
194288}
194289
194290
194291static int fts5ExecPrintf(
194292  sqlite3 *db,
194293  char **pzErr,
194294  const char *zFormat,
194295  ...
194296){
194297  int rc;
194298  va_list ap;                     /* ... printf arguments */
194299  char *zSql;
194300
194301  va_start(ap, zFormat);
194302  zSql = sqlite3_vmprintf(zFormat, ap);
194303
194304  if( zSql==0 ){
194305    rc = SQLITE_NOMEM;
194306  }else{
194307    rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
194308    sqlite3_free(zSql);
194309  }
194310
194311  va_end(ap);
194312  return rc;
194313}
194314
194315/*
194316** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
194317** code otherwise.
194318*/
194319static int sqlite3Fts5DropAll(Fts5Config *pConfig){
194320  int rc = fts5ExecPrintf(pConfig->db, 0,
194321      "DROP TABLE IF EXISTS %Q.'%q_data';"
194322      "DROP TABLE IF EXISTS %Q.'%q_idx';"
194323      "DROP TABLE IF EXISTS %Q.'%q_config';",
194324      pConfig->zDb, pConfig->zName,
194325      pConfig->zDb, pConfig->zName,
194326      pConfig->zDb, pConfig->zName
194327  );
194328  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194329    rc = fts5ExecPrintf(pConfig->db, 0,
194330        "DROP TABLE IF EXISTS %Q.'%q_docsize';",
194331        pConfig->zDb, pConfig->zName
194332    );
194333  }
194334  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
194335    rc = fts5ExecPrintf(pConfig->db, 0,
194336        "DROP TABLE IF EXISTS %Q.'%q_content';",
194337        pConfig->zDb, pConfig->zName
194338    );
194339  }
194340  return rc;
194341}
194342
194343static void fts5StorageRenameOne(
194344  Fts5Config *pConfig,            /* Current FTS5 configuration */
194345  int *pRc,                       /* IN/OUT: Error code */
194346  const char *zTail,              /* Tail of table name e.g. "data", "config" */
194347  const char *zName               /* New name of FTS5 table */
194348){
194349  if( *pRc==SQLITE_OK ){
194350    *pRc = fts5ExecPrintf(pConfig->db, 0,
194351        "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
194352        pConfig->zDb, pConfig->zName, zTail, zName, zTail
194353    );
194354  }
194355}
194356
194357static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
194358  Fts5Config *pConfig = pStorage->pConfig;
194359  int rc = sqlite3Fts5StorageSync(pStorage, 1);
194360
194361  fts5StorageRenameOne(pConfig, &rc, "data", zName);
194362  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
194363  fts5StorageRenameOne(pConfig, &rc, "config", zName);
194364  if( pConfig->bColumnsize ){
194365    fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
194366  }
194367  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194368    fts5StorageRenameOne(pConfig, &rc, "content", zName);
194369  }
194370  return rc;
194371}
194372
194373/*
194374** Create the shadow table named zPost, with definition zDefn. Return
194375** SQLITE_OK if successful, or an SQLite error code otherwise.
194376*/
194377static int sqlite3Fts5CreateTable(
194378  Fts5Config *pConfig,            /* FTS5 configuration */
194379  const char *zPost,              /* Shadow table to create (e.g. "content") */
194380  const char *zDefn,              /* Columns etc. for shadow table */
194381  int bWithout,                   /* True for without rowid */
194382  char **pzErr                    /* OUT: Error message */
194383){
194384  int rc;
194385  char *zErr = 0;
194386
194387  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
194388      pConfig->zDb, pConfig->zName, zPost, zDefn,
194389#ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
194390      bWithout?" WITHOUT ROWID":
194391#endif
194392      ""
194393  );
194394  if( zErr ){
194395    *pzErr = sqlite3_mprintf(
194396        "fts5: error creating shadow table %q_%s: %s",
194397        pConfig->zName, zPost, zErr
194398    );
194399    sqlite3_free(zErr);
194400  }
194401
194402  return rc;
194403}
194404
194405/*
194406** Open a new Fts5Index handle. If the bCreate argument is true, create
194407** and initialize the underlying tables
194408**
194409** If successful, set *pp to point to the new object and return SQLITE_OK.
194410** Otherwise, set *pp to NULL and return an SQLite error code.
194411*/
194412static int sqlite3Fts5StorageOpen(
194413  Fts5Config *pConfig,
194414  Fts5Index *pIndex,
194415  int bCreate,
194416  Fts5Storage **pp,
194417  char **pzErr                    /* OUT: Error message */
194418){
194419  int rc = SQLITE_OK;
194420  Fts5Storage *p;                 /* New object */
194421  int nByte;                      /* Bytes of space to allocate */
194422
194423  nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
194424        + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
194425  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
194426  if( !p ) return SQLITE_NOMEM;
194427
194428  memset(p, 0, nByte);
194429  p->aTotalSize = (i64*)&p[1];
194430  p->pConfig = pConfig;
194431  p->pIndex = pIndex;
194432
194433  if( bCreate ){
194434    if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194435      int nDefn = 32 + pConfig->nCol*10;
194436      char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
194437      if( zDefn==0 ){
194438        rc = SQLITE_NOMEM;
194439      }else{
194440        int i;
194441        int iOff;
194442        sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
194443        iOff = (int)strlen(zDefn);
194444        for(i=0; i<pConfig->nCol; i++){
194445          sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
194446          iOff += (int)strlen(&zDefn[iOff]);
194447        }
194448        rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
194449      }
194450      sqlite3_free(zDefn);
194451    }
194452
194453    if( rc==SQLITE_OK && pConfig->bColumnsize ){
194454      rc = sqlite3Fts5CreateTable(
194455          pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
194456      );
194457    }
194458    if( rc==SQLITE_OK ){
194459      rc = sqlite3Fts5CreateTable(
194460          pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
194461      );
194462    }
194463    if( rc==SQLITE_OK ){
194464      rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
194465    }
194466  }
194467
194468  if( rc ){
194469    sqlite3Fts5StorageClose(p);
194470    *pp = 0;
194471  }
194472  return rc;
194473}
194474
194475/*
194476** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
194477*/
194478static int sqlite3Fts5StorageClose(Fts5Storage *p){
194479  int rc = SQLITE_OK;
194480  if( p ){
194481    int i;
194482
194483    /* Finalize all SQL statements */
194484    for(i=0; i<ArraySize(p->aStmt); i++){
194485      sqlite3_finalize(p->aStmt[i]);
194486    }
194487
194488    sqlite3_free(p);
194489  }
194490  return rc;
194491}
194492
194493typedef struct Fts5InsertCtx Fts5InsertCtx;
194494struct Fts5InsertCtx {
194495  Fts5Storage *pStorage;
194496  int iCol;
194497  int szCol;                      /* Size of column value in tokens */
194498};
194499
194500/*
194501** Tokenization callback used when inserting tokens into the FTS index.
194502*/
194503static int fts5StorageInsertCallback(
194504  void *pContext,                 /* Pointer to Fts5InsertCtx object */
194505  int tflags,
194506  const char *pToken,             /* Buffer containing token */
194507  int nToken,                     /* Size of token in bytes */
194508  int iUnused1,                   /* Start offset of token */
194509  int iUnused2                    /* End offset of token */
194510){
194511  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
194512  Fts5Index *pIdx = pCtx->pStorage->pIndex;
194513  UNUSED_PARAM2(iUnused1, iUnused2);
194514  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
194515  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
194516    pCtx->szCol++;
194517  }
194518  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
194519}
194520
194521/*
194522** If a row with rowid iDel is present in the %_content table, add the
194523** delete-markers to the FTS index necessary to delete it. Do not actually
194524** remove the %_content row at this time though.
194525*/
194526static int fts5StorageDeleteFromIndex(
194527  Fts5Storage *p,
194528  i64 iDel,
194529  sqlite3_value **apVal
194530){
194531  Fts5Config *pConfig = p->pConfig;
194532  sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
194533  int rc;                         /* Return code */
194534  int rc2;                        /* sqlite3_reset() return code */
194535  int iCol;
194536  Fts5InsertCtx ctx;
194537
194538  if( apVal==0 ){
194539    rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
194540    if( rc!=SQLITE_OK ) return rc;
194541    sqlite3_bind_int64(pSeek, 1, iDel);
194542    if( sqlite3_step(pSeek)!=SQLITE_ROW ){
194543      return sqlite3_reset(pSeek);
194544    }
194545  }
194546
194547  ctx.pStorage = p;
194548  ctx.iCol = -1;
194549  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
194550  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
194551    if( pConfig->abUnindexed[iCol-1]==0 ){
194552      const char *zText;
194553      int nText;
194554      if( pSeek ){
194555        zText = (const char*)sqlite3_column_text(pSeek, iCol);
194556        nText = sqlite3_column_bytes(pSeek, iCol);
194557      }else{
194558        zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
194559        nText = sqlite3_value_bytes(apVal[iCol-1]);
194560      }
194561      ctx.szCol = 0;
194562      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
194563          zText, nText, (void*)&ctx, fts5StorageInsertCallback
194564      );
194565      p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
194566    }
194567  }
194568  p->nTotalRow--;
194569
194570  rc2 = sqlite3_reset(pSeek);
194571  if( rc==SQLITE_OK ) rc = rc2;
194572  return rc;
194573}
194574
194575
194576/*
194577** Insert a record into the %_docsize table. Specifically, do:
194578**
194579**   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
194580**
194581** If there is no %_docsize table (as happens if the columnsize=0 option
194582** is specified when the FTS5 table is created), this function is a no-op.
194583*/
194584static int fts5StorageInsertDocsize(
194585  Fts5Storage *p,                 /* Storage module to write to */
194586  i64 iRowid,                     /* id value */
194587  Fts5Buffer *pBuf                /* sz value */
194588){
194589  int rc = SQLITE_OK;
194590  if( p->pConfig->bColumnsize ){
194591    sqlite3_stmt *pReplace = 0;
194592    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
194593    if( rc==SQLITE_OK ){
194594      sqlite3_bind_int64(pReplace, 1, iRowid);
194595      sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
194596      sqlite3_step(pReplace);
194597      rc = sqlite3_reset(pReplace);
194598    }
194599  }
194600  return rc;
194601}
194602
194603/*
194604** Load the contents of the "averages" record from disk into the
194605** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
194606** argument bCache is true, set the p->bTotalsValid flag to indicate
194607** that the contents of aTotalSize[] and nTotalRow are valid until
194608** further notice.
194609**
194610** Return SQLITE_OK if successful, or an SQLite error code if an error
194611** occurs.
194612*/
194613static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
194614  int rc = SQLITE_OK;
194615  if( p->bTotalsValid==0 ){
194616    rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
194617    p->bTotalsValid = bCache;
194618  }
194619  return rc;
194620}
194621
194622/*
194623** Store the current contents of the p->nTotalRow and p->aTotalSize[]
194624** variables in the "averages" record on disk.
194625**
194626** Return SQLITE_OK if successful, or an SQLite error code if an error
194627** occurs.
194628*/
194629static int fts5StorageSaveTotals(Fts5Storage *p){
194630  int nCol = p->pConfig->nCol;
194631  int i;
194632  Fts5Buffer buf;
194633  int rc = SQLITE_OK;
194634  memset(&buf, 0, sizeof(buf));
194635
194636  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
194637  for(i=0; i<nCol; i++){
194638    sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
194639  }
194640  if( rc==SQLITE_OK ){
194641    rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
194642  }
194643  sqlite3_free(buf.p);
194644
194645  return rc;
194646}
194647
194648/*
194649** Remove a row from the FTS table.
194650*/
194651static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
194652  Fts5Config *pConfig = p->pConfig;
194653  int rc;
194654  sqlite3_stmt *pDel = 0;
194655
194656  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
194657  rc = fts5StorageLoadTotals(p, 1);
194658
194659  /* Delete the index records */
194660  if( rc==SQLITE_OK ){
194661    rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
194662  }
194663
194664  /* Delete the %_docsize record */
194665  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194666    rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
194667    if( rc==SQLITE_OK ){
194668      sqlite3_bind_int64(pDel, 1, iDel);
194669      sqlite3_step(pDel);
194670      rc = sqlite3_reset(pDel);
194671    }
194672  }
194673
194674  /* Delete the %_content record */
194675  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194676    if( rc==SQLITE_OK ){
194677      rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
194678    }
194679    if( rc==SQLITE_OK ){
194680      sqlite3_bind_int64(pDel, 1, iDel);
194681      sqlite3_step(pDel);
194682      rc = sqlite3_reset(pDel);
194683    }
194684  }
194685
194686  /* Write the averages record */
194687  if( rc==SQLITE_OK ){
194688    rc = fts5StorageSaveTotals(p);
194689  }
194690
194691  return rc;
194692}
194693
194694/*
194695** Delete all entries in the FTS5 index.
194696*/
194697static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
194698  Fts5Config *pConfig = p->pConfig;
194699  int rc;
194700
194701  /* Delete the contents of the %_data and %_docsize tables. */
194702  rc = fts5ExecPrintf(pConfig->db, 0,
194703      "DELETE FROM %Q.'%q_data';"
194704      "DELETE FROM %Q.'%q_idx';",
194705      pConfig->zDb, pConfig->zName,
194706      pConfig->zDb, pConfig->zName
194707  );
194708  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194709    rc = fts5ExecPrintf(pConfig->db, 0,
194710        "DELETE FROM %Q.'%q_docsize';",
194711        pConfig->zDb, pConfig->zName
194712    );
194713  }
194714
194715  /* Reinitialize the %_data table. This call creates the initial structure
194716  ** and averages records.  */
194717  if( rc==SQLITE_OK ){
194718    rc = sqlite3Fts5IndexReinit(p->pIndex);
194719  }
194720  if( rc==SQLITE_OK ){
194721    rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
194722  }
194723  return rc;
194724}
194725
194726static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
194727  Fts5Buffer buf = {0,0,0};
194728  Fts5Config *pConfig = p->pConfig;
194729  sqlite3_stmt *pScan = 0;
194730  Fts5InsertCtx ctx;
194731  int rc;
194732
194733  memset(&ctx, 0, sizeof(Fts5InsertCtx));
194734  ctx.pStorage = p;
194735  rc = sqlite3Fts5StorageDeleteAll(p);
194736  if( rc==SQLITE_OK ){
194737    rc = fts5StorageLoadTotals(p, 1);
194738  }
194739
194740  if( rc==SQLITE_OK ){
194741    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
194742  }
194743
194744  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
194745    i64 iRowid = sqlite3_column_int64(pScan, 0);
194746
194747    sqlite3Fts5BufferZero(&buf);
194748    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
194749    for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
194750      ctx.szCol = 0;
194751      if( pConfig->abUnindexed[ctx.iCol]==0 ){
194752        rc = sqlite3Fts5Tokenize(pConfig,
194753            FTS5_TOKENIZE_DOCUMENT,
194754            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
194755            sqlite3_column_bytes(pScan, ctx.iCol+1),
194756            (void*)&ctx,
194757            fts5StorageInsertCallback
194758        );
194759      }
194760      sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
194761      p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
194762    }
194763    p->nTotalRow++;
194764
194765    if( rc==SQLITE_OK ){
194766      rc = fts5StorageInsertDocsize(p, iRowid, &buf);
194767    }
194768  }
194769  sqlite3_free(buf.p);
194770
194771  /* Write the averages record */
194772  if( rc==SQLITE_OK ){
194773    rc = fts5StorageSaveTotals(p);
194774  }
194775  return rc;
194776}
194777
194778static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
194779  return sqlite3Fts5IndexOptimize(p->pIndex);
194780}
194781
194782static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
194783  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
194784}
194785
194786static int sqlite3Fts5StorageReset(Fts5Storage *p){
194787  return sqlite3Fts5IndexReset(p->pIndex);
194788}
194789
194790/*
194791** Allocate a new rowid. This is used for "external content" tables when
194792** a NULL value is inserted into the rowid column. The new rowid is allocated
194793** by inserting a dummy row into the %_docsize table. The dummy will be
194794** overwritten later.
194795**
194796** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
194797** this case the user is required to provide a rowid explicitly.
194798*/
194799static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
194800  int rc = SQLITE_MISMATCH;
194801  if( p->pConfig->bColumnsize ){
194802    sqlite3_stmt *pReplace = 0;
194803    rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
194804    if( rc==SQLITE_OK ){
194805      sqlite3_bind_null(pReplace, 1);
194806      sqlite3_bind_null(pReplace, 2);
194807      sqlite3_step(pReplace);
194808      rc = sqlite3_reset(pReplace);
194809    }
194810    if( rc==SQLITE_OK ){
194811      *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
194812    }
194813  }
194814  return rc;
194815}
194816
194817/*
194818** Insert a new row into the FTS content table.
194819*/
194820static int sqlite3Fts5StorageContentInsert(
194821  Fts5Storage *p,
194822  sqlite3_value **apVal,
194823  i64 *piRowid
194824){
194825  Fts5Config *pConfig = p->pConfig;
194826  int rc = SQLITE_OK;
194827
194828  /* Insert the new row into the %_content table. */
194829  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
194830    if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
194831      *piRowid = sqlite3_value_int64(apVal[1]);
194832    }else{
194833      rc = fts5StorageNewRowid(p, piRowid);
194834    }
194835  }else{
194836    sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
194837    int i;                        /* Counter variable */
194838    rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
194839    for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
194840      rc = sqlite3_bind_value(pInsert, i, apVal[i]);
194841    }
194842    if( rc==SQLITE_OK ){
194843      sqlite3_step(pInsert);
194844      rc = sqlite3_reset(pInsert);
194845    }
194846    *piRowid = sqlite3_last_insert_rowid(pConfig->db);
194847  }
194848
194849  return rc;
194850}
194851
194852/*
194853** Insert new entries into the FTS index and %_docsize table.
194854*/
194855static int sqlite3Fts5StorageIndexInsert(
194856  Fts5Storage *p,
194857  sqlite3_value **apVal,
194858  i64 iRowid
194859){
194860  Fts5Config *pConfig = p->pConfig;
194861  int rc = SQLITE_OK;             /* Return code */
194862  Fts5InsertCtx ctx;              /* Tokenization callback context object */
194863  Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
194864
194865  memset(&buf, 0, sizeof(Fts5Buffer));
194866  ctx.pStorage = p;
194867  rc = fts5StorageLoadTotals(p, 1);
194868
194869  if( rc==SQLITE_OK ){
194870    rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
194871  }
194872  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
194873    ctx.szCol = 0;
194874    if( pConfig->abUnindexed[ctx.iCol]==0 ){
194875      rc = sqlite3Fts5Tokenize(pConfig,
194876          FTS5_TOKENIZE_DOCUMENT,
194877          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
194878          sqlite3_value_bytes(apVal[ctx.iCol+2]),
194879          (void*)&ctx,
194880          fts5StorageInsertCallback
194881      );
194882    }
194883    sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
194884    p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
194885  }
194886  p->nTotalRow++;
194887
194888  /* Write the %_docsize record */
194889  if( rc==SQLITE_OK ){
194890    rc = fts5StorageInsertDocsize(p, iRowid, &buf);
194891  }
194892  sqlite3_free(buf.p);
194893
194894  /* Write the averages record */
194895  if( rc==SQLITE_OK ){
194896    rc = fts5StorageSaveTotals(p);
194897  }
194898
194899  return rc;
194900}
194901
194902static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
194903  Fts5Config *pConfig = p->pConfig;
194904  char *zSql;
194905  int rc;
194906
194907  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
194908      pConfig->zDb, pConfig->zName, zSuffix
194909  );
194910  if( zSql==0 ){
194911    rc = SQLITE_NOMEM;
194912  }else{
194913    sqlite3_stmt *pCnt = 0;
194914    rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
194915    if( rc==SQLITE_OK ){
194916      if( SQLITE_ROW==sqlite3_step(pCnt) ){
194917        *pnRow = sqlite3_column_int64(pCnt, 0);
194918      }
194919      rc = sqlite3_finalize(pCnt);
194920    }
194921  }
194922
194923  sqlite3_free(zSql);
194924  return rc;
194925}
194926
194927/*
194928** Context object used by sqlite3Fts5StorageIntegrity().
194929*/
194930typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
194931struct Fts5IntegrityCtx {
194932  i64 iRowid;
194933  int iCol;
194934  int szCol;
194935  u64 cksum;
194936  Fts5Termset *pTermset;
194937  Fts5Config *pConfig;
194938};
194939
194940
194941/*
194942** Tokenization callback used by integrity check.
194943*/
194944static int fts5StorageIntegrityCallback(
194945  void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
194946  int tflags,
194947  const char *pToken,             /* Buffer containing token */
194948  int nToken,                     /* Size of token in bytes */
194949  int iUnused1,                   /* Start offset of token */
194950  int iUnused2                    /* End offset of token */
194951){
194952  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
194953  Fts5Termset *pTermset = pCtx->pTermset;
194954  int bPresent;
194955  int ii;
194956  int rc = SQLITE_OK;
194957  int iPos;
194958  int iCol;
194959
194960  UNUSED_PARAM2(iUnused1, iUnused2);
194961  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
194962
194963  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
194964    pCtx->szCol++;
194965  }
194966
194967  switch( pCtx->pConfig->eDetail ){
194968    case FTS5_DETAIL_FULL:
194969      iPos = pCtx->szCol-1;
194970      iCol = pCtx->iCol;
194971      break;
194972
194973    case FTS5_DETAIL_COLUMNS:
194974      iPos = pCtx->iCol;
194975      iCol = 0;
194976      break;
194977
194978    default:
194979      assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
194980      iPos = 0;
194981      iCol = 0;
194982      break;
194983  }
194984
194985  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
194986  if( rc==SQLITE_OK && bPresent==0 ){
194987    pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
194988        pCtx->iRowid, iCol, iPos, 0, pToken, nToken
194989    );
194990  }
194991
194992  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
194993    const int nChar = pCtx->pConfig->aPrefix[ii];
194994    int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
194995    if( nByte ){
194996      rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
194997      if( bPresent==0 ){
194998        pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
194999            pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
195000        );
195001      }
195002    }
195003  }
195004
195005  return rc;
195006}
195007
195008/*
195009** Check that the contents of the FTS index match that of the %_content
195010** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
195011** some other SQLite error code if an error occurs while attempting to
195012** determine this.
195013*/
195014static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
195015  Fts5Config *pConfig = p->pConfig;
195016  int rc;                         /* Return code */
195017  int *aColSize;                  /* Array of size pConfig->nCol */
195018  i64 *aTotalSize;                /* Array of size pConfig->nCol */
195019  Fts5IntegrityCtx ctx;
195020  sqlite3_stmt *pScan;
195021
195022  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
195023  ctx.pConfig = p->pConfig;
195024  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
195025  if( !aTotalSize ) return SQLITE_NOMEM;
195026  aColSize = (int*)&aTotalSize[pConfig->nCol];
195027  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
195028
195029  /* Generate the expected index checksum based on the contents of the
195030  ** %_content table. This block stores the checksum in ctx.cksum. */
195031  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
195032  if( rc==SQLITE_OK ){
195033    int rc2;
195034    while( SQLITE_ROW==sqlite3_step(pScan) ){
195035      int i;
195036      ctx.iRowid = sqlite3_column_int64(pScan, 0);
195037      ctx.szCol = 0;
195038      if( pConfig->bColumnsize ){
195039        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
195040      }
195041      if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
195042        rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
195043      }
195044      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
195045        if( pConfig->abUnindexed[i] ) continue;
195046        ctx.iCol = i;
195047        ctx.szCol = 0;
195048        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195049          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
195050        }
195051        if( rc==SQLITE_OK ){
195052          rc = sqlite3Fts5Tokenize(pConfig,
195053              FTS5_TOKENIZE_DOCUMENT,
195054              (const char*)sqlite3_column_text(pScan, i+1),
195055              sqlite3_column_bytes(pScan, i+1),
195056              (void*)&ctx,
195057              fts5StorageIntegrityCallback
195058          );
195059        }
195060        if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
195061          rc = FTS5_CORRUPT;
195062        }
195063        aTotalSize[i] += ctx.szCol;
195064        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195065          sqlite3Fts5TermsetFree(ctx.pTermset);
195066          ctx.pTermset = 0;
195067        }
195068      }
195069      sqlite3Fts5TermsetFree(ctx.pTermset);
195070      ctx.pTermset = 0;
195071
195072      if( rc!=SQLITE_OK ) break;
195073    }
195074    rc2 = sqlite3_reset(pScan);
195075    if( rc==SQLITE_OK ) rc = rc2;
195076  }
195077
195078  /* Test that the "totals" (sometimes called "averages") record looks Ok */
195079  if( rc==SQLITE_OK ){
195080    int i;
195081    rc = fts5StorageLoadTotals(p, 0);
195082    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
195083      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
195084    }
195085  }
195086
195087  /* Check that the %_docsize and %_content tables contain the expected
195088  ** number of rows.  */
195089  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
195090    i64 nRow = 0;
195091    rc = fts5StorageCount(p, "content", &nRow);
195092    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
195093  }
195094  if( rc==SQLITE_OK && pConfig->bColumnsize ){
195095    i64 nRow = 0;
195096    rc = fts5StorageCount(p, "docsize", &nRow);
195097    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
195098  }
195099
195100  /* Pass the expected checksum down to the FTS index module. It will
195101  ** verify, amongst other things, that it matches the checksum generated by
195102  ** inspecting the index itself.  */
195103  if( rc==SQLITE_OK ){
195104    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
195105  }
195106
195107  sqlite3_free(aTotalSize);
195108  return rc;
195109}
195110
195111/*
195112** Obtain an SQLite statement handle that may be used to read data from the
195113** %_content table.
195114*/
195115static int sqlite3Fts5StorageStmt(
195116  Fts5Storage *p,
195117  int eStmt,
195118  sqlite3_stmt **pp,
195119  char **pzErrMsg
195120){
195121  int rc;
195122  assert( eStmt==FTS5_STMT_SCAN_ASC
195123       || eStmt==FTS5_STMT_SCAN_DESC
195124       || eStmt==FTS5_STMT_LOOKUP
195125  );
195126  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
195127  if( rc==SQLITE_OK ){
195128    assert( p->aStmt[eStmt]==*pp );
195129    p->aStmt[eStmt] = 0;
195130  }
195131  return rc;
195132}
195133
195134/*
195135** Release an SQLite statement handle obtained via an earlier call to
195136** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
195137** must match that passed to the sqlite3Fts5StorageStmt() call.
195138*/
195139static void sqlite3Fts5StorageStmtRelease(
195140  Fts5Storage *p,
195141  int eStmt,
195142  sqlite3_stmt *pStmt
195143){
195144  assert( eStmt==FTS5_STMT_SCAN_ASC
195145       || eStmt==FTS5_STMT_SCAN_DESC
195146       || eStmt==FTS5_STMT_LOOKUP
195147  );
195148  if( p->aStmt[eStmt]==0 ){
195149    sqlite3_reset(pStmt);
195150    p->aStmt[eStmt] = pStmt;
195151  }else{
195152    sqlite3_finalize(pStmt);
195153  }
195154}
195155
195156static int fts5StorageDecodeSizeArray(
195157  int *aCol, int nCol,            /* Array to populate */
195158  const u8 *aBlob, int nBlob      /* Record to read varints from */
195159){
195160  int i;
195161  int iOff = 0;
195162  for(i=0; i<nCol; i++){
195163    if( iOff>=nBlob ) return 1;
195164    iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
195165  }
195166  return (iOff!=nBlob);
195167}
195168
195169/*
195170** Argument aCol points to an array of integers containing one entry for
195171** each table column. This function reads the %_docsize record for the
195172** specified rowid and populates aCol[] with the results.
195173**
195174** An SQLite error code is returned if an error occurs, or SQLITE_OK
195175** otherwise.
195176*/
195177static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
195178  int nCol = p->pConfig->nCol;    /* Number of user columns in table */
195179  sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
195180  int rc;                         /* Return Code */
195181
195182  assert( p->pConfig->bColumnsize );
195183  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
195184  if( rc==SQLITE_OK ){
195185    int bCorrupt = 1;
195186    sqlite3_bind_int64(pLookup, 1, iRowid);
195187    if( SQLITE_ROW==sqlite3_step(pLookup) ){
195188      const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
195189      int nBlob = sqlite3_column_bytes(pLookup, 0);
195190      if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
195191        bCorrupt = 0;
195192      }
195193    }
195194    rc = sqlite3_reset(pLookup);
195195    if( bCorrupt && rc==SQLITE_OK ){
195196      rc = FTS5_CORRUPT;
195197    }
195198  }
195199
195200  return rc;
195201}
195202
195203static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
195204  int rc = fts5StorageLoadTotals(p, 0);
195205  if( rc==SQLITE_OK ){
195206    *pnToken = 0;
195207    if( iCol<0 ){
195208      int i;
195209      for(i=0; i<p->pConfig->nCol; i++){
195210        *pnToken += p->aTotalSize[i];
195211      }
195212    }else if( iCol<p->pConfig->nCol ){
195213      *pnToken = p->aTotalSize[iCol];
195214    }else{
195215      rc = SQLITE_RANGE;
195216    }
195217  }
195218  return rc;
195219}
195220
195221static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
195222  int rc = fts5StorageLoadTotals(p, 0);
195223  if( rc==SQLITE_OK ){
195224    *pnRow = p->nTotalRow;
195225  }
195226  return rc;
195227}
195228
195229/*
195230** Flush any data currently held in-memory to disk.
195231*/
195232static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
195233  if( bCommit && p->bTotalsValid ){
195234    int rc = fts5StorageSaveTotals(p);
195235    p->bTotalsValid = 0;
195236    if( rc!=SQLITE_OK ) return rc;
195237  }
195238  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
195239}
195240
195241static int sqlite3Fts5StorageRollback(Fts5Storage *p){
195242  p->bTotalsValid = 0;
195243  return sqlite3Fts5IndexRollback(p->pIndex);
195244}
195245
195246static int sqlite3Fts5StorageConfigValue(
195247  Fts5Storage *p,
195248  const char *z,
195249  sqlite3_value *pVal,
195250  int iVal
195251){
195252  sqlite3_stmt *pReplace = 0;
195253  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
195254  if( rc==SQLITE_OK ){
195255    sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
195256    if( pVal ){
195257      sqlite3_bind_value(pReplace, 2, pVal);
195258    }else{
195259      sqlite3_bind_int(pReplace, 2, iVal);
195260    }
195261    sqlite3_step(pReplace);
195262    rc = sqlite3_reset(pReplace);
195263  }
195264  if( rc==SQLITE_OK && pVal ){
195265    int iNew = p->pConfig->iCookie + 1;
195266    rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
195267    if( rc==SQLITE_OK ){
195268      p->pConfig->iCookie = iNew;
195269    }
195270  }
195271  return rc;
195272}
195273
195274/*
195275** 2014 May 31
195276**
195277** The author disclaims copyright to this source code.  In place of
195278** a legal notice, here is a blessing:
195279**
195280**    May you do good and not evil.
195281**    May you find forgiveness for yourself and forgive others.
195282**    May you share freely, never taking more than you give.
195283**
195284******************************************************************************
195285*/
195286
195287
195288/* #include "fts5Int.h" */
195289
195290/**************************************************************************
195291** Start of ascii tokenizer implementation.
195292*/
195293
195294/*
195295** For tokenizers with no "unicode" modifier, the set of token characters
195296** is the same as the set of ASCII range alphanumeric characters.
195297*/
195298static unsigned char aAsciiTokenChar[128] = {
195299  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
195300  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
195301  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
195302  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
195303  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
195304  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
195305  0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
195306  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
195307};
195308
195309typedef struct AsciiTokenizer AsciiTokenizer;
195310struct AsciiTokenizer {
195311  unsigned char aTokenChar[128];
195312};
195313
195314static void fts5AsciiAddExceptions(
195315  AsciiTokenizer *p,
195316  const char *zArg,
195317  int bTokenChars
195318){
195319  int i;
195320  for(i=0; zArg[i]; i++){
195321    if( (zArg[i] & 0x80)==0 ){
195322      p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
195323    }
195324  }
195325}
195326
195327/*
195328** Delete a "ascii" tokenizer.
195329*/
195330static void fts5AsciiDelete(Fts5Tokenizer *p){
195331  sqlite3_free(p);
195332}
195333
195334/*
195335** Create an "ascii" tokenizer.
195336*/
195337static int fts5AsciiCreate(
195338  void *pUnused,
195339  const char **azArg, int nArg,
195340  Fts5Tokenizer **ppOut
195341){
195342  int rc = SQLITE_OK;
195343  AsciiTokenizer *p = 0;
195344  UNUSED_PARAM(pUnused);
195345  if( nArg%2 ){
195346    rc = SQLITE_ERROR;
195347  }else{
195348    p = sqlite3_malloc(sizeof(AsciiTokenizer));
195349    if( p==0 ){
195350      rc = SQLITE_NOMEM;
195351    }else{
195352      int i;
195353      memset(p, 0, sizeof(AsciiTokenizer));
195354      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
195355      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
195356        const char *zArg = azArg[i+1];
195357        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
195358          fts5AsciiAddExceptions(p, zArg, 1);
195359        }else
195360        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
195361          fts5AsciiAddExceptions(p, zArg, 0);
195362        }else{
195363          rc = SQLITE_ERROR;
195364        }
195365      }
195366      if( rc!=SQLITE_OK ){
195367        fts5AsciiDelete((Fts5Tokenizer*)p);
195368        p = 0;
195369      }
195370    }
195371  }
195372
195373  *ppOut = (Fts5Tokenizer*)p;
195374  return rc;
195375}
195376
195377
195378static void asciiFold(char *aOut, const char *aIn, int nByte){
195379  int i;
195380  for(i=0; i<nByte; i++){
195381    char c = aIn[i];
195382    if( c>='A' && c<='Z' ) c += 32;
195383    aOut[i] = c;
195384  }
195385}
195386
195387/*
195388** Tokenize some text using the ascii tokenizer.
195389*/
195390static int fts5AsciiTokenize(
195391  Fts5Tokenizer *pTokenizer,
195392  void *pCtx,
195393  int iUnused,
195394  const char *pText, int nText,
195395  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195396){
195397  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
195398  int rc = SQLITE_OK;
195399  int ie;
195400  int is = 0;
195401
195402  char aFold[64];
195403  int nFold = sizeof(aFold);
195404  char *pFold = aFold;
195405  unsigned char *a = p->aTokenChar;
195406
195407  UNUSED_PARAM(iUnused);
195408
195409  while( is<nText && rc==SQLITE_OK ){
195410    int nByte;
195411
195412    /* Skip any leading divider characters. */
195413    while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
195414      is++;
195415    }
195416    if( is==nText ) break;
195417
195418    /* Count the token characters */
195419    ie = is+1;
195420    while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
195421      ie++;
195422    }
195423
195424    /* Fold to lower case */
195425    nByte = ie-is;
195426    if( nByte>nFold ){
195427      if( pFold!=aFold ) sqlite3_free(pFold);
195428      pFold = sqlite3_malloc(nByte*2);
195429      if( pFold==0 ){
195430        rc = SQLITE_NOMEM;
195431        break;
195432      }
195433      nFold = nByte*2;
195434    }
195435    asciiFold(pFold, &pText[is], nByte);
195436
195437    /* Invoke the token callback */
195438    rc = xToken(pCtx, 0, pFold, nByte, is, ie);
195439    is = ie+1;
195440  }
195441
195442  if( pFold!=aFold ) sqlite3_free(pFold);
195443  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195444  return rc;
195445}
195446
195447/**************************************************************************
195448** Start of unicode61 tokenizer implementation.
195449*/
195450
195451
195452/*
195453** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
195454** from the sqlite3 source file utf.c. If this file is compiled as part
195455** of the amalgamation, they are not required.
195456*/
195457#ifndef SQLITE_AMALGAMATION
195458
195459static const unsigned char sqlite3Utf8Trans1[] = {
195460  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195461  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
195462  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
195463  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
195464  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195465  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
195466  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195467  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
195468};
195469
195470#define READ_UTF8(zIn, zTerm, c)                           \
195471  c = *(zIn++);                                            \
195472  if( c>=0xc0 ){                                           \
195473    c = sqlite3Utf8Trans1[c-0xc0];                         \
195474    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
195475      c = (c<<6) + (0x3f & *(zIn++));                      \
195476    }                                                      \
195477    if( c<0x80                                             \
195478        || (c&0xFFFFF800)==0xD800                          \
195479        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
195480  }
195481
195482
195483#define WRITE_UTF8(zOut, c) {                          \
195484  if( c<0x00080 ){                                     \
195485    *zOut++ = (unsigned char)(c&0xFF);                 \
195486  }                                                    \
195487  else if( c<0x00800 ){                                \
195488    *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
195489    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195490  }                                                    \
195491  else if( c<0x10000 ){                                \
195492    *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
195493    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
195494    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195495  }else{                                               \
195496    *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
195497    *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
195498    *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
195499    *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195500  }                                                    \
195501}
195502
195503#endif /* ifndef SQLITE_AMALGAMATION */
195504
195505typedef struct Unicode61Tokenizer Unicode61Tokenizer;
195506struct Unicode61Tokenizer {
195507  unsigned char aTokenChar[128];  /* ASCII range token characters */
195508  char *aFold;                    /* Buffer to fold text into */
195509  int nFold;                      /* Size of aFold[] in bytes */
195510  int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
195511  int nException;
195512  int *aiException;
195513};
195514
195515static int fts5UnicodeAddExceptions(
195516  Unicode61Tokenizer *p,          /* Tokenizer object */
195517  const char *z,                  /* Characters to treat as exceptions */
195518  int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
195519){
195520  int rc = SQLITE_OK;
195521  int n = (int)strlen(z);
195522  int *aNew;
195523
195524  if( n>0 ){
195525    aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
195526    if( aNew ){
195527      int nNew = p->nException;
195528      const unsigned char *zCsr = (const unsigned char*)z;
195529      const unsigned char *zTerm = (const unsigned char*)&z[n];
195530      while( zCsr<zTerm ){
195531        int iCode;
195532        int bToken;
195533        READ_UTF8(zCsr, zTerm, iCode);
195534        if( iCode<128 ){
195535          p->aTokenChar[iCode] = (unsigned char)bTokenChars;
195536        }else{
195537          bToken = sqlite3Fts5UnicodeIsalnum(iCode);
195538          assert( (bToken==0 || bToken==1) );
195539          assert( (bTokenChars==0 || bTokenChars==1) );
195540          if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
195541            int i;
195542            for(i=0; i<nNew; i++){
195543              if( aNew[i]>iCode ) break;
195544            }
195545            memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
195546            aNew[i] = iCode;
195547            nNew++;
195548          }
195549        }
195550      }
195551      p->aiException = aNew;
195552      p->nException = nNew;
195553    }else{
195554      rc = SQLITE_NOMEM;
195555    }
195556  }
195557
195558  return rc;
195559}
195560
195561/*
195562** Return true if the p->aiException[] array contains the value iCode.
195563*/
195564static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
195565  if( p->nException>0 ){
195566    int *a = p->aiException;
195567    int iLo = 0;
195568    int iHi = p->nException-1;
195569
195570    while( iHi>=iLo ){
195571      int iTest = (iHi + iLo) / 2;
195572      if( iCode==a[iTest] ){
195573        return 1;
195574      }else if( iCode>a[iTest] ){
195575        iLo = iTest+1;
195576      }else{
195577        iHi = iTest-1;
195578      }
195579    }
195580  }
195581
195582  return 0;
195583}
195584
195585/*
195586** Delete a "unicode61" tokenizer.
195587*/
195588static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
195589  if( pTok ){
195590    Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
195591    sqlite3_free(p->aiException);
195592    sqlite3_free(p->aFold);
195593    sqlite3_free(p);
195594  }
195595  return;
195596}
195597
195598/*
195599** Create a "unicode61" tokenizer.
195600*/
195601static int fts5UnicodeCreate(
195602  void *pUnused,
195603  const char **azArg, int nArg,
195604  Fts5Tokenizer **ppOut
195605){
195606  int rc = SQLITE_OK;             /* Return code */
195607  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
195608
195609  UNUSED_PARAM(pUnused);
195610
195611  if( nArg%2 ){
195612    rc = SQLITE_ERROR;
195613  }else{
195614    p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
195615    if( p ){
195616      int i;
195617      memset(p, 0, sizeof(Unicode61Tokenizer));
195618      memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
195619      p->bRemoveDiacritic = 1;
195620      p->nFold = 64;
195621      p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
195622      if( p->aFold==0 ){
195623        rc = SQLITE_NOMEM;
195624      }
195625      for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
195626        const char *zArg = azArg[i+1];
195627        if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
195628          if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
195629            rc = SQLITE_ERROR;
195630          }
195631          p->bRemoveDiacritic = (zArg[0]=='1');
195632        }else
195633        if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
195634          rc = fts5UnicodeAddExceptions(p, zArg, 1);
195635        }else
195636        if( 0==sqlite3_stricmp(azArg[i], "separators") ){
195637          rc = fts5UnicodeAddExceptions(p, zArg, 0);
195638        }else{
195639          rc = SQLITE_ERROR;
195640        }
195641      }
195642    }else{
195643      rc = SQLITE_NOMEM;
195644    }
195645    if( rc!=SQLITE_OK ){
195646      fts5UnicodeDelete((Fts5Tokenizer*)p);
195647      p = 0;
195648    }
195649    *ppOut = (Fts5Tokenizer*)p;
195650  }
195651  return rc;
195652}
195653
195654/*
195655** Return true if, for the purposes of tokenizing with the tokenizer
195656** passed as the first argument, codepoint iCode is considered a token
195657** character (not a separator).
195658*/
195659static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
195660  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
195661  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
195662}
195663
195664static int fts5UnicodeTokenize(
195665  Fts5Tokenizer *pTokenizer,
195666  void *pCtx,
195667  int iUnused,
195668  const char *pText, int nText,
195669  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195670){
195671  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
195672  int rc = SQLITE_OK;
195673  unsigned char *a = p->aTokenChar;
195674
195675  unsigned char *zTerm = (unsigned char*)&pText[nText];
195676  unsigned char *zCsr = (unsigned char *)pText;
195677
195678  /* Output buffer */
195679  char *aFold = p->aFold;
195680  int nFold = p->nFold;
195681  const char *pEnd = &aFold[nFold-6];
195682
195683  UNUSED_PARAM(iUnused);
195684
195685  /* Each iteration of this loop gobbles up a contiguous run of separators,
195686  ** then the next token.  */
195687  while( rc==SQLITE_OK ){
195688    int iCode;                    /* non-ASCII codepoint read from input */
195689    char *zOut = aFold;
195690    int is;
195691    int ie;
195692
195693    /* Skip any separator characters. */
195694    while( 1 ){
195695      if( zCsr>=zTerm ) goto tokenize_done;
195696      if( *zCsr & 0x80 ) {
195697        /* A character outside of the ascii range. Skip past it if it is
195698        ** a separator character. Or break out of the loop if it is not. */
195699        is = zCsr - (unsigned char*)pText;
195700        READ_UTF8(zCsr, zTerm, iCode);
195701        if( fts5UnicodeIsAlnum(p, iCode) ){
195702          goto non_ascii_tokenchar;
195703        }
195704      }else{
195705        if( a[*zCsr] ){
195706          is = zCsr - (unsigned char*)pText;
195707          goto ascii_tokenchar;
195708        }
195709        zCsr++;
195710      }
195711    }
195712
195713    /* Run through the tokenchars. Fold them into the output buffer along
195714    ** the way.  */
195715    while( zCsr<zTerm ){
195716
195717      /* Grow the output buffer so that there is sufficient space to fit the
195718      ** largest possible utf-8 character.  */
195719      if( zOut>pEnd ){
195720        aFold = sqlite3_malloc(nFold*2);
195721        if( aFold==0 ){
195722          rc = SQLITE_NOMEM;
195723          goto tokenize_done;
195724        }
195725        zOut = &aFold[zOut - p->aFold];
195726        memcpy(aFold, p->aFold, nFold);
195727        sqlite3_free(p->aFold);
195728        p->aFold = aFold;
195729        p->nFold = nFold = nFold*2;
195730        pEnd = &aFold[nFold-6];
195731      }
195732
195733      if( *zCsr & 0x80 ){
195734        /* An non-ascii-range character. Fold it into the output buffer if
195735        ** it is a token character, or break out of the loop if it is not. */
195736        READ_UTF8(zCsr, zTerm, iCode);
195737        if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
195738 non_ascii_tokenchar:
195739          iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
195740          if( iCode ) WRITE_UTF8(zOut, iCode);
195741        }else{
195742          break;
195743        }
195744      }else if( a[*zCsr]==0 ){
195745        /* An ascii-range separator character. End of token. */
195746        break;
195747      }else{
195748 ascii_tokenchar:
195749        if( *zCsr>='A' && *zCsr<='Z' ){
195750          *zOut++ = *zCsr + 32;
195751        }else{
195752          *zOut++ = *zCsr;
195753        }
195754        zCsr++;
195755      }
195756      ie = zCsr - (unsigned char*)pText;
195757    }
195758
195759    /* Invoke the token callback */
195760    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
195761  }
195762
195763 tokenize_done:
195764  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195765  return rc;
195766}
195767
195768/**************************************************************************
195769** Start of porter stemmer implementation.
195770*/
195771
195772/* Any tokens larger than this (in bytes) are passed through without
195773** stemming. */
195774#define FTS5_PORTER_MAX_TOKEN 64
195775
195776typedef struct PorterTokenizer PorterTokenizer;
195777struct PorterTokenizer {
195778  fts5_tokenizer tokenizer;       /* Parent tokenizer module */
195779  Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
195780  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
195781};
195782
195783/*
195784** Delete a "porter" tokenizer.
195785*/
195786static void fts5PorterDelete(Fts5Tokenizer *pTok){
195787  if( pTok ){
195788    PorterTokenizer *p = (PorterTokenizer*)pTok;
195789    if( p->pTokenizer ){
195790      p->tokenizer.xDelete(p->pTokenizer);
195791    }
195792    sqlite3_free(p);
195793  }
195794}
195795
195796/*
195797** Create a "porter" tokenizer.
195798*/
195799static int fts5PorterCreate(
195800  void *pCtx,
195801  const char **azArg, int nArg,
195802  Fts5Tokenizer **ppOut
195803){
195804  fts5_api *pApi = (fts5_api*)pCtx;
195805  int rc = SQLITE_OK;
195806  PorterTokenizer *pRet;
195807  void *pUserdata = 0;
195808  const char *zBase = "unicode61";
195809
195810  if( nArg>0 ){
195811    zBase = azArg[0];
195812  }
195813
195814  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
195815  if( pRet ){
195816    memset(pRet, 0, sizeof(PorterTokenizer));
195817    rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
195818  }else{
195819    rc = SQLITE_NOMEM;
195820  }
195821  if( rc==SQLITE_OK ){
195822    int nArg2 = (nArg>0 ? nArg-1 : 0);
195823    const char **azArg2 = (nArg2 ? &azArg[1] : 0);
195824    rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
195825  }
195826
195827  if( rc!=SQLITE_OK ){
195828    fts5PorterDelete((Fts5Tokenizer*)pRet);
195829    pRet = 0;
195830  }
195831  *ppOut = (Fts5Tokenizer*)pRet;
195832  return rc;
195833}
195834
195835typedef struct PorterContext PorterContext;
195836struct PorterContext {
195837  void *pCtx;
195838  int (*xToken)(void*, int, const char*, int, int, int);
195839  char *aBuf;
195840};
195841
195842typedef struct PorterRule PorterRule;
195843struct PorterRule {
195844  const char *zSuffix;
195845  int nSuffix;
195846  int (*xCond)(char *zStem, int nStem);
195847  const char *zOutput;
195848  int nOutput;
195849};
195850
195851#if 0
195852static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
195853  int ret = -1;
195854  int nBuf = *pnBuf;
195855  PorterRule *p;
195856
195857  for(p=aRule; p->zSuffix; p++){
195858    assert( strlen(p->zSuffix)==p->nSuffix );
195859    assert( strlen(p->zOutput)==p->nOutput );
195860    if( nBuf<p->nSuffix ) continue;
195861    if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
195862  }
195863
195864  if( p->zSuffix ){
195865    int nStem = nBuf - p->nSuffix;
195866    if( p->xCond==0 || p->xCond(aBuf, nStem) ){
195867      memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
195868      *pnBuf = nStem + p->nOutput;
195869      ret = p - aRule;
195870    }
195871  }
195872
195873  return ret;
195874}
195875#endif
195876
195877static int fts5PorterIsVowel(char c, int bYIsVowel){
195878  return (
195879      c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
195880  );
195881}
195882
195883static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
195884  int i;
195885  int bCons = bPrevCons;
195886
195887  /* Scan for a vowel */
195888  for(i=0; i<nStem; i++){
195889    if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
195890  }
195891
195892  /* Scan for a consonent */
195893  for(i++; i<nStem; i++){
195894    if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
195895  }
195896  return 0;
195897}
195898
195899/* porter rule condition: (m > 0) */
195900static int fts5Porter_MGt0(char *zStem, int nStem){
195901  return !!fts5PorterGobbleVC(zStem, nStem, 0);
195902}
195903
195904/* porter rule condition: (m > 1) */
195905static int fts5Porter_MGt1(char *zStem, int nStem){
195906  int n;
195907  n = fts5PorterGobbleVC(zStem, nStem, 0);
195908  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
195909    return 1;
195910  }
195911  return 0;
195912}
195913
195914/* porter rule condition: (m = 1) */
195915static int fts5Porter_MEq1(char *zStem, int nStem){
195916  int n;
195917  n = fts5PorterGobbleVC(zStem, nStem, 0);
195918  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
195919    return 1;
195920  }
195921  return 0;
195922}
195923
195924/* porter rule condition: (*o) */
195925static int fts5Porter_Ostar(char *zStem, int nStem){
195926  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
195927    return 0;
195928  }else{
195929    int i;
195930    int mask = 0;
195931    int bCons = 0;
195932    for(i=0; i<nStem; i++){
195933      bCons = !fts5PorterIsVowel(zStem[i], bCons);
195934      assert( bCons==0 || bCons==1 );
195935      mask = (mask << 1) + bCons;
195936    }
195937    return ((mask & 0x0007)==0x0005);
195938  }
195939}
195940
195941/* porter rule condition: (m > 1 and (*S or *T)) */
195942static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
195943  assert( nStem>0 );
195944  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
195945      && fts5Porter_MGt1(zStem, nStem);
195946}
195947
195948/* porter rule condition: (*v*) */
195949static int fts5Porter_Vowel(char *zStem, int nStem){
195950  int i;
195951  for(i=0; i<nStem; i++){
195952    if( fts5PorterIsVowel(zStem[i], i>0) ){
195953      return 1;
195954    }
195955  }
195956  return 0;
195957}
195958
195959
195960/**************************************************************************
195961***************************************************************************
195962** GENERATED CODE STARTS HERE (mkportersteps.tcl)
195963*/
195964
195965static int fts5PorterStep4(char *aBuf, int *pnBuf){
195966  int ret = 0;
195967  int nBuf = *pnBuf;
195968  switch( aBuf[nBuf-2] ){
195969
195970    case 'a':
195971      if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
195972        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
195973          *pnBuf = nBuf - 2;
195974        }
195975      }
195976      break;
195977
195978    case 'c':
195979      if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
195980        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
195981          *pnBuf = nBuf - 4;
195982        }
195983      }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
195984        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
195985          *pnBuf = nBuf - 4;
195986        }
195987      }
195988      break;
195989
195990    case 'e':
195991      if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
195992        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
195993          *pnBuf = nBuf - 2;
195994        }
195995      }
195996      break;
195997
195998    case 'i':
195999      if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
196000        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
196001          *pnBuf = nBuf - 2;
196002        }
196003      }
196004      break;
196005
196006    case 'l':
196007      if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
196008        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196009          *pnBuf = nBuf - 4;
196010        }
196011      }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
196012        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196013          *pnBuf = nBuf - 4;
196014        }
196015      }
196016      break;
196017
196018    case 'n':
196019      if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
196020        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196021          *pnBuf = nBuf - 3;
196022        }
196023      }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
196024        if( fts5Porter_MGt1(aBuf, nBuf-5) ){
196025          *pnBuf = nBuf - 5;
196026        }
196027      }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
196028        if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196029          *pnBuf = nBuf - 4;
196030        }
196031      }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
196032        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196033          *pnBuf = nBuf - 3;
196034        }
196035      }
196036      break;
196037
196038    case 'o':
196039      if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
196040        if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
196041          *pnBuf = nBuf - 3;
196042        }
196043      }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
196044        if( fts5Porter_MGt1(aBuf, nBuf-2) ){
196045          *pnBuf = nBuf - 2;
196046        }
196047      }
196048      break;
196049
196050    case 's':
196051      if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
196052        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196053          *pnBuf = nBuf - 3;
196054        }
196055      }
196056      break;
196057
196058    case 't':
196059      if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
196060        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196061          *pnBuf = nBuf - 3;
196062        }
196063      }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
196064        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196065          *pnBuf = nBuf - 3;
196066        }
196067      }
196068      break;
196069
196070    case 'u':
196071      if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
196072        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196073          *pnBuf = nBuf - 3;
196074        }
196075      }
196076      break;
196077
196078    case 'v':
196079      if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
196080        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196081          *pnBuf = nBuf - 3;
196082        }
196083      }
196084      break;
196085
196086    case 'z':
196087      if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
196088        if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196089          *pnBuf = nBuf - 3;
196090        }
196091      }
196092      break;
196093
196094  }
196095  return ret;
196096}
196097
196098
196099static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
196100  int ret = 0;
196101  int nBuf = *pnBuf;
196102  switch( aBuf[nBuf-2] ){
196103
196104    case 'a':
196105      if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
196106        memcpy(&aBuf[nBuf-2], "ate", 3);
196107        *pnBuf = nBuf - 2 + 3;
196108        ret = 1;
196109      }
196110      break;
196111
196112    case 'b':
196113      if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
196114        memcpy(&aBuf[nBuf-2], "ble", 3);
196115        *pnBuf = nBuf - 2 + 3;
196116        ret = 1;
196117      }
196118      break;
196119
196120    case 'i':
196121      if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
196122        memcpy(&aBuf[nBuf-2], "ize", 3);
196123        *pnBuf = nBuf - 2 + 3;
196124        ret = 1;
196125      }
196126      break;
196127
196128  }
196129  return ret;
196130}
196131
196132
196133static int fts5PorterStep2(char *aBuf, int *pnBuf){
196134  int ret = 0;
196135  int nBuf = *pnBuf;
196136  switch( aBuf[nBuf-2] ){
196137
196138    case 'a':
196139      if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
196140        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196141          memcpy(&aBuf[nBuf-7], "ate", 3);
196142          *pnBuf = nBuf - 7 + 3;
196143        }
196144      }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
196145        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
196146          memcpy(&aBuf[nBuf-6], "tion", 4);
196147          *pnBuf = nBuf - 6 + 4;
196148        }
196149      }
196150      break;
196151
196152    case 'c':
196153      if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
196154        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196155          memcpy(&aBuf[nBuf-4], "ence", 4);
196156          *pnBuf = nBuf - 4 + 4;
196157        }
196158      }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
196159        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196160          memcpy(&aBuf[nBuf-4], "ance", 4);
196161          *pnBuf = nBuf - 4 + 4;
196162        }
196163      }
196164      break;
196165
196166    case 'e':
196167      if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
196168        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196169          memcpy(&aBuf[nBuf-4], "ize", 3);
196170          *pnBuf = nBuf - 4 + 3;
196171        }
196172      }
196173      break;
196174
196175    case 'g':
196176      if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
196177        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196178          memcpy(&aBuf[nBuf-4], "log", 3);
196179          *pnBuf = nBuf - 4 + 3;
196180        }
196181      }
196182      break;
196183
196184    case 'l':
196185      if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
196186        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196187          memcpy(&aBuf[nBuf-3], "ble", 3);
196188          *pnBuf = nBuf - 3 + 3;
196189        }
196190      }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
196191        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196192          memcpy(&aBuf[nBuf-4], "al", 2);
196193          *pnBuf = nBuf - 4 + 2;
196194        }
196195      }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
196196        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196197          memcpy(&aBuf[nBuf-5], "ent", 3);
196198          *pnBuf = nBuf - 5 + 3;
196199        }
196200      }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
196201        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196202          memcpy(&aBuf[nBuf-3], "e", 1);
196203          *pnBuf = nBuf - 3 + 1;
196204        }
196205      }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
196206        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196207          memcpy(&aBuf[nBuf-5], "ous", 3);
196208          *pnBuf = nBuf - 5 + 3;
196209        }
196210      }
196211      break;
196212
196213    case 'o':
196214      if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
196215        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196216          memcpy(&aBuf[nBuf-7], "ize", 3);
196217          *pnBuf = nBuf - 7 + 3;
196218        }
196219      }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
196220        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196221          memcpy(&aBuf[nBuf-5], "ate", 3);
196222          *pnBuf = nBuf - 5 + 3;
196223        }
196224      }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
196225        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196226          memcpy(&aBuf[nBuf-4], "ate", 3);
196227          *pnBuf = nBuf - 4 + 3;
196228        }
196229      }
196230      break;
196231
196232    case 's':
196233      if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
196234        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196235          memcpy(&aBuf[nBuf-5], "al", 2);
196236          *pnBuf = nBuf - 5 + 2;
196237        }
196238      }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
196239        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196240          memcpy(&aBuf[nBuf-7], "ive", 3);
196241          *pnBuf = nBuf - 7 + 3;
196242        }
196243      }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
196244        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196245          memcpy(&aBuf[nBuf-7], "ful", 3);
196246          *pnBuf = nBuf - 7 + 3;
196247        }
196248      }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
196249        if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196250          memcpy(&aBuf[nBuf-7], "ous", 3);
196251          *pnBuf = nBuf - 7 + 3;
196252        }
196253      }
196254      break;
196255
196256    case 't':
196257      if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
196258        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196259          memcpy(&aBuf[nBuf-5], "al", 2);
196260          *pnBuf = nBuf - 5 + 2;
196261        }
196262      }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
196263        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196264          memcpy(&aBuf[nBuf-5], "ive", 3);
196265          *pnBuf = nBuf - 5 + 3;
196266        }
196267      }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
196268        if( fts5Porter_MGt0(aBuf, nBuf-6) ){
196269          memcpy(&aBuf[nBuf-6], "ble", 3);
196270          *pnBuf = nBuf - 6 + 3;
196271        }
196272      }
196273      break;
196274
196275  }
196276  return ret;
196277}
196278
196279
196280static int fts5PorterStep3(char *aBuf, int *pnBuf){
196281  int ret = 0;
196282  int nBuf = *pnBuf;
196283  switch( aBuf[nBuf-2] ){
196284
196285    case 'a':
196286      if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
196287        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196288          memcpy(&aBuf[nBuf-4], "ic", 2);
196289          *pnBuf = nBuf - 4 + 2;
196290        }
196291      }
196292      break;
196293
196294    case 's':
196295      if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
196296        if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196297          *pnBuf = nBuf - 4;
196298        }
196299      }
196300      break;
196301
196302    case 't':
196303      if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
196304        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196305          memcpy(&aBuf[nBuf-5], "ic", 2);
196306          *pnBuf = nBuf - 5 + 2;
196307        }
196308      }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
196309        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196310          memcpy(&aBuf[nBuf-5], "ic", 2);
196311          *pnBuf = nBuf - 5 + 2;
196312        }
196313      }
196314      break;
196315
196316    case 'u':
196317      if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
196318        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196319          *pnBuf = nBuf - 3;
196320        }
196321      }
196322      break;
196323
196324    case 'v':
196325      if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
196326        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196327          *pnBuf = nBuf - 5;
196328        }
196329      }
196330      break;
196331
196332    case 'z':
196333      if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
196334        if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196335          memcpy(&aBuf[nBuf-5], "al", 2);
196336          *pnBuf = nBuf - 5 + 2;
196337        }
196338      }
196339      break;
196340
196341  }
196342  return ret;
196343}
196344
196345
196346static int fts5PorterStep1B(char *aBuf, int *pnBuf){
196347  int ret = 0;
196348  int nBuf = *pnBuf;
196349  switch( aBuf[nBuf-2] ){
196350
196351    case 'e':
196352      if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
196353        if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196354          memcpy(&aBuf[nBuf-3], "ee", 2);
196355          *pnBuf = nBuf - 3 + 2;
196356        }
196357      }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
196358        if( fts5Porter_Vowel(aBuf, nBuf-2) ){
196359          *pnBuf = nBuf - 2;
196360          ret = 1;
196361        }
196362      }
196363      break;
196364
196365    case 'n':
196366      if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
196367        if( fts5Porter_Vowel(aBuf, nBuf-3) ){
196368          *pnBuf = nBuf - 3;
196369          ret = 1;
196370        }
196371      }
196372      break;
196373
196374  }
196375  return ret;
196376}
196377
196378/*
196379** GENERATED CODE ENDS HERE (mkportersteps.tcl)
196380***************************************************************************
196381**************************************************************************/
196382
196383static void fts5PorterStep1A(char *aBuf, int *pnBuf){
196384  int nBuf = *pnBuf;
196385  if( aBuf[nBuf-1]=='s' ){
196386    if( aBuf[nBuf-2]=='e' ){
196387      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
196388       || (nBuf>3 && aBuf[nBuf-3]=='i' )
196389      ){
196390        *pnBuf = nBuf-2;
196391      }else{
196392        *pnBuf = nBuf-1;
196393      }
196394    }
196395    else if( aBuf[nBuf-2]!='s' ){
196396      *pnBuf = nBuf-1;
196397    }
196398  }
196399}
196400
196401static int fts5PorterCb(
196402  void *pCtx,
196403  int tflags,
196404  const char *pToken,
196405  int nToken,
196406  int iStart,
196407  int iEnd
196408){
196409  PorterContext *p = (PorterContext*)pCtx;
196410
196411  char *aBuf;
196412  int nBuf;
196413
196414  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
196415  aBuf = p->aBuf;
196416  nBuf = nToken;
196417  memcpy(aBuf, pToken, nBuf);
196418
196419  /* Step 1. */
196420  fts5PorterStep1A(aBuf, &nBuf);
196421  if( fts5PorterStep1B(aBuf, &nBuf) ){
196422    if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
196423      char c = aBuf[nBuf-1];
196424      if( fts5PorterIsVowel(c, 0)==0
196425       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
196426      ){
196427        nBuf--;
196428      }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
196429        aBuf[nBuf++] = 'e';
196430      }
196431    }
196432  }
196433
196434  /* Step 1C. */
196435  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
196436    aBuf[nBuf-1] = 'i';
196437  }
196438
196439  /* Steps 2 through 4. */
196440  fts5PorterStep2(aBuf, &nBuf);
196441  fts5PorterStep3(aBuf, &nBuf);
196442  fts5PorterStep4(aBuf, &nBuf);
196443
196444  /* Step 5a. */
196445  assert( nBuf>0 );
196446  if( aBuf[nBuf-1]=='e' ){
196447    if( fts5Porter_MGt1(aBuf, nBuf-1)
196448     || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
196449    ){
196450      nBuf--;
196451    }
196452  }
196453
196454  /* Step 5b. */
196455  if( nBuf>1 && aBuf[nBuf-1]=='l'
196456   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
196457  ){
196458    nBuf--;
196459  }
196460
196461  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
196462
196463 pass_through:
196464  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
196465}
196466
196467/*
196468** Tokenize using the porter tokenizer.
196469*/
196470static int fts5PorterTokenize(
196471  Fts5Tokenizer *pTokenizer,
196472  void *pCtx,
196473  int flags,
196474  const char *pText, int nText,
196475  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
196476){
196477  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
196478  PorterContext sCtx;
196479  sCtx.xToken = xToken;
196480  sCtx.pCtx = pCtx;
196481  sCtx.aBuf = p->aBuf;
196482  return p->tokenizer.xTokenize(
196483      p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
196484  );
196485}
196486
196487/*
196488** Register all built-in tokenizers with FTS5.
196489*/
196490static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
196491  struct BuiltinTokenizer {
196492    const char *zName;
196493    fts5_tokenizer x;
196494  } aBuiltin[] = {
196495    { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
196496    { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
196497    { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
196498  };
196499
196500  int rc = SQLITE_OK;             /* Return code */
196501  int i;                          /* To iterate through builtin functions */
196502
196503  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
196504    rc = pApi->xCreateTokenizer(pApi,
196505        aBuiltin[i].zName,
196506        (void*)pApi,
196507        &aBuiltin[i].x,
196508        0
196509    );
196510  }
196511
196512  return rc;
196513}
196514
196515
196516
196517/*
196518** 2012 May 25
196519**
196520** The author disclaims copyright to this source code.  In place of
196521** a legal notice, here is a blessing:
196522**
196523**    May you do good and not evil.
196524**    May you find forgiveness for yourself and forgive others.
196525**    May you share freely, never taking more than you give.
196526**
196527******************************************************************************
196528*/
196529
196530/*
196531** DO NOT EDIT THIS MACHINE GENERATED FILE.
196532*/
196533
196534
196535/* #include <assert.h> */
196536
196537/*
196538** Return true if the argument corresponds to a unicode codepoint
196539** classified as either a letter or a number. Otherwise false.
196540**
196541** The results are undefined if the value passed to this function
196542** is less than zero.
196543*/
196544static int sqlite3Fts5UnicodeIsalnum(int c){
196545  /* Each unsigned integer in the following array corresponds to a contiguous
196546  ** range of unicode codepoints that are not either letters or numbers (i.e.
196547  ** codepoints for which this function should return 0).
196548  **
196549  ** The most significant 22 bits in each 32-bit value contain the first
196550  ** codepoint in the range. The least significant 10 bits are used to store
196551  ** the size of the range (always at least 1). In other words, the value
196552  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
196553  ** C. It is not possible to represent a range larger than 1023 codepoints
196554  ** using this format.
196555  */
196556  static const unsigned int aEntry[] = {
196557    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
196558    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
196559    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
196560    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
196561    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
196562    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
196563    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
196564    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
196565    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
196566    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
196567    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
196568    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
196569    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
196570    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
196571    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
196572    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
196573    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
196574    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
196575    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
196576    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
196577    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
196578    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
196579    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
196580    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
196581    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
196582    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
196583    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
196584    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
196585    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
196586    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
196587    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
196588    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
196589    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
196590    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
196591    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
196592    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
196593    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
196594    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
196595    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
196596    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
196597    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
196598    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
196599    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
196600    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
196601    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
196602    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
196603    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
196604    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
196605    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
196606    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
196607    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
196608    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
196609    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
196610    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
196611    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
196612    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
196613    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
196614    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
196615    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
196616    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
196617    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
196618    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
196619    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
196620    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
196621    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
196622    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
196623    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
196624    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
196625    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
196626    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
196627    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
196628    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
196629    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
196630    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
196631    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
196632    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
196633    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
196634    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
196635    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
196636    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
196637    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
196638    0x380400F0,
196639  };
196640  static const unsigned int aAscii[4] = {
196641    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
196642  };
196643
196644  if( (unsigned int)c<128 ){
196645    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
196646  }else if( (unsigned int)c<(1<<22) ){
196647    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
196648    int iRes = 0;
196649    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
196650    int iLo = 0;
196651    while( iHi>=iLo ){
196652      int iTest = (iHi + iLo) / 2;
196653      if( key >= aEntry[iTest] ){
196654        iRes = iTest;
196655        iLo = iTest+1;
196656      }else{
196657        iHi = iTest-1;
196658      }
196659    }
196660    assert( aEntry[0]<key );
196661    assert( key>=aEntry[iRes] );
196662    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
196663  }
196664  return 1;
196665}
196666
196667
196668/*
196669** If the argument is a codepoint corresponding to a lowercase letter
196670** in the ASCII range with a diacritic added, return the codepoint
196671** of the ASCII letter only. For example, if passed 235 - "LATIN
196672** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
196673** E"). The resuls of passing a codepoint that corresponds to an
196674** uppercase letter are undefined.
196675*/
196676static int fts5_remove_diacritic(int c){
196677  unsigned short aDia[] = {
196678        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
196679     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
196680     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
196681     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
196682     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
196683     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
196684     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
196685     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
196686    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
196687    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
196688    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
196689    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
196690    62924, 63050, 63082, 63274, 63390,
196691  };
196692  char aChar[] = {
196693    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
196694    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
196695    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
196696    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
196697    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
196698    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
196699    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
196700    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
196701    'e',  'i',  'o',  'u',  'y',
196702  };
196703
196704  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
196705  int iRes = 0;
196706  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
196707  int iLo = 0;
196708  while( iHi>=iLo ){
196709    int iTest = (iHi + iLo) / 2;
196710    if( key >= aDia[iTest] ){
196711      iRes = iTest;
196712      iLo = iTest+1;
196713    }else{
196714      iHi = iTest-1;
196715    }
196716  }
196717  assert( key>=aDia[iRes] );
196718  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
196719}
196720
196721
196722/*
196723** Return true if the argument interpreted as a unicode codepoint
196724** is a diacritical modifier character.
196725*/
196726static int sqlite3Fts5UnicodeIsdiacritic(int c){
196727  unsigned int mask0 = 0x08029FDF;
196728  unsigned int mask1 = 0x000361F8;
196729  if( c<768 || c>817 ) return 0;
196730  return (c < 768+32) ?
196731      (mask0 & (1 << (c-768))) :
196732      (mask1 & (1 << (c-768-32)));
196733}
196734
196735
196736/*
196737** Interpret the argument as a unicode codepoint. If the codepoint
196738** is an upper case character that has a lower case equivalent,
196739** return the codepoint corresponding to the lower case version.
196740** Otherwise, return a copy of the argument.
196741**
196742** The results are undefined if the value passed to this function
196743** is less than zero.
196744*/
196745static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
196746  /* Each entry in the following array defines a rule for folding a range
196747  ** of codepoints to lower case. The rule applies to a range of nRange
196748  ** codepoints starting at codepoint iCode.
196749  **
196750  ** If the least significant bit in flags is clear, then the rule applies
196751  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
196752  ** need to be folded). Or, if it is set, then the rule only applies to
196753  ** every second codepoint in the range, starting with codepoint C.
196754  **
196755  ** The 7 most significant bits in flags are an index into the aiOff[]
196756  ** array. If a specific codepoint C does require folding, then its lower
196757  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
196758  **
196759  ** The contents of this array are generated by parsing the CaseFolding.txt
196760  ** file distributed as part of the "Unicode Character Database". See
196761  ** http://www.unicode.org for details.
196762  */
196763  static const struct TableEntry {
196764    unsigned short iCode;
196765    unsigned char flags;
196766    unsigned char nRange;
196767  } aEntry[] = {
196768    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
196769    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
196770    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
196771    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
196772    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
196773    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
196774    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
196775    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
196776    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
196777    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
196778    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
196779    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
196780    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
196781    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
196782    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
196783    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
196784    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
196785    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
196786    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
196787    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
196788    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
196789    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
196790    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
196791    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
196792    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
196793    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
196794    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
196795    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
196796    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
196797    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
196798    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
196799    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
196800    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
196801    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
196802    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
196803    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
196804    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
196805    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
196806    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
196807    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
196808    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
196809    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
196810    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
196811    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
196812    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
196813    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
196814    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
196815    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
196816    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
196817    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
196818    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
196819    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
196820    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
196821    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
196822    {65313, 14, 26},
196823  };
196824  static const unsigned short aiOff[] = {
196825   1,     2,     8,     15,    16,    26,    28,    32,
196826   37,    38,    40,    48,    63,    64,    69,    71,
196827   79,    80,    116,   202,   203,   205,   206,   207,
196828   209,   210,   211,   213,   214,   217,   218,   219,
196829   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
196830   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
196831   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
196832   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
196833   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
196834   65514, 65521, 65527, 65528, 65529,
196835  };
196836
196837  int ret = c;
196838
196839  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
196840
196841  if( c<128 ){
196842    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
196843  }else if( c<65536 ){
196844    const struct TableEntry *p;
196845    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
196846    int iLo = 0;
196847    int iRes = -1;
196848
196849    assert( c>aEntry[0].iCode );
196850    while( iHi>=iLo ){
196851      int iTest = (iHi + iLo) / 2;
196852      int cmp = (c - aEntry[iTest].iCode);
196853      if( cmp>=0 ){
196854        iRes = iTest;
196855        iLo = iTest+1;
196856      }else{
196857        iHi = iTest-1;
196858      }
196859    }
196860
196861    assert( iRes>=0 && c>=aEntry[iRes].iCode );
196862    p = &aEntry[iRes];
196863    if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
196864      ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
196865      assert( ret>0 );
196866    }
196867
196868    if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
196869  }
196870
196871  else if( c>=66560 && c<66600 ){
196872    ret = c + 40;
196873  }
196874
196875  return ret;
196876}
196877
196878/*
196879** 2015 May 30
196880**
196881** The author disclaims copyright to this source code.  In place of
196882** a legal notice, here is a blessing:
196883**
196884**    May you do good and not evil.
196885**    May you find forgiveness for yourself and forgive others.
196886**    May you share freely, never taking more than you give.
196887**
196888******************************************************************************
196889**
196890** Routines for varint serialization and deserialization.
196891*/
196892
196893
196894/* #include "fts5Int.h" */
196895
196896/*
196897** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
196898** Except, this version does handle the single byte case that the core
196899** version depends on being handled before its function is called.
196900*/
196901static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
196902  u32 a,b;
196903
196904  /* The 1-byte case. Overwhelmingly the most common. */
196905  a = *p;
196906  /* a: p0 (unmasked) */
196907  if (!(a&0x80))
196908  {
196909    /* Values between 0 and 127 */
196910    *v = a;
196911    return 1;
196912  }
196913
196914  /* The 2-byte case */
196915  p++;
196916  b = *p;
196917  /* b: p1 (unmasked) */
196918  if (!(b&0x80))
196919  {
196920    /* Values between 128 and 16383 */
196921    a &= 0x7f;
196922    a = a<<7;
196923    *v = a | b;
196924    return 2;
196925  }
196926
196927  /* The 3-byte case */
196928  p++;
196929  a = a<<14;
196930  a |= *p;
196931  /* a: p0<<14 | p2 (unmasked) */
196932  if (!(a&0x80))
196933  {
196934    /* Values between 16384 and 2097151 */
196935    a &= (0x7f<<14)|(0x7f);
196936    b &= 0x7f;
196937    b = b<<7;
196938    *v = a | b;
196939    return 3;
196940  }
196941
196942  /* A 32-bit varint is used to store size information in btrees.
196943  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
196944  ** A 3-byte varint is sufficient, for example, to record the size
196945  ** of a 1048569-byte BLOB or string.
196946  **
196947  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
196948  ** rare larger cases can be handled by the slower 64-bit varint
196949  ** routine.
196950  */
196951  {
196952    u64 v64;
196953    u8 n;
196954    p -= 2;
196955    n = sqlite3Fts5GetVarint(p, &v64);
196956    *v = (u32)v64;
196957    assert( n>3 && n<=9 );
196958    return n;
196959  }
196960}
196961
196962
196963/*
196964** Bitmasks used by sqlite3GetVarint().  These precomputed constants
196965** are defined here rather than simply putting the constant expressions
196966** inline in order to work around bugs in the RVT compiler.
196967**
196968** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
196969**
196970** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
196971*/
196972#define SLOT_2_0     0x001fc07f
196973#define SLOT_4_2_0   0xf01fc07f
196974
196975/*
196976** Read a 64-bit variable-length integer from memory starting at p[0].
196977** Return the number of bytes read.  The value is stored in *v.
196978*/
196979static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
196980  u32 a,b,s;
196981
196982  a = *p;
196983  /* a: p0 (unmasked) */
196984  if (!(a&0x80))
196985  {
196986    *v = a;
196987    return 1;
196988  }
196989
196990  p++;
196991  b = *p;
196992  /* b: p1 (unmasked) */
196993  if (!(b&0x80))
196994  {
196995    a &= 0x7f;
196996    a = a<<7;
196997    a |= b;
196998    *v = a;
196999    return 2;
197000  }
197001
197002  /* Verify that constants are precomputed correctly */
197003  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
197004  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
197005
197006  p++;
197007  a = a<<14;
197008  a |= *p;
197009  /* a: p0<<14 | p2 (unmasked) */
197010  if (!(a&0x80))
197011  {
197012    a &= SLOT_2_0;
197013    b &= 0x7f;
197014    b = b<<7;
197015    a |= b;
197016    *v = a;
197017    return 3;
197018  }
197019
197020  /* CSE1 from below */
197021  a &= SLOT_2_0;
197022  p++;
197023  b = b<<14;
197024  b |= *p;
197025  /* b: p1<<14 | p3 (unmasked) */
197026  if (!(b&0x80))
197027  {
197028    b &= SLOT_2_0;
197029    /* moved CSE1 up */
197030    /* a &= (0x7f<<14)|(0x7f); */
197031    a = a<<7;
197032    a |= b;
197033    *v = a;
197034    return 4;
197035  }
197036
197037  /* a: p0<<14 | p2 (masked) */
197038  /* b: p1<<14 | p3 (unmasked) */
197039  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197040  /* moved CSE1 up */
197041  /* a &= (0x7f<<14)|(0x7f); */
197042  b &= SLOT_2_0;
197043  s = a;
197044  /* s: p0<<14 | p2 (masked) */
197045
197046  p++;
197047  a = a<<14;
197048  a |= *p;
197049  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
197050  if (!(a&0x80))
197051  {
197052    /* we can skip these cause they were (effectively) done above in calc'ing s */
197053    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
197054    /* b &= (0x7f<<14)|(0x7f); */
197055    b = b<<7;
197056    a |= b;
197057    s = s>>18;
197058    *v = ((u64)s)<<32 | a;
197059    return 5;
197060  }
197061
197062  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197063  s = s<<7;
197064  s |= b;
197065  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197066
197067  p++;
197068  b = b<<14;
197069  b |= *p;
197070  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
197071  if (!(b&0x80))
197072  {
197073    /* we can skip this cause it was (effectively) done above in calc'ing s */
197074    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
197075    a &= SLOT_2_0;
197076    a = a<<7;
197077    a |= b;
197078    s = s>>18;
197079    *v = ((u64)s)<<32 | a;
197080    return 6;
197081  }
197082
197083  p++;
197084  a = a<<14;
197085  a |= *p;
197086  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
197087  if (!(a&0x80))
197088  {
197089    a &= SLOT_4_2_0;
197090    b &= SLOT_2_0;
197091    b = b<<7;
197092    a |= b;
197093    s = s>>11;
197094    *v = ((u64)s)<<32 | a;
197095    return 7;
197096  }
197097
197098  /* CSE2 from below */
197099  a &= SLOT_2_0;
197100  p++;
197101  b = b<<14;
197102  b |= *p;
197103  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
197104  if (!(b&0x80))
197105  {
197106    b &= SLOT_4_2_0;
197107    /* moved CSE2 up */
197108    /* a &= (0x7f<<14)|(0x7f); */
197109    a = a<<7;
197110    a |= b;
197111    s = s>>4;
197112    *v = ((u64)s)<<32 | a;
197113    return 8;
197114  }
197115
197116  p++;
197117  a = a<<15;
197118  a |= *p;
197119  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
197120
197121  /* moved CSE2 up */
197122  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
197123  b &= SLOT_2_0;
197124  b = b<<8;
197125  a |= b;
197126
197127  s = s<<4;
197128  b = p[-4];
197129  b &= 0x7f;
197130  b = b>>3;
197131  s |= b;
197132
197133  *v = ((u64)s)<<32 | a;
197134
197135  return 9;
197136}
197137
197138/*
197139** The variable-length integer encoding is as follows:
197140**
197141** KEY:
197142**         A = 0xxxxxxx    7 bits of data and one flag bit
197143**         B = 1xxxxxxx    7 bits of data and one flag bit
197144**         C = xxxxxxxx    8 bits of data
197145**
197146**  7 bits - A
197147** 14 bits - BA
197148** 21 bits - BBA
197149** 28 bits - BBBA
197150** 35 bits - BBBBA
197151** 42 bits - BBBBBA
197152** 49 bits - BBBBBBA
197153** 56 bits - BBBBBBBA
197154** 64 bits - BBBBBBBBC
197155*/
197156
197157#ifdef SQLITE_NOINLINE
197158# define FTS5_NOINLINE SQLITE_NOINLINE
197159#else
197160# define FTS5_NOINLINE
197161#endif
197162
197163/*
197164** Write a 64-bit variable-length integer to memory starting at p[0].
197165** The length of data write will be between 1 and 9 bytes.  The number
197166** of bytes written is returned.
197167**
197168** A variable-length integer consists of the lower 7 bits of each byte
197169** for all bytes that have the 8th bit set and one byte with the 8th
197170** bit clear.  Except, if we get to the 9th byte, it stores the full
197171** 8 bits and is the last byte.
197172*/
197173static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
197174  int i, j, n;
197175  u8 buf[10];
197176  if( v & (((u64)0xff000000)<<32) ){
197177    p[8] = (u8)v;
197178    v >>= 8;
197179    for(i=7; i>=0; i--){
197180      p[i] = (u8)((v & 0x7f) | 0x80);
197181      v >>= 7;
197182    }
197183    return 9;
197184  }
197185  n = 0;
197186  do{
197187    buf[n++] = (u8)((v & 0x7f) | 0x80);
197188    v >>= 7;
197189  }while( v!=0 );
197190  buf[0] &= 0x7f;
197191  assert( n<=9 );
197192  for(i=0, j=n-1; j>=0; j--, i++){
197193    p[i] = buf[j];
197194  }
197195  return n;
197196}
197197
197198static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
197199  if( v<=0x7f ){
197200    p[0] = v&0x7f;
197201    return 1;
197202  }
197203  if( v<=0x3fff ){
197204    p[0] = ((v>>7)&0x7f)|0x80;
197205    p[1] = v&0x7f;
197206    return 2;
197207  }
197208  return fts5PutVarint64(p,v);
197209}
197210
197211
197212static int sqlite3Fts5GetVarintLen(u32 iVal){
197213#if 0
197214  if( iVal<(1 << 7 ) ) return 1;
197215#endif
197216  assert( iVal>=(1 << 7) );
197217  if( iVal<(1 << 14) ) return 2;
197218  if( iVal<(1 << 21) ) return 3;
197219  if( iVal<(1 << 28) ) return 4;
197220  return 5;
197221}
197222
197223
197224/*
197225** 2015 May 08
197226**
197227** The author disclaims copyright to this source code.  In place of
197228** a legal notice, here is a blessing:
197229**
197230**    May you do good and not evil.
197231**    May you find forgiveness for yourself and forgive others.
197232**    May you share freely, never taking more than you give.
197233**
197234******************************************************************************
197235**
197236** This is an SQLite virtual table module implementing direct access to an
197237** existing FTS5 index. The module may create several different types of
197238** tables:
197239**
197240** col:
197241**     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
197242**
197243**   One row for each term/column combination. The value of $doc is set to
197244**   the number of fts5 rows that contain at least one instance of term
197245**   $term within column $col. Field $cnt is set to the total number of
197246**   instances of term $term in column $col (in any row of the fts5 table).
197247**
197248** row:
197249**     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
197250**
197251**   One row for each term in the database. The value of $doc is set to
197252**   the number of fts5 rows that contain at least one instance of term
197253**   $term. Field $cnt is set to the total number of instances of term
197254**   $term in the database.
197255*/
197256
197257
197258/* #include "fts5Int.h" */
197259
197260
197261typedef struct Fts5VocabTable Fts5VocabTable;
197262typedef struct Fts5VocabCursor Fts5VocabCursor;
197263
197264struct Fts5VocabTable {
197265  sqlite3_vtab base;
197266  char *zFts5Tbl;                 /* Name of fts5 table */
197267  char *zFts5Db;                  /* Db containing fts5 table */
197268  sqlite3 *db;                    /* Database handle */
197269  Fts5Global *pGlobal;            /* FTS5 global object for this database */
197270  int eType;                      /* FTS5_VOCAB_COL or ROW */
197271};
197272
197273struct Fts5VocabCursor {
197274  sqlite3_vtab_cursor base;
197275  sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
197276  Fts5Index *pIndex;              /* Associated FTS5 index */
197277
197278  int bEof;                       /* True if this cursor is at EOF */
197279  Fts5IndexIter *pIter;           /* Term/rowid iterator object */
197280
197281  int nLeTerm;                    /* Size of zLeTerm in bytes */
197282  char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
197283
197284  /* These are used by 'col' tables only */
197285  Fts5Config *pConfig;            /* Fts5 table configuration */
197286  int iCol;
197287  i64 *aCnt;
197288  i64 *aDoc;
197289
197290  /* Output values used by 'row' and 'col' tables */
197291  i64 rowid;                      /* This table's current rowid value */
197292  Fts5Buffer term;                /* Current value of 'term' column */
197293};
197294
197295#define FTS5_VOCAB_COL    0
197296#define FTS5_VOCAB_ROW    1
197297
197298#define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
197299#define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
197300
197301/*
197302** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
197303*/
197304#define FTS5_VOCAB_TERM_EQ 0x01
197305#define FTS5_VOCAB_TERM_GE 0x02
197306#define FTS5_VOCAB_TERM_LE 0x04
197307
197308
197309/*
197310** Translate a string containing an fts5vocab table type to an
197311** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
197312** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
197313** and return SQLITE_ERROR.
197314*/
197315static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
197316  int rc = SQLITE_OK;
197317  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
197318  if( rc==SQLITE_OK ){
197319    sqlite3Fts5Dequote(zCopy);
197320    if( sqlite3_stricmp(zCopy, "col")==0 ){
197321      *peType = FTS5_VOCAB_COL;
197322    }else
197323
197324    if( sqlite3_stricmp(zCopy, "row")==0 ){
197325      *peType = FTS5_VOCAB_ROW;
197326    }else
197327    {
197328      *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
197329      rc = SQLITE_ERROR;
197330    }
197331    sqlite3_free(zCopy);
197332  }
197333
197334  return rc;
197335}
197336
197337
197338/*
197339** The xDisconnect() virtual table method.
197340*/
197341static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
197342  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
197343  sqlite3_free(pTab);
197344  return SQLITE_OK;
197345}
197346
197347/*
197348** The xDestroy() virtual table method.
197349*/
197350static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
197351  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
197352  sqlite3_free(pTab);
197353  return SQLITE_OK;
197354}
197355
197356/*
197357** This function is the implementation of both the xConnect and xCreate
197358** methods of the FTS3 virtual table.
197359**
197360** The argv[] array contains the following:
197361**
197362**   argv[0]   -> module name  ("fts5vocab")
197363**   argv[1]   -> database name
197364**   argv[2]   -> table name
197365**
197366** then:
197367**
197368**   argv[3]   -> name of fts5 table
197369**   argv[4]   -> type of fts5vocab table
197370**
197371** or, for tables in the TEMP schema only.
197372**
197373**   argv[3]   -> name of fts5 tables database
197374**   argv[4]   -> name of fts5 table
197375**   argv[5]   -> type of fts5vocab table
197376*/
197377static int fts5VocabInitVtab(
197378  sqlite3 *db,                    /* The SQLite database connection */
197379  void *pAux,                     /* Pointer to Fts5Global object */
197380  int argc,                       /* Number of elements in argv array */
197381  const char * const *argv,       /* xCreate/xConnect argument array */
197382  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
197383  char **pzErr                    /* Write any error message here */
197384){
197385  const char *azSchema[] = {
197386    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
197387    "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
197388  };
197389
197390  Fts5VocabTable *pRet = 0;
197391  int rc = SQLITE_OK;             /* Return code */
197392  int bDb;
197393
197394  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
197395
197396  if( argc!=5 && bDb==0 ){
197397    *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
197398    rc = SQLITE_ERROR;
197399  }else{
197400    int nByte;                      /* Bytes of space to allocate */
197401    const char *zDb = bDb ? argv[3] : argv[1];
197402    const char *zTab = bDb ? argv[4] : argv[3];
197403    const char *zType = bDb ? argv[5] : argv[4];
197404    int nDb = (int)strlen(zDb)+1;
197405    int nTab = (int)strlen(zTab)+1;
197406    int eType = 0;
197407
197408    rc = fts5VocabTableType(zType, pzErr, &eType);
197409    if( rc==SQLITE_OK ){
197410      assert( eType>=0 && eType<ArraySize(azSchema) );
197411      rc = sqlite3_declare_vtab(db, azSchema[eType]);
197412    }
197413
197414    nByte = sizeof(Fts5VocabTable) + nDb + nTab;
197415    pRet = sqlite3Fts5MallocZero(&rc, nByte);
197416    if( pRet ){
197417      pRet->pGlobal = (Fts5Global*)pAux;
197418      pRet->eType = eType;
197419      pRet->db = db;
197420      pRet->zFts5Tbl = (char*)&pRet[1];
197421      pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
197422      memcpy(pRet->zFts5Tbl, zTab, nTab);
197423      memcpy(pRet->zFts5Db, zDb, nDb);
197424      sqlite3Fts5Dequote(pRet->zFts5Tbl);
197425      sqlite3Fts5Dequote(pRet->zFts5Db);
197426    }
197427  }
197428
197429  *ppVTab = (sqlite3_vtab*)pRet;
197430  return rc;
197431}
197432
197433
197434/*
197435** The xConnect() and xCreate() methods for the virtual table. All the
197436** work is done in function fts5VocabInitVtab().
197437*/
197438static int fts5VocabConnectMethod(
197439  sqlite3 *db,                    /* Database connection */
197440  void *pAux,                     /* Pointer to tokenizer hash table */
197441  int argc,                       /* Number of elements in argv array */
197442  const char * const *argv,       /* xCreate/xConnect argument array */
197443  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
197444  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
197445){
197446  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
197447}
197448static int fts5VocabCreateMethod(
197449  sqlite3 *db,                    /* Database connection */
197450  void *pAux,                     /* Pointer to tokenizer hash table */
197451  int argc,                       /* Number of elements in argv array */
197452  const char * const *argv,       /* xCreate/xConnect argument array */
197453  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
197454  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
197455){
197456  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
197457}
197458
197459/*
197460** Implementation of the xBestIndex method.
197461*/
197462static int fts5VocabBestIndexMethod(
197463  sqlite3_vtab *pUnused,
197464  sqlite3_index_info *pInfo
197465){
197466  int i;
197467  int iTermEq = -1;
197468  int iTermGe = -1;
197469  int iTermLe = -1;
197470  int idxNum = 0;
197471  int nArg = 0;
197472
197473  UNUSED_PARAM(pUnused);
197474
197475  for(i=0; i<pInfo->nConstraint; i++){
197476    struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
197477    if( p->usable==0 ) continue;
197478    if( p->iColumn==0 ){          /* term column */
197479      if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
197480      if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
197481      if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
197482      if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
197483      if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
197484    }
197485  }
197486
197487  if( iTermEq>=0 ){
197488    idxNum |= FTS5_VOCAB_TERM_EQ;
197489    pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
197490    pInfo->estimatedCost = 100;
197491  }else{
197492    pInfo->estimatedCost = 1000000;
197493    if( iTermGe>=0 ){
197494      idxNum |= FTS5_VOCAB_TERM_GE;
197495      pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
197496      pInfo->estimatedCost = pInfo->estimatedCost / 2;
197497    }
197498    if( iTermLe>=0 ){
197499      idxNum |= FTS5_VOCAB_TERM_LE;
197500      pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
197501      pInfo->estimatedCost = pInfo->estimatedCost / 2;
197502    }
197503  }
197504
197505  pInfo->idxNum = idxNum;
197506
197507  return SQLITE_OK;
197508}
197509
197510/*
197511** Implementation of xOpen method.
197512*/
197513static int fts5VocabOpenMethod(
197514  sqlite3_vtab *pVTab,
197515  sqlite3_vtab_cursor **ppCsr
197516){
197517  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
197518  Fts5Index *pIndex = 0;
197519  Fts5Config *pConfig = 0;
197520  Fts5VocabCursor *pCsr = 0;
197521  int rc = SQLITE_OK;
197522  sqlite3_stmt *pStmt = 0;
197523  char *zSql = 0;
197524
197525  zSql = sqlite3Fts5Mprintf(&rc,
197526      "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
197527      pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
197528  );
197529  if( zSql ){
197530    rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
197531  }
197532  sqlite3_free(zSql);
197533  assert( rc==SQLITE_OK || pStmt==0 );
197534  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
197535
197536  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
197537    i64 iId = sqlite3_column_int64(pStmt, 0);
197538    pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
197539  }
197540
197541  if( rc==SQLITE_OK && pIndex==0 ){
197542    rc = sqlite3_finalize(pStmt);
197543    pStmt = 0;
197544    if( rc==SQLITE_OK ){
197545      pVTab->zErrMsg = sqlite3_mprintf(
197546          "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
197547      );
197548      rc = SQLITE_ERROR;
197549    }
197550  }
197551
197552  if( rc==SQLITE_OK ){
197553    int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
197554    pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
197555  }
197556
197557  if( pCsr ){
197558    pCsr->pIndex = pIndex;
197559    pCsr->pStmt = pStmt;
197560    pCsr->pConfig = pConfig;
197561    pCsr->aCnt = (i64*)&pCsr[1];
197562    pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
197563  }else{
197564    sqlite3_finalize(pStmt);
197565  }
197566
197567  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
197568  return rc;
197569}
197570
197571static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
197572  pCsr->rowid = 0;
197573  sqlite3Fts5IterClose(pCsr->pIter);
197574  pCsr->pIter = 0;
197575  sqlite3_free(pCsr->zLeTerm);
197576  pCsr->nLeTerm = -1;
197577  pCsr->zLeTerm = 0;
197578}
197579
197580/*
197581** Close the cursor.  For additional information see the documentation
197582** on the xClose method of the virtual table interface.
197583*/
197584static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
197585  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197586  fts5VocabResetCursor(pCsr);
197587  sqlite3Fts5BufferFree(&pCsr->term);
197588  sqlite3_finalize(pCsr->pStmt);
197589  sqlite3_free(pCsr);
197590  return SQLITE_OK;
197591}
197592
197593
197594/*
197595** Advance the cursor to the next row in the table.
197596*/
197597static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
197598  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197599  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
197600  int rc = SQLITE_OK;
197601  int nCol = pCsr->pConfig->nCol;
197602
197603  pCsr->rowid++;
197604
197605  if( pTab->eType==FTS5_VOCAB_COL ){
197606    for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
197607      if( pCsr->aDoc[pCsr->iCol] ) break;
197608    }
197609  }
197610
197611  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
197612    if( sqlite3Fts5IterEof(pCsr->pIter) ){
197613      pCsr->bEof = 1;
197614    }else{
197615      const char *zTerm;
197616      int nTerm;
197617
197618      zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
197619      if( pCsr->nLeTerm>=0 ){
197620        int nCmp = MIN(nTerm, pCsr->nLeTerm);
197621        int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
197622        if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
197623          pCsr->bEof = 1;
197624          return SQLITE_OK;
197625        }
197626      }
197627
197628      sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
197629      memset(pCsr->aCnt, 0, nCol * sizeof(i64));
197630      memset(pCsr->aDoc, 0, nCol * sizeof(i64));
197631      pCsr->iCol = 0;
197632
197633      assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
197634      while( rc==SQLITE_OK ){
197635        const u8 *pPos; int nPos;   /* Position list */
197636        i64 iPos = 0;               /* 64-bit position read from poslist */
197637        int iOff = 0;               /* Current offset within position list */
197638
197639        pPos = pCsr->pIter->pData;
197640        nPos = pCsr->pIter->nData;
197641        switch( pCsr->pConfig->eDetail ){
197642          case FTS5_DETAIL_FULL:
197643            pPos = pCsr->pIter->pData;
197644            nPos = pCsr->pIter->nData;
197645            if( pTab->eType==FTS5_VOCAB_ROW ){
197646              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
197647                pCsr->aCnt[0]++;
197648              }
197649              pCsr->aDoc[0]++;
197650            }else{
197651              int iCol = -1;
197652              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
197653                int ii = FTS5_POS2COLUMN(iPos);
197654                pCsr->aCnt[ii]++;
197655                if( iCol!=ii ){
197656                  if( ii>=nCol ){
197657                    rc = FTS5_CORRUPT;
197658                    break;
197659                  }
197660                  pCsr->aDoc[ii]++;
197661                  iCol = ii;
197662                }
197663              }
197664            }
197665            break;
197666
197667          case FTS5_DETAIL_COLUMNS:
197668            if( pTab->eType==FTS5_VOCAB_ROW ){
197669              pCsr->aDoc[0]++;
197670            }else{
197671              while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
197672                assert_nc( iPos>=0 && iPos<nCol );
197673                if( iPos>=nCol ){
197674                  rc = FTS5_CORRUPT;
197675                  break;
197676                }
197677                pCsr->aDoc[iPos]++;
197678              }
197679            }
197680            break;
197681
197682          default:
197683            assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
197684            pCsr->aDoc[0]++;
197685            break;
197686        }
197687
197688        if( rc==SQLITE_OK ){
197689          rc = sqlite3Fts5IterNextScan(pCsr->pIter);
197690        }
197691
197692        if( rc==SQLITE_OK ){
197693          zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
197694          if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
197695            break;
197696          }
197697          if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
197698        }
197699      }
197700    }
197701  }
197702
197703  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
197704    while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
197705    assert( pCsr->iCol<pCsr->pConfig->nCol );
197706  }
197707  return rc;
197708}
197709
197710/*
197711** This is the xFilter implementation for the virtual table.
197712*/
197713static int fts5VocabFilterMethod(
197714  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
197715  int idxNum,                     /* Strategy index */
197716  const char *zUnused,            /* Unused */
197717  int nUnused,                    /* Number of elements in apVal */
197718  sqlite3_value **apVal           /* Arguments for the indexing scheme */
197719){
197720  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197721  int rc = SQLITE_OK;
197722
197723  int iVal = 0;
197724  int f = FTS5INDEX_QUERY_SCAN;
197725  const char *zTerm = 0;
197726  int nTerm = 0;
197727
197728  sqlite3_value *pEq = 0;
197729  sqlite3_value *pGe = 0;
197730  sqlite3_value *pLe = 0;
197731
197732  UNUSED_PARAM2(zUnused, nUnused);
197733
197734  fts5VocabResetCursor(pCsr);
197735  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
197736  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
197737  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
197738
197739  if( pEq ){
197740    zTerm = (const char *)sqlite3_value_text(pEq);
197741    nTerm = sqlite3_value_bytes(pEq);
197742    f = 0;
197743  }else{
197744    if( pGe ){
197745      zTerm = (const char *)sqlite3_value_text(pGe);
197746      nTerm = sqlite3_value_bytes(pGe);
197747    }
197748    if( pLe ){
197749      const char *zCopy = (const char *)sqlite3_value_text(pLe);
197750      pCsr->nLeTerm = sqlite3_value_bytes(pLe);
197751      pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
197752      if( pCsr->zLeTerm==0 ){
197753        rc = SQLITE_NOMEM;
197754      }else{
197755        memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
197756      }
197757    }
197758  }
197759
197760
197761  if( rc==SQLITE_OK ){
197762    rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
197763  }
197764  if( rc==SQLITE_OK ){
197765    rc = fts5VocabNextMethod(pCursor);
197766  }
197767
197768  return rc;
197769}
197770
197771/*
197772** This is the xEof method of the virtual table. SQLite calls this
197773** routine to find out if it has reached the end of a result set.
197774*/
197775static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
197776  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197777  return pCsr->bEof;
197778}
197779
197780static int fts5VocabColumnMethod(
197781  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
197782  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
197783  int iCol                        /* Index of column to read value from */
197784){
197785  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197786  int eDetail = pCsr->pConfig->eDetail;
197787  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
197788  i64 iVal = 0;
197789
197790  if( iCol==0 ){
197791    sqlite3_result_text(
197792        pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
197793    );
197794  }else if( eType==FTS5_VOCAB_COL ){
197795    assert( iCol==1 || iCol==2 || iCol==3 );
197796    if( iCol==1 ){
197797      if( eDetail!=FTS5_DETAIL_NONE ){
197798        const char *z = pCsr->pConfig->azCol[pCsr->iCol];
197799        sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
197800      }
197801    }else if( iCol==2 ){
197802      iVal = pCsr->aDoc[pCsr->iCol];
197803    }else{
197804      iVal = pCsr->aCnt[pCsr->iCol];
197805    }
197806  }else{
197807    assert( iCol==1 || iCol==2 );
197808    if( iCol==1 ){
197809      iVal = pCsr->aDoc[0];
197810    }else{
197811      iVal = pCsr->aCnt[0];
197812    }
197813  }
197814
197815  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
197816  return SQLITE_OK;
197817}
197818
197819/*
197820** This is the xRowid method. The SQLite core calls this routine to
197821** retrieve the rowid for the current row of the result set. The
197822** rowid should be written to *pRowid.
197823*/
197824static int fts5VocabRowidMethod(
197825  sqlite3_vtab_cursor *pCursor,
197826  sqlite_int64 *pRowid
197827){
197828  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197829  *pRowid = pCsr->rowid;
197830  return SQLITE_OK;
197831}
197832
197833static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
197834  static const sqlite3_module fts5Vocab = {
197835    /* iVersion      */ 2,
197836    /* xCreate       */ fts5VocabCreateMethod,
197837    /* xConnect      */ fts5VocabConnectMethod,
197838    /* xBestIndex    */ fts5VocabBestIndexMethod,
197839    /* xDisconnect   */ fts5VocabDisconnectMethod,
197840    /* xDestroy      */ fts5VocabDestroyMethod,
197841    /* xOpen         */ fts5VocabOpenMethod,
197842    /* xClose        */ fts5VocabCloseMethod,
197843    /* xFilter       */ fts5VocabFilterMethod,
197844    /* xNext         */ fts5VocabNextMethod,
197845    /* xEof          */ fts5VocabEofMethod,
197846    /* xColumn       */ fts5VocabColumnMethod,
197847    /* xRowid        */ fts5VocabRowidMethod,
197848    /* xUpdate       */ 0,
197849    /* xBegin        */ 0,
197850    /* xSync         */ 0,
197851    /* xCommit       */ 0,
197852    /* xRollback     */ 0,
197853    /* xFindFunction */ 0,
197854    /* xRename       */ 0,
197855    /* xSavepoint    */ 0,
197856    /* xRelease      */ 0,
197857    /* xRollbackTo   */ 0,
197858  };
197859  void *p = (void*)pGlobal;
197860
197861  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
197862}
197863
197864
197865
197866
197867
197868#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
197869
197870/************** End of fts5.c ************************************************/
197871